1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/EHPersonalities.h" 31 #include "llvm/Analysis/Loads.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/ProfileSummaryInfo.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/Analysis/VectorUtils.h" 37 #include "llvm/CodeGen/Analysis.h" 38 #include "llvm/CodeGen/FunctionLoweringInfo.h" 39 #include "llvm/CodeGen/GCMetadata.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 53 #include "llvm/CodeGen/StackMaps.h" 54 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 55 #include "llvm/CodeGen/TargetFrameLowering.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetOpcodes.h" 58 #include "llvm/CodeGen/TargetRegisterInfo.h" 59 #include "llvm/CodeGen/TargetSubtargetInfo.h" 60 #include "llvm/CodeGen/WinEHFuncInfo.h" 61 #include "llvm/IR/Argument.h" 62 #include "llvm/IR/Attributes.h" 63 #include "llvm/IR/BasicBlock.h" 64 #include "llvm/IR/CFG.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/ConstantRange.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugInfoMetadata.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/MC/MCSymbol.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/MathExtras.h" 98 #include "llvm/Support/raw_ostream.h" 99 #include "llvm/Target/TargetIntrinsicInfo.h" 100 #include "llvm/Target/TargetMachine.h" 101 #include "llvm/Target/TargetOptions.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <cstring> 105 #include <iterator> 106 #include <limits> 107 #include <numeric> 108 #include <tuple> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 using namespace SwitchCG; 113 114 #define DEBUG_TYPE "isel" 115 116 /// LimitFloatPrecision - Generate low-precision inline sequences for 117 /// some float libcalls (6, 8 or 12 bits). 118 static unsigned LimitFloatPrecision; 119 120 static cl::opt<bool> 121 InsertAssertAlign("insert-assert-align", cl::init(true), 122 cl::desc("Insert the experimental `assertalign` node."), 123 cl::ReallyHidden); 124 125 static cl::opt<unsigned, true> 126 LimitFPPrecision("limit-float-precision", 127 cl::desc("Generate low-precision inline sequences " 128 "for some float libcalls"), 129 cl::location(LimitFloatPrecision), cl::Hidden, 130 cl::init(0)); 131 132 static cl::opt<unsigned> SwitchPeelThreshold( 133 "switch-peel-threshold", cl::Hidden, cl::init(66), 134 cl::desc("Set the case probability threshold for peeling the case from a " 135 "switch statement. A value greater than 100 will void this " 136 "optimization")); 137 138 // Limit the width of DAG chains. This is important in general to prevent 139 // DAG-based analysis from blowing up. For example, alias analysis and 140 // load clustering may not complete in reasonable time. It is difficult to 141 // recognize and avoid this situation within each individual analysis, and 142 // future analyses are likely to have the same behavior. Limiting DAG width is 143 // the safe approach and will be especially important with global DAGs. 144 // 145 // MaxParallelChains default is arbitrarily high to avoid affecting 146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 147 // sequence over this should have been converted to llvm.memcpy by the 148 // frontend. It is easy to induce this behavior with .ll code such as: 149 // %buffer = alloca [4096 x i8] 150 // %data = load [4096 x i8]* %argPtr 151 // store [4096 x i8] %data, [4096 x i8]* %buffer 152 static const unsigned MaxParallelChains = 64; 153 154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 155 const SDValue *Parts, unsigned NumParts, 156 MVT PartVT, EVT ValueVT, const Value *V, 157 Optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 165 const SDValue *Parts, unsigned NumParts, 166 MVT PartVT, EVT ValueVT, const Value *V, 167 Optional<CallingConv::ID> CC = None, 168 Optional<ISD::NodeType> AssertOp = None) { 169 // Let the target assemble the parts if it wants to 170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 171 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 172 PartVT, ValueVT, CC)) 173 return Val; 174 175 if (ValueVT.isVector()) 176 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 177 CC); 178 179 assert(NumParts > 0 && "No parts to assemble!"); 180 SDValue Val = Parts[0]; 181 182 if (NumParts > 1) { 183 // Assemble the value from multiple parts. 184 if (ValueVT.isInteger()) { 185 unsigned PartBits = PartVT.getSizeInBits(); 186 unsigned ValueBits = ValueVT.getSizeInBits(); 187 188 // Assemble the power of 2 part. 189 unsigned RoundParts = 190 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 200 PartVT, HalfVT, V); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 202 RoundParts / 2, PartVT, HalfVT, V); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = 227 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 228 DAG.getConstant(Lo.getValueSizeInBits(), DL, 229 TLI.getPointerTy(DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 249 } 250 } 251 252 // There is now one part, held in Val. Correct it to match ValueVT. 253 // PartEVT is the type of the register class that holds the value. 254 // ValueVT is the type of the inline asm operation. 255 EVT PartEVT = Val.getValueType(); 256 257 if (PartEVT == ValueVT) 258 return Val; 259 260 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 261 ValueVT.bitsLT(PartEVT)) { 262 // For an FP value in an integer part, we need to truncate to the right 263 // width first. 264 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 265 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 266 } 267 268 // Handle types that have the same size. 269 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 270 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 271 272 // Handle types with different sizes. 273 if (PartEVT.isInteger() && ValueVT.isInteger()) { 274 if (ValueVT.bitsLT(PartEVT)) { 275 // For a truncate, see if we have any information to 276 // indicate whether the truncated bits will always be 277 // zero or sign-extension. 278 if (AssertOp.hasValue()) 279 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 280 DAG.getValueType(ValueVT)); 281 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 282 } 283 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 284 } 285 286 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 287 // FP_ROUND's are always exact here. 288 if (ValueVT.bitsLT(Val.getValueType())) 289 return DAG.getNode( 290 ISD::FP_ROUND, DL, ValueVT, Val, 291 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 292 293 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 294 } 295 296 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 297 // then truncating. 298 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 299 ValueVT.bitsLT(PartEVT)) { 300 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 301 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 302 } 303 304 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 305 } 306 307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 308 const Twine &ErrMsg) { 309 const Instruction *I = dyn_cast_or_null<Instruction>(V); 310 if (!V) 311 return Ctx.emitError(ErrMsg); 312 313 const char *AsmError = ", possible invalid constraint for vector type"; 314 if (const CallInst *CI = dyn_cast<CallInst>(I)) 315 if (CI->isInlineAsm()) 316 return Ctx.emitError(I, ErrMsg + AsmError); 317 318 return Ctx.emitError(I, ErrMsg); 319 } 320 321 /// getCopyFromPartsVector - Create a value that contains the specified legal 322 /// parts combined into the value they represent. If the parts combine to a 323 /// type larger than ValueVT then AssertOp can be used to specify whether the 324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 325 /// ValueVT (ISD::AssertSext). 326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 327 const SDValue *Parts, unsigned NumParts, 328 MVT PartVT, EVT ValueVT, const Value *V, 329 Optional<CallingConv::ID> CallConv) { 330 assert(ValueVT.isVector() && "Not a vector value"); 331 assert(NumParts > 0 && "No parts to assemble!"); 332 const bool IsABIRegCopy = CallConv.hasValue(); 333 334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 335 SDValue Val = Parts[0]; 336 337 // Handle a multi-element vector. 338 if (NumParts > 1) { 339 EVT IntermediateVT; 340 MVT RegisterVT; 341 unsigned NumIntermediates; 342 unsigned NumRegs; 343 344 if (IsABIRegCopy) { 345 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 346 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } else { 349 NumRegs = 350 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 351 NumIntermediates, RegisterVT); 352 } 353 354 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 355 NumParts = NumRegs; // Silence a compiler warning. 356 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 357 assert(RegisterVT.getSizeInBits() == 358 Parts[0].getSimpleValueType().getSizeInBits() && 359 "Part type sizes don't match!"); 360 361 // Assemble the parts into intermediate operands. 362 SmallVector<SDValue, 8> Ops(NumIntermediates); 363 if (NumIntermediates == NumParts) { 364 // If the register was not expanded, truncate or copy the value, 365 // as appropriate. 366 for (unsigned i = 0; i != NumParts; ++i) 367 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 368 PartVT, IntermediateVT, V, CallConv); 369 } else if (NumParts > 0) { 370 // If the intermediate type was expanded, build the intermediate 371 // operands from the parts. 372 assert(NumParts % NumIntermediates == 0 && 373 "Must expand into a divisible number of parts!"); 374 unsigned Factor = NumParts / NumIntermediates; 375 for (unsigned i = 0; i != NumIntermediates; ++i) 376 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 377 PartVT, IntermediateVT, V, CallConv); 378 } 379 380 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 381 // intermediate operands. 382 EVT BuiltVectorTy = 383 IntermediateVT.isVector() 384 ? EVT::getVectorVT( 385 *DAG.getContext(), IntermediateVT.getScalarType(), 386 IntermediateVT.getVectorElementCount() * NumParts) 387 : EVT::getVectorVT(*DAG.getContext(), 388 IntermediateVT.getScalarType(), 389 NumIntermediates); 390 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 391 : ISD::BUILD_VECTOR, 392 DL, BuiltVectorTy, Ops); 393 } 394 395 // There is now one part, held in Val. Correct it to match ValueVT. 396 EVT PartEVT = Val.getValueType(); 397 398 if (PartEVT == ValueVT) 399 return Val; 400 401 if (PartEVT.isVector()) { 402 // If the element type of the source/dest vectors are the same, but the 403 // parts vector has more elements than the value vector, then we have a 404 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 405 // elements we want. 406 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 407 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 408 ValueVT.getVectorElementCount().getKnownMinValue()) && 409 (PartEVT.getVectorElementCount().isScalable() == 410 ValueVT.getVectorElementCount().isScalable()) && 411 "Cannot narrow, it would be a lossy transformation"); 412 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 413 DAG.getVectorIdxConstant(0, DL)); 414 } 415 416 // Vector/Vector bitcast. 417 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 420 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 421 "Cannot handle this kind of promotion"); 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 425 } 426 427 // Trivial bitcast if the types are the same size and the destination 428 // vector type is legal. 429 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 430 TLI.isTypeLegal(ValueVT)) 431 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 432 433 if (ValueVT.getVectorNumElements() != 1) { 434 // Certain ABIs require that vectors are passed as integers. For vectors 435 // are the same size, this is an obvious bitcast. 436 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 437 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 438 } else if (ValueVT.bitsLT(PartEVT)) { 439 // Bitcast Val back the original type and extract the corresponding 440 // vector we want. 441 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 442 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 443 ValueVT.getVectorElementType(), Elts); 444 Val = DAG.getBitcast(WiderVecType, Val); 445 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 446 DAG.getVectorIdxConstant(0, DL)); 447 } 448 449 diagnosePossiblyInvalidConstraint( 450 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 451 return DAG.getUNDEF(ValueVT); 452 } 453 454 // Handle cases such as i8 -> <1 x i1> 455 EVT ValueSVT = ValueVT.getVectorElementType(); 456 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 457 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 458 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 459 else 460 Val = ValueVT.isFloatingPoint() 461 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 462 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 463 } 464 465 return DAG.getBuildVector(ValueVT, DL, Val); 466 } 467 468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 469 SDValue Val, SDValue *Parts, unsigned NumParts, 470 MVT PartVT, const Value *V, 471 Optional<CallingConv::ID> CallConv); 472 473 /// getCopyToParts - Create a series of nodes that contain the specified value 474 /// split into legal parts. If the parts contain more bits than Val, then, for 475 /// integers, ExtendKind can be used to specify how to generate the extra bits. 476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 477 SDValue *Parts, unsigned NumParts, MVT PartVT, 478 const Value *V, 479 Optional<CallingConv::ID> CallConv = None, 480 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 481 // Let the target split the parts if it wants to 482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 483 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 484 CallConv)) 485 return; 486 EVT ValueVT = Val.getValueType(); 487 488 // Handle the vector case separately. 489 if (ValueVT.isVector()) 490 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 491 CallConv); 492 493 unsigned PartBits = PartVT.getSizeInBits(); 494 unsigned OrigNumParts = NumParts; 495 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 496 "Copying to an illegal type!"); 497 498 if (NumParts == 0) 499 return; 500 501 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 502 EVT PartEVT = PartVT; 503 if (PartEVT == ValueVT) { 504 assert(NumParts == 1 && "No-op copy with multiple parts!"); 505 Parts[0] = Val; 506 return; 507 } 508 509 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 510 // If the parts cover more bits than the value has, promote the value. 511 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 512 assert(NumParts == 1 && "Do not know what to promote to!"); 513 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 514 } else { 515 if (ValueVT.isFloatingPoint()) { 516 // FP values need to be bitcast, then extended if they are being put 517 // into a larger container. 518 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 519 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 520 } 521 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 522 ValueVT.isInteger() && 523 "Unknown mismatch!"); 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 525 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 526 if (PartVT == MVT::x86mmx) 527 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 528 } 529 } else if (PartBits == ValueVT.getSizeInBits()) { 530 // Different types of the same size. 531 assert(NumParts == 1 && PartEVT != ValueVT); 532 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 533 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 534 // If the parts cover less bits than value has, truncate the value. 535 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 536 ValueVT.isInteger() && 537 "Unknown mismatch!"); 538 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 539 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 540 if (PartVT == MVT::x86mmx) 541 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 542 } 543 544 // The value may have changed - recompute ValueVT. 545 ValueVT = Val.getValueType(); 546 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 547 "Failed to tile the value with PartVT!"); 548 549 if (NumParts == 1) { 550 if (PartEVT != ValueVT) { 551 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 552 "scalar-to-vector conversion failed"); 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 556 Parts[0] = Val; 557 return; 558 } 559 560 // Expand the value into multiple parts. 561 if (NumParts & (NumParts - 1)) { 562 // The number of parts is not a power of 2. Split off and copy the tail. 563 assert(PartVT.isInteger() && ValueVT.isInteger() && 564 "Do not know what to expand to!"); 565 unsigned RoundParts = 1 << Log2_32(NumParts); 566 unsigned RoundBits = RoundParts * PartBits; 567 unsigned OddParts = NumParts - RoundParts; 568 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 569 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 570 571 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 572 CallConv); 573 574 if (DAG.getDataLayout().isBigEndian()) 575 // The odd parts were reversed by getCopyToParts - unreverse them. 576 std::reverse(Parts + RoundParts, Parts + NumParts); 577 578 NumParts = RoundParts; 579 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 580 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 581 } 582 583 // The number of parts is a power of 2. Repeatedly bisect the value using 584 // EXTRACT_ELEMENT. 585 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 586 EVT::getIntegerVT(*DAG.getContext(), 587 ValueVT.getSizeInBits()), 588 Val); 589 590 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 591 for (unsigned i = 0; i < NumParts; i += StepSize) { 592 unsigned ThisBits = StepSize * PartBits / 2; 593 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 594 SDValue &Part0 = Parts[i]; 595 SDValue &Part1 = Parts[i+StepSize/2]; 596 597 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 598 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 599 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 600 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 601 602 if (ThisBits == PartBits && ThisVT != PartVT) { 603 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 604 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 605 } 606 } 607 } 608 609 if (DAG.getDataLayout().isBigEndian()) 610 std::reverse(Parts, Parts + OrigNumParts); 611 } 612 613 static SDValue widenVectorToPartType(SelectionDAG &DAG, 614 SDValue Val, const SDLoc &DL, EVT PartVT) { 615 if (!PartVT.isFixedLengthVector()) 616 return SDValue(); 617 618 EVT ValueVT = Val.getValueType(); 619 unsigned PartNumElts = PartVT.getVectorNumElements(); 620 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 621 if (PartNumElts > ValueNumElts && 622 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 623 EVT ElementVT = PartVT.getVectorElementType(); 624 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 625 // undef elements. 626 SmallVector<SDValue, 16> Ops; 627 DAG.ExtractVectorElements(Val, Ops); 628 SDValue EltUndef = DAG.getUNDEF(ElementVT); 629 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 630 Ops.push_back(EltUndef); 631 632 // FIXME: Use CONCAT for 2x -> 4x. 633 return DAG.getBuildVector(PartVT, DL, Ops); 634 } 635 636 return SDValue(); 637 } 638 639 /// getCopyToPartsVector - Create a series of nodes that contain the specified 640 /// value split into legal parts. 641 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 642 SDValue Val, SDValue *Parts, unsigned NumParts, 643 MVT PartVT, const Value *V, 644 Optional<CallingConv::ID> CallConv) { 645 EVT ValueVT = Val.getValueType(); 646 assert(ValueVT.isVector() && "Not a vector"); 647 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 648 const bool IsABIRegCopy = CallConv.hasValue(); 649 650 if (NumParts == 1) { 651 EVT PartEVT = PartVT; 652 if (PartEVT == ValueVT) { 653 // Nothing to do. 654 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 655 // Bitconvert vector->vector case. 656 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 657 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 658 Val = Widened; 659 } else if (PartVT.isVector() && 660 PartEVT.getVectorElementType().bitsGE( 661 ValueVT.getVectorElementType()) && 662 PartEVT.getVectorElementCount() == 663 ValueVT.getVectorElementCount()) { 664 665 // Promoted vector extract 666 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 667 } else { 668 if (ValueVT.getVectorElementCount().isScalar()) { 669 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 670 DAG.getVectorIdxConstant(0, DL)); 671 } else { 672 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 673 assert(PartVT.getFixedSizeInBits() > ValueSize && 674 "lossy conversion of vector to scalar type"); 675 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 676 Val = DAG.getBitcast(IntermediateType, Val); 677 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 678 } 679 } 680 681 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 682 Parts[0] = Val; 683 return; 684 } 685 686 // Handle a multi-element vector. 687 EVT IntermediateVT; 688 MVT RegisterVT; 689 unsigned NumIntermediates; 690 unsigned NumRegs; 691 if (IsABIRegCopy) { 692 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 693 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 694 NumIntermediates, RegisterVT); 695 } else { 696 NumRegs = 697 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 698 NumIntermediates, RegisterVT); 699 } 700 701 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 702 NumParts = NumRegs; // Silence a compiler warning. 703 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 704 705 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 706 "Mixing scalable and fixed vectors when copying in parts"); 707 708 Optional<ElementCount> DestEltCnt; 709 710 if (IntermediateVT.isVector()) 711 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 712 else 713 DestEltCnt = ElementCount::getFixed(NumIntermediates); 714 715 EVT BuiltVectorTy = EVT::getVectorVT( 716 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 717 if (ValueVT != BuiltVectorTy) { 718 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 719 Val = Widened; 720 721 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 722 } 723 724 // Split the vector into intermediate operands. 725 SmallVector<SDValue, 8> Ops(NumIntermediates); 726 for (unsigned i = 0; i != NumIntermediates; ++i) { 727 if (IntermediateVT.isVector()) { 728 // This does something sensible for scalable vectors - see the 729 // definition of EXTRACT_SUBVECTOR for further details. 730 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 731 Ops[i] = 732 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 733 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 734 } else { 735 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 736 DAG.getVectorIdxConstant(i, DL)); 737 } 738 } 739 740 // Split the intermediate operands into legal parts. 741 if (NumParts == NumIntermediates) { 742 // If the register was not expanded, promote or copy the value, 743 // as appropriate. 744 for (unsigned i = 0; i != NumParts; ++i) 745 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 746 } else if (NumParts > 0) { 747 // If the intermediate type was expanded, split each the value into 748 // legal parts. 749 assert(NumIntermediates != 0 && "division by zero"); 750 assert(NumParts % NumIntermediates == 0 && 751 "Must expand into a divisible number of parts!"); 752 unsigned Factor = NumParts / NumIntermediates; 753 for (unsigned i = 0; i != NumIntermediates; ++i) 754 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 755 CallConv); 756 } 757 } 758 759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 760 EVT valuevt, Optional<CallingConv::ID> CC) 761 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 762 RegCount(1, regs.size()), CallConv(CC) {} 763 764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 765 const DataLayout &DL, unsigned Reg, Type *Ty, 766 Optional<CallingConv::ID> CC) { 767 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 768 769 CallConv = CC; 770 771 for (EVT ValueVT : ValueVTs) { 772 unsigned NumRegs = 773 isABIMangled() 774 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 775 : TLI.getNumRegisters(Context, ValueVT); 776 MVT RegisterVT = 777 isABIMangled() 778 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 779 : TLI.getRegisterType(Context, ValueVT); 780 for (unsigned i = 0; i != NumRegs; ++i) 781 Regs.push_back(Reg + i); 782 RegVTs.push_back(RegisterVT); 783 RegCount.push_back(NumRegs); 784 Reg += NumRegs; 785 } 786 } 787 788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 789 FunctionLoweringInfo &FuncInfo, 790 const SDLoc &dl, SDValue &Chain, 791 SDValue *Flag, const Value *V) const { 792 // A Value with type {} or [0 x %t] needs no registers. 793 if (ValueVTs.empty()) 794 return SDValue(); 795 796 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 797 798 // Assemble the legal parts into the final values. 799 SmallVector<SDValue, 4> Values(ValueVTs.size()); 800 SmallVector<SDValue, 8> Parts; 801 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 802 // Copy the legal parts from the registers. 803 EVT ValueVT = ValueVTs[Value]; 804 unsigned NumRegs = RegCount[Value]; 805 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 806 *DAG.getContext(), 807 CallConv.getValue(), RegVTs[Value]) 808 : RegVTs[Value]; 809 810 Parts.resize(NumRegs); 811 for (unsigned i = 0; i != NumRegs; ++i) { 812 SDValue P; 813 if (!Flag) { 814 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 815 } else { 816 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 817 *Flag = P.getValue(2); 818 } 819 820 Chain = P.getValue(1); 821 Parts[i] = P; 822 823 // If the source register was virtual and if we know something about it, 824 // add an assert node. 825 if (!Register::isVirtualRegister(Regs[Part + i]) || 826 !RegisterVT.isInteger()) 827 continue; 828 829 const FunctionLoweringInfo::LiveOutInfo *LOI = 830 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 831 if (!LOI) 832 continue; 833 834 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 835 unsigned NumSignBits = LOI->NumSignBits; 836 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 837 838 if (NumZeroBits == RegSize) { 839 // The current value is a zero. 840 // Explicitly express that as it would be easier for 841 // optimizations to kick in. 842 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 843 continue; 844 } 845 846 // FIXME: We capture more information than the dag can represent. For 847 // now, just use the tightest assertzext/assertsext possible. 848 bool isSExt; 849 EVT FromVT(MVT::Other); 850 if (NumZeroBits) { 851 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 852 isSExt = false; 853 } else if (NumSignBits > 1) { 854 FromVT = 855 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 856 isSExt = true; 857 } else { 858 continue; 859 } 860 // Add an assertion node. 861 assert(FromVT != MVT::Other); 862 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 863 RegisterVT, P, DAG.getValueType(FromVT)); 864 } 865 866 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 867 RegisterVT, ValueVT, V, CallConv); 868 Part += NumRegs; 869 Parts.clear(); 870 } 871 872 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 873 } 874 875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 876 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 877 const Value *V, 878 ISD::NodeType PreferredExtendType) const { 879 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 880 ISD::NodeType ExtendKind = PreferredExtendType; 881 882 // Get the list of the values's legal parts. 883 unsigned NumRegs = Regs.size(); 884 SmallVector<SDValue, 8> Parts(NumRegs); 885 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 886 unsigned NumParts = RegCount[Value]; 887 888 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 889 *DAG.getContext(), 890 CallConv.getValue(), RegVTs[Value]) 891 : RegVTs[Value]; 892 893 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 894 ExtendKind = ISD::ZERO_EXTEND; 895 896 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 897 NumParts, RegisterVT, V, CallConv, ExtendKind); 898 Part += NumParts; 899 } 900 901 // Copy the parts into the registers. 902 SmallVector<SDValue, 8> Chains(NumRegs); 903 for (unsigned i = 0; i != NumRegs; ++i) { 904 SDValue Part; 905 if (!Flag) { 906 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 907 } else { 908 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 909 *Flag = Part.getValue(1); 910 } 911 912 Chains[i] = Part.getValue(0); 913 } 914 915 if (NumRegs == 1 || Flag) 916 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 917 // flagged to it. That is the CopyToReg nodes and the user are considered 918 // a single scheduling unit. If we create a TokenFactor and return it as 919 // chain, then the TokenFactor is both a predecessor (operand) of the 920 // user as well as a successor (the TF operands are flagged to the user). 921 // c1, f1 = CopyToReg 922 // c2, f2 = CopyToReg 923 // c3 = TokenFactor c1, c2 924 // ... 925 // = op c3, ..., f2 926 Chain = Chains[NumRegs-1]; 927 else 928 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 929 } 930 931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 932 unsigned MatchingIdx, const SDLoc &dl, 933 SelectionDAG &DAG, 934 std::vector<SDValue> &Ops) const { 935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 936 937 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 938 if (HasMatching) 939 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 940 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 941 // Put the register class of the virtual registers in the flag word. That 942 // way, later passes can recompute register class constraints for inline 943 // assembly as well as normal instructions. 944 // Don't do this for tied operands that can use the regclass information 945 // from the def. 946 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 947 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 948 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 949 } 950 951 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 952 Ops.push_back(Res); 953 954 if (Code == InlineAsm::Kind_Clobber) { 955 // Clobbers should always have a 1:1 mapping with registers, and may 956 // reference registers that have illegal (e.g. vector) types. Hence, we 957 // shouldn't try to apply any sort of splitting logic to them. 958 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 959 "No 1:1 mapping from clobbers to regs?"); 960 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 961 (void)SP; 962 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 963 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 964 assert( 965 (Regs[I] != SP || 966 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 967 "If we clobbered the stack pointer, MFI should know about it."); 968 } 969 return; 970 } 971 972 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 973 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 974 MVT RegisterVT = RegVTs[Value]; 975 for (unsigned i = 0; i != NumRegs; ++i) { 976 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 977 unsigned TheReg = Regs[Reg++]; 978 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 979 } 980 } 981 } 982 983 SmallVector<std::pair<unsigned, TypeSize>, 4> 984 RegsForValue::getRegsAndSizes() const { 985 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 986 unsigned I = 0; 987 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 988 unsigned RegCount = std::get<0>(CountAndVT); 989 MVT RegisterVT = std::get<1>(CountAndVT); 990 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 991 for (unsigned E = I + RegCount; I != E; ++I) 992 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 993 } 994 return OutVec; 995 } 996 997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 998 const TargetLibraryInfo *li) { 999 AA = aa; 1000 GFI = gfi; 1001 LibInfo = li; 1002 DL = &DAG.getDataLayout(); 1003 Context = DAG.getContext(); 1004 LPadToCallSiteMap.clear(); 1005 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1006 } 1007 1008 void SelectionDAGBuilder::clear() { 1009 NodeMap.clear(); 1010 UnusedArgNodeMap.clear(); 1011 PendingLoads.clear(); 1012 PendingExports.clear(); 1013 PendingConstrainedFP.clear(); 1014 PendingConstrainedFPStrict.clear(); 1015 CurInst = nullptr; 1016 HasTailCall = false; 1017 SDNodeOrder = LowestSDNodeOrder; 1018 StatepointLowering.clear(); 1019 } 1020 1021 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1022 DanglingDebugInfoMap.clear(); 1023 } 1024 1025 // Update DAG root to include dependencies on Pending chains. 1026 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1027 SDValue Root = DAG.getRoot(); 1028 1029 if (Pending.empty()) 1030 return Root; 1031 1032 // Add current root to PendingChains, unless we already indirectly 1033 // depend on it. 1034 if (Root.getOpcode() != ISD::EntryToken) { 1035 unsigned i = 0, e = Pending.size(); 1036 for (; i != e; ++i) { 1037 assert(Pending[i].getNode()->getNumOperands() > 1); 1038 if (Pending[i].getNode()->getOperand(0) == Root) 1039 break; // Don't add the root if we already indirectly depend on it. 1040 } 1041 1042 if (i == e) 1043 Pending.push_back(Root); 1044 } 1045 1046 if (Pending.size() == 1) 1047 Root = Pending[0]; 1048 else 1049 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1050 1051 DAG.setRoot(Root); 1052 Pending.clear(); 1053 return Root; 1054 } 1055 1056 SDValue SelectionDAGBuilder::getMemoryRoot() { 1057 return updateRoot(PendingLoads); 1058 } 1059 1060 SDValue SelectionDAGBuilder::getRoot() { 1061 // Chain up all pending constrained intrinsics together with all 1062 // pending loads, by simply appending them to PendingLoads and 1063 // then calling getMemoryRoot(). 1064 PendingLoads.reserve(PendingLoads.size() + 1065 PendingConstrainedFP.size() + 1066 PendingConstrainedFPStrict.size()); 1067 PendingLoads.append(PendingConstrainedFP.begin(), 1068 PendingConstrainedFP.end()); 1069 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1070 PendingConstrainedFPStrict.end()); 1071 PendingConstrainedFP.clear(); 1072 PendingConstrainedFPStrict.clear(); 1073 return getMemoryRoot(); 1074 } 1075 1076 SDValue SelectionDAGBuilder::getControlRoot() { 1077 // We need to emit pending fpexcept.strict constrained intrinsics, 1078 // so append them to the PendingExports list. 1079 PendingExports.append(PendingConstrainedFPStrict.begin(), 1080 PendingConstrainedFPStrict.end()); 1081 PendingConstrainedFPStrict.clear(); 1082 return updateRoot(PendingExports); 1083 } 1084 1085 void SelectionDAGBuilder::visit(const Instruction &I) { 1086 // Set up outgoing PHI node register values before emitting the terminator. 1087 if (I.isTerminator()) { 1088 HandlePHINodesInSuccessorBlocks(I.getParent()); 1089 } 1090 1091 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1092 if (!isa<DbgInfoIntrinsic>(I)) 1093 ++SDNodeOrder; 1094 1095 CurInst = &I; 1096 1097 visit(I.getOpcode(), I); 1098 1099 if (!I.isTerminator() && !HasTailCall && 1100 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1101 CopyToExportRegsIfNeeded(&I); 1102 1103 CurInst = nullptr; 1104 } 1105 1106 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1107 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1108 } 1109 1110 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1111 // Note: this doesn't use InstVisitor, because it has to work with 1112 // ConstantExpr's in addition to instructions. 1113 switch (Opcode) { 1114 default: llvm_unreachable("Unknown instruction type encountered!"); 1115 // Build the switch statement using the Instruction.def file. 1116 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1117 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1118 #include "llvm/IR/Instruction.def" 1119 } 1120 } 1121 1122 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1123 DebugLoc DL, unsigned Order) { 1124 // We treat variadic dbg_values differently at this stage. 1125 if (DI->hasArgList()) { 1126 // For variadic dbg_values we will now insert an undef. 1127 // FIXME: We can potentially recover these! 1128 SmallVector<SDDbgOperand, 2> Locs; 1129 for (const Value *V : DI->getValues()) { 1130 auto Undef = UndefValue::get(V->getType()); 1131 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1132 } 1133 SDDbgValue *SDV = DAG.getDbgValueList( 1134 DI->getVariable(), DI->getExpression(), Locs, {}, 1135 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1136 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1137 } else { 1138 // TODO: Dangling debug info will eventually either be resolved or produce 1139 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1140 // between the original dbg.value location and its resolved DBG_VALUE, 1141 // which we should ideally fill with an extra Undef DBG_VALUE. 1142 assert(DI->getNumVariableLocationOps() == 1 && 1143 "DbgValueInst without an ArgList should have a single location " 1144 "operand."); 1145 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1146 } 1147 } 1148 1149 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1150 const DIExpression *Expr) { 1151 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1152 const DbgValueInst *DI = DDI.getDI(); 1153 DIVariable *DanglingVariable = DI->getVariable(); 1154 DIExpression *DanglingExpr = DI->getExpression(); 1155 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1156 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1157 return true; 1158 } 1159 return false; 1160 }; 1161 1162 for (auto &DDIMI : DanglingDebugInfoMap) { 1163 DanglingDebugInfoVector &DDIV = DDIMI.second; 1164 1165 // If debug info is to be dropped, run it through final checks to see 1166 // whether it can be salvaged. 1167 for (auto &DDI : DDIV) 1168 if (isMatchingDbgValue(DDI)) 1169 salvageUnresolvedDbgValue(DDI); 1170 1171 erase_if(DDIV, isMatchingDbgValue); 1172 } 1173 } 1174 1175 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1176 // generate the debug data structures now that we've seen its definition. 1177 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1178 SDValue Val) { 1179 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1180 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1181 return; 1182 1183 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1184 for (auto &DDI : DDIV) { 1185 const DbgValueInst *DI = DDI.getDI(); 1186 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1187 assert(DI && "Ill-formed DanglingDebugInfo"); 1188 DebugLoc dl = DDI.getdl(); 1189 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1190 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1191 DILocalVariable *Variable = DI->getVariable(); 1192 DIExpression *Expr = DI->getExpression(); 1193 assert(Variable->isValidLocationForIntrinsic(dl) && 1194 "Expected inlined-at fields to agree"); 1195 SDDbgValue *SDV; 1196 if (Val.getNode()) { 1197 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1198 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1199 // we couldn't resolve it directly when examining the DbgValue intrinsic 1200 // in the first place we should not be more successful here). Unless we 1201 // have some test case that prove this to be correct we should avoid 1202 // calling EmitFuncArgumentDbgValue here. 1203 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1204 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1205 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1206 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1207 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1208 // inserted after the definition of Val when emitting the instructions 1209 // after ISel. An alternative could be to teach 1210 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1211 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1212 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1213 << ValSDNodeOrder << "\n"); 1214 SDV = getDbgValue(Val, Variable, Expr, dl, 1215 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1216 DAG.AddDbgValue(SDV, false); 1217 } else 1218 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1219 << "in EmitFuncArgumentDbgValue\n"); 1220 } else { 1221 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1222 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1223 auto SDV = 1224 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1225 DAG.AddDbgValue(SDV, false); 1226 } 1227 } 1228 DDIV.clear(); 1229 } 1230 1231 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1232 assert(!DDI.getDI()->hasArgList() && 1233 "Not implemented for variadic dbg_values"); 1234 Value *V = DDI.getDI()->getValue(0); 1235 DILocalVariable *Var = DDI.getDI()->getVariable(); 1236 DIExpression *Expr = DDI.getDI()->getExpression(); 1237 DebugLoc DL = DDI.getdl(); 1238 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1239 unsigned SDOrder = DDI.getSDNodeOrder(); 1240 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1241 // that DW_OP_stack_value is desired. 1242 assert(isa<DbgValueInst>(DDI.getDI())); 1243 bool StackValue = true; 1244 1245 // Can this Value can be encoded without any further work? 1246 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1247 return; 1248 1249 // Attempt to salvage back through as many instructions as possible. Bail if 1250 // a non-instruction is seen, such as a constant expression or global 1251 // variable. FIXME: Further work could recover those too. 1252 while (isa<Instruction>(V)) { 1253 Instruction &VAsInst = *cast<Instruction>(V); 1254 // Temporary "0", awaiting real implementation. 1255 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0); 1256 1257 // If we cannot salvage any further, and haven't yet found a suitable debug 1258 // expression, bail out. 1259 if (!NewExpr) 1260 break; 1261 1262 // New value and expr now represent this debuginfo. 1263 V = VAsInst.getOperand(0); 1264 Expr = NewExpr; 1265 1266 // Some kind of simplification occurred: check whether the operand of the 1267 // salvaged debug expression can be encoded in this DAG. 1268 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1269 /*IsVariadic=*/false)) { 1270 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1271 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1272 return; 1273 } 1274 } 1275 1276 // This was the final opportunity to salvage this debug information, and it 1277 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1278 // any earlier variable location. 1279 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1280 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1281 DAG.AddDbgValue(SDV, false); 1282 1283 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1284 << "\n"); 1285 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1286 << "\n"); 1287 } 1288 1289 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1290 DILocalVariable *Var, 1291 DIExpression *Expr, DebugLoc dl, 1292 DebugLoc InstDL, unsigned Order, 1293 bool IsVariadic) { 1294 if (Values.empty()) 1295 return true; 1296 SDDbgValue::LocOpVector LocationOps; 1297 SDDbgValue::SDNodeVector Dependencies; 1298 for (const Value *V : Values) { 1299 // Constant value. 1300 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1301 isa<ConstantPointerNull>(V)) { 1302 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1303 continue; 1304 } 1305 1306 // If the Value is a frame index, we can create a FrameIndex debug value 1307 // without relying on the DAG at all. 1308 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1309 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1310 if (SI != FuncInfo.StaticAllocaMap.end()) { 1311 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1312 continue; 1313 } 1314 } 1315 1316 // Do not use getValue() in here; we don't want to generate code at 1317 // this point if it hasn't been done yet. 1318 SDValue N = NodeMap[V]; 1319 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1320 N = UnusedArgNodeMap[V]; 1321 if (N.getNode()) { 1322 // Only emit func arg dbg value for non-variadic dbg.values for now. 1323 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1324 return true; 1325 Dependencies.push_back(N.getNode()); 1326 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1327 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1328 // describe stack slot locations. 1329 // 1330 // Consider "int x = 0; int *px = &x;". There are two kinds of 1331 // interesting debug values here after optimization: 1332 // 1333 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1334 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1335 // 1336 // Both describe the direct values of their associated variables. 1337 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1338 continue; 1339 } 1340 LocationOps.emplace_back( 1341 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1342 continue; 1343 } 1344 1345 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1346 // Special rules apply for the first dbg.values of parameter variables in a 1347 // function. Identify them by the fact they reference Argument Values, that 1348 // they're parameters, and they are parameters of the current function. We 1349 // need to let them dangle until they get an SDNode. 1350 bool IsParamOfFunc = 1351 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1352 if (IsParamOfFunc) 1353 return false; 1354 1355 // The value is not used in this block yet (or it would have an SDNode). 1356 // We still want the value to appear for the user if possible -- if it has 1357 // an associated VReg, we can refer to that instead. 1358 auto VMI = FuncInfo.ValueMap.find(V); 1359 if (VMI != FuncInfo.ValueMap.end()) { 1360 unsigned Reg = VMI->second; 1361 // If this is a PHI node, it may be split up into several MI PHI nodes 1362 // (in FunctionLoweringInfo::set). 1363 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1364 V->getType(), None); 1365 if (RFV.occupiesMultipleRegs()) { 1366 // FIXME: We could potentially support variadic dbg_values here. 1367 if (IsVariadic) 1368 return false; 1369 unsigned Offset = 0; 1370 unsigned BitsToDescribe = 0; 1371 if (auto VarSize = Var->getSizeInBits()) 1372 BitsToDescribe = *VarSize; 1373 if (auto Fragment = Expr->getFragmentInfo()) 1374 BitsToDescribe = Fragment->SizeInBits; 1375 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1376 // Bail out if all bits are described already. 1377 if (Offset >= BitsToDescribe) 1378 break; 1379 // TODO: handle scalable vectors. 1380 unsigned RegisterSize = RegAndSize.second; 1381 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1382 ? BitsToDescribe - Offset 1383 : RegisterSize; 1384 auto FragmentExpr = DIExpression::createFragmentExpression( 1385 Expr, Offset, FragmentSize); 1386 if (!FragmentExpr) 1387 continue; 1388 SDDbgValue *SDV = DAG.getVRegDbgValue( 1389 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1390 DAG.AddDbgValue(SDV, false); 1391 Offset += RegisterSize; 1392 } 1393 return true; 1394 } 1395 // We can use simple vreg locations for variadic dbg_values as well. 1396 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1397 continue; 1398 } 1399 // We failed to create a SDDbgOperand for V. 1400 return false; 1401 } 1402 1403 // We have created a SDDbgOperand for each Value in Values. 1404 // Should use Order instead of SDNodeOrder? 1405 assert(!LocationOps.empty()); 1406 SDDbgValue *SDV = 1407 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1408 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1409 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1410 return true; 1411 } 1412 1413 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1414 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1415 for (auto &Pair : DanglingDebugInfoMap) 1416 for (auto &DDI : Pair.second) 1417 salvageUnresolvedDbgValue(DDI); 1418 clearDanglingDebugInfo(); 1419 } 1420 1421 /// getCopyFromRegs - If there was virtual register allocated for the value V 1422 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1423 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1424 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1425 SDValue Result; 1426 1427 if (It != FuncInfo.ValueMap.end()) { 1428 Register InReg = It->second; 1429 1430 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1431 DAG.getDataLayout(), InReg, Ty, 1432 None); // This is not an ABI copy. 1433 SDValue Chain = DAG.getEntryNode(); 1434 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1435 V); 1436 resolveDanglingDebugInfo(V, Result); 1437 } 1438 1439 return Result; 1440 } 1441 1442 /// getValue - Return an SDValue for the given Value. 1443 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1444 // If we already have an SDValue for this value, use it. It's important 1445 // to do this first, so that we don't create a CopyFromReg if we already 1446 // have a regular SDValue. 1447 SDValue &N = NodeMap[V]; 1448 if (N.getNode()) return N; 1449 1450 // If there's a virtual register allocated and initialized for this 1451 // value, use it. 1452 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1453 return copyFromReg; 1454 1455 // Otherwise create a new SDValue and remember it. 1456 SDValue Val = getValueImpl(V); 1457 NodeMap[V] = Val; 1458 resolveDanglingDebugInfo(V, Val); 1459 return Val; 1460 } 1461 1462 /// getNonRegisterValue - Return an SDValue for the given Value, but 1463 /// don't look in FuncInfo.ValueMap for a virtual register. 1464 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1465 // If we already have an SDValue for this value, use it. 1466 SDValue &N = NodeMap[V]; 1467 if (N.getNode()) { 1468 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1469 // Remove the debug location from the node as the node is about to be used 1470 // in a location which may differ from the original debug location. This 1471 // is relevant to Constant and ConstantFP nodes because they can appear 1472 // as constant expressions inside PHI nodes. 1473 N->setDebugLoc(DebugLoc()); 1474 } 1475 return N; 1476 } 1477 1478 // Otherwise create a new SDValue and remember it. 1479 SDValue Val = getValueImpl(V); 1480 NodeMap[V] = Val; 1481 resolveDanglingDebugInfo(V, Val); 1482 return Val; 1483 } 1484 1485 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1486 /// Create an SDValue for the given value. 1487 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1489 1490 if (const Constant *C = dyn_cast<Constant>(V)) { 1491 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1492 1493 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1494 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1495 1496 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1497 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1498 1499 if (isa<ConstantPointerNull>(C)) { 1500 unsigned AS = V->getType()->getPointerAddressSpace(); 1501 return DAG.getConstant(0, getCurSDLoc(), 1502 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1503 } 1504 1505 if (match(C, m_VScale(DAG.getDataLayout()))) 1506 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1507 1508 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1509 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1510 1511 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1512 return DAG.getUNDEF(VT); 1513 1514 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1515 visit(CE->getOpcode(), *CE); 1516 SDValue N1 = NodeMap[V]; 1517 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1518 return N1; 1519 } 1520 1521 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1522 SmallVector<SDValue, 4> Constants; 1523 for (const Use &U : C->operands()) { 1524 SDNode *Val = getValue(U).getNode(); 1525 // If the operand is an empty aggregate, there are no values. 1526 if (!Val) continue; 1527 // Add each leaf value from the operand to the Constants list 1528 // to form a flattened list of all the values. 1529 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1530 Constants.push_back(SDValue(Val, i)); 1531 } 1532 1533 return DAG.getMergeValues(Constants, getCurSDLoc()); 1534 } 1535 1536 if (const ConstantDataSequential *CDS = 1537 dyn_cast<ConstantDataSequential>(C)) { 1538 SmallVector<SDValue, 4> Ops; 1539 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1540 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1541 // Add each leaf value from the operand to the Constants list 1542 // to form a flattened list of all the values. 1543 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1544 Ops.push_back(SDValue(Val, i)); 1545 } 1546 1547 if (isa<ArrayType>(CDS->getType())) 1548 return DAG.getMergeValues(Ops, getCurSDLoc()); 1549 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1550 } 1551 1552 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1553 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1554 "Unknown struct or array constant!"); 1555 1556 SmallVector<EVT, 4> ValueVTs; 1557 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1558 unsigned NumElts = ValueVTs.size(); 1559 if (NumElts == 0) 1560 return SDValue(); // empty struct 1561 SmallVector<SDValue, 4> Constants(NumElts); 1562 for (unsigned i = 0; i != NumElts; ++i) { 1563 EVT EltVT = ValueVTs[i]; 1564 if (isa<UndefValue>(C)) 1565 Constants[i] = DAG.getUNDEF(EltVT); 1566 else if (EltVT.isFloatingPoint()) 1567 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1568 else 1569 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1570 } 1571 1572 return DAG.getMergeValues(Constants, getCurSDLoc()); 1573 } 1574 1575 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1576 return DAG.getBlockAddress(BA, VT); 1577 1578 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1579 return getValue(Equiv->getGlobalValue()); 1580 1581 VectorType *VecTy = cast<VectorType>(V->getType()); 1582 1583 // Now that we know the number and type of the elements, get that number of 1584 // elements into the Ops array based on what kind of constant it is. 1585 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1586 SmallVector<SDValue, 16> Ops; 1587 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1588 for (unsigned i = 0; i != NumElements; ++i) 1589 Ops.push_back(getValue(CV->getOperand(i))); 1590 1591 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1592 } else if (isa<ConstantAggregateZero>(C)) { 1593 EVT EltVT = 1594 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1595 1596 SDValue Op; 1597 if (EltVT.isFloatingPoint()) 1598 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1599 else 1600 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1601 1602 if (isa<ScalableVectorType>(VecTy)) 1603 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1604 else { 1605 SmallVector<SDValue, 16> Ops; 1606 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1607 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1608 } 1609 } 1610 llvm_unreachable("Unknown vector constant"); 1611 } 1612 1613 // If this is a static alloca, generate it as the frameindex instead of 1614 // computation. 1615 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1616 DenseMap<const AllocaInst*, int>::iterator SI = 1617 FuncInfo.StaticAllocaMap.find(AI); 1618 if (SI != FuncInfo.StaticAllocaMap.end()) 1619 return DAG.getFrameIndex(SI->second, 1620 TLI.getFrameIndexTy(DAG.getDataLayout())); 1621 } 1622 1623 // If this is an instruction which fast-isel has deferred, select it now. 1624 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1625 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1626 1627 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1628 Inst->getType(), None); 1629 SDValue Chain = DAG.getEntryNode(); 1630 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1631 } 1632 1633 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1634 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1635 } 1636 llvm_unreachable("Can't get register for value!"); 1637 } 1638 1639 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1640 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1641 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1642 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1643 bool IsSEH = isAsynchronousEHPersonality(Pers); 1644 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1645 if (!IsSEH) 1646 CatchPadMBB->setIsEHScopeEntry(); 1647 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1648 if (IsMSVCCXX || IsCoreCLR) 1649 CatchPadMBB->setIsEHFuncletEntry(); 1650 } 1651 1652 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1653 // Update machine-CFG edge. 1654 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1655 FuncInfo.MBB->addSuccessor(TargetMBB); 1656 TargetMBB->setIsEHCatchretTarget(true); 1657 DAG.getMachineFunction().setHasEHCatchret(true); 1658 1659 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1660 bool IsSEH = isAsynchronousEHPersonality(Pers); 1661 if (IsSEH) { 1662 // If this is not a fall-through branch or optimizations are switched off, 1663 // emit the branch. 1664 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1665 TM.getOptLevel() == CodeGenOpt::None) 1666 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1667 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1668 return; 1669 } 1670 1671 // Figure out the funclet membership for the catchret's successor. 1672 // This will be used by the FuncletLayout pass to determine how to order the 1673 // BB's. 1674 // A 'catchret' returns to the outer scope's color. 1675 Value *ParentPad = I.getCatchSwitchParentPad(); 1676 const BasicBlock *SuccessorColor; 1677 if (isa<ConstantTokenNone>(ParentPad)) 1678 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1679 else 1680 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1681 assert(SuccessorColor && "No parent funclet for catchret!"); 1682 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1683 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1684 1685 // Create the terminator node. 1686 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1687 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1688 DAG.getBasicBlock(SuccessorColorMBB)); 1689 DAG.setRoot(Ret); 1690 } 1691 1692 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1693 // Don't emit any special code for the cleanuppad instruction. It just marks 1694 // the start of an EH scope/funclet. 1695 FuncInfo.MBB->setIsEHScopeEntry(); 1696 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1697 if (Pers != EHPersonality::Wasm_CXX) { 1698 FuncInfo.MBB->setIsEHFuncletEntry(); 1699 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1700 } 1701 } 1702 1703 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1704 // not match, it is OK to add only the first unwind destination catchpad to the 1705 // successors, because there will be at least one invoke instruction within the 1706 // catch scope that points to the next unwind destination, if one exists, so 1707 // CFGSort cannot mess up with BB sorting order. 1708 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1709 // call within them, and catchpads only consisting of 'catch (...)' have a 1710 // '__cxa_end_catch' call within them, both of which generate invokes in case 1711 // the next unwind destination exists, i.e., the next unwind destination is not 1712 // the caller.) 1713 // 1714 // Having at most one EH pad successor is also simpler and helps later 1715 // transformations. 1716 // 1717 // For example, 1718 // current: 1719 // invoke void @foo to ... unwind label %catch.dispatch 1720 // catch.dispatch: 1721 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1722 // catch.start: 1723 // ... 1724 // ... in this BB or some other child BB dominated by this BB there will be an 1725 // invoke that points to 'next' BB as an unwind destination 1726 // 1727 // next: ; We don't need to add this to 'current' BB's successor 1728 // ... 1729 static void findWasmUnwindDestinations( 1730 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1731 BranchProbability Prob, 1732 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1733 &UnwindDests) { 1734 while (EHPadBB) { 1735 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1736 if (isa<CleanupPadInst>(Pad)) { 1737 // Stop on cleanup pads. 1738 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1739 UnwindDests.back().first->setIsEHScopeEntry(); 1740 break; 1741 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1742 // Add the catchpad handlers to the possible destinations. We don't 1743 // continue to the unwind destination of the catchswitch for wasm. 1744 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1745 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1746 UnwindDests.back().first->setIsEHScopeEntry(); 1747 } 1748 break; 1749 } else { 1750 continue; 1751 } 1752 } 1753 } 1754 1755 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1756 /// many places it could ultimately go. In the IR, we have a single unwind 1757 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1758 /// This function skips over imaginary basic blocks that hold catchswitch 1759 /// instructions, and finds all the "real" machine 1760 /// basic block destinations. As those destinations may not be successors of 1761 /// EHPadBB, here we also calculate the edge probability to those destinations. 1762 /// The passed-in Prob is the edge probability to EHPadBB. 1763 static void findUnwindDestinations( 1764 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1765 BranchProbability Prob, 1766 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1767 &UnwindDests) { 1768 EHPersonality Personality = 1769 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1770 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1771 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1772 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1773 bool IsSEH = isAsynchronousEHPersonality(Personality); 1774 1775 if (IsWasmCXX) { 1776 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1777 assert(UnwindDests.size() <= 1 && 1778 "There should be at most one unwind destination for wasm"); 1779 return; 1780 } 1781 1782 while (EHPadBB) { 1783 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1784 BasicBlock *NewEHPadBB = nullptr; 1785 if (isa<LandingPadInst>(Pad)) { 1786 // Stop on landingpads. They are not funclets. 1787 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1788 break; 1789 } else if (isa<CleanupPadInst>(Pad)) { 1790 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1791 // personalities. 1792 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1793 UnwindDests.back().first->setIsEHScopeEntry(); 1794 UnwindDests.back().first->setIsEHFuncletEntry(); 1795 break; 1796 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1797 // Add the catchpad handlers to the possible destinations. 1798 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1799 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1800 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1801 if (IsMSVCCXX || IsCoreCLR) 1802 UnwindDests.back().first->setIsEHFuncletEntry(); 1803 if (!IsSEH) 1804 UnwindDests.back().first->setIsEHScopeEntry(); 1805 } 1806 NewEHPadBB = CatchSwitch->getUnwindDest(); 1807 } else { 1808 continue; 1809 } 1810 1811 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1812 if (BPI && NewEHPadBB) 1813 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1814 EHPadBB = NewEHPadBB; 1815 } 1816 } 1817 1818 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1819 // Update successor info. 1820 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1821 auto UnwindDest = I.getUnwindDest(); 1822 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1823 BranchProbability UnwindDestProb = 1824 (BPI && UnwindDest) 1825 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1826 : BranchProbability::getZero(); 1827 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1828 for (auto &UnwindDest : UnwindDests) { 1829 UnwindDest.first->setIsEHPad(); 1830 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1831 } 1832 FuncInfo.MBB->normalizeSuccProbs(); 1833 1834 // Create the terminator node. 1835 SDValue Ret = 1836 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1837 DAG.setRoot(Ret); 1838 } 1839 1840 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1841 report_fatal_error("visitCatchSwitch not yet implemented!"); 1842 } 1843 1844 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1845 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1846 auto &DL = DAG.getDataLayout(); 1847 SDValue Chain = getControlRoot(); 1848 SmallVector<ISD::OutputArg, 8> Outs; 1849 SmallVector<SDValue, 8> OutVals; 1850 1851 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1852 // lower 1853 // 1854 // %val = call <ty> @llvm.experimental.deoptimize() 1855 // ret <ty> %val 1856 // 1857 // differently. 1858 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1859 LowerDeoptimizingReturn(); 1860 return; 1861 } 1862 1863 if (!FuncInfo.CanLowerReturn) { 1864 unsigned DemoteReg = FuncInfo.DemoteRegister; 1865 const Function *F = I.getParent()->getParent(); 1866 1867 // Emit a store of the return value through the virtual register. 1868 // Leave Outs empty so that LowerReturn won't try to load return 1869 // registers the usual way. 1870 SmallVector<EVT, 1> PtrValueVTs; 1871 ComputeValueVTs(TLI, DL, 1872 F->getReturnType()->getPointerTo( 1873 DAG.getDataLayout().getAllocaAddrSpace()), 1874 PtrValueVTs); 1875 1876 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1877 DemoteReg, PtrValueVTs[0]); 1878 SDValue RetOp = getValue(I.getOperand(0)); 1879 1880 SmallVector<EVT, 4> ValueVTs, MemVTs; 1881 SmallVector<uint64_t, 4> Offsets; 1882 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1883 &Offsets); 1884 unsigned NumValues = ValueVTs.size(); 1885 1886 SmallVector<SDValue, 4> Chains(NumValues); 1887 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1888 for (unsigned i = 0; i != NumValues; ++i) { 1889 // An aggregate return value cannot wrap around the address space, so 1890 // offsets to its parts don't wrap either. 1891 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1892 TypeSize::Fixed(Offsets[i])); 1893 1894 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1895 if (MemVTs[i] != ValueVTs[i]) 1896 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1897 Chains[i] = DAG.getStore( 1898 Chain, getCurSDLoc(), Val, 1899 // FIXME: better loc info would be nice. 1900 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1901 commonAlignment(BaseAlign, Offsets[i])); 1902 } 1903 1904 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1905 MVT::Other, Chains); 1906 } else if (I.getNumOperands() != 0) { 1907 SmallVector<EVT, 4> ValueVTs; 1908 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1909 unsigned NumValues = ValueVTs.size(); 1910 if (NumValues) { 1911 SDValue RetOp = getValue(I.getOperand(0)); 1912 1913 const Function *F = I.getParent()->getParent(); 1914 1915 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1916 I.getOperand(0)->getType(), F->getCallingConv(), 1917 /*IsVarArg*/ false); 1918 1919 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1920 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1921 Attribute::SExt)) 1922 ExtendKind = ISD::SIGN_EXTEND; 1923 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1924 Attribute::ZExt)) 1925 ExtendKind = ISD::ZERO_EXTEND; 1926 1927 LLVMContext &Context = F->getContext(); 1928 bool RetInReg = F->getAttributes().hasAttribute( 1929 AttributeList::ReturnIndex, Attribute::InReg); 1930 1931 for (unsigned j = 0; j != NumValues; ++j) { 1932 EVT VT = ValueVTs[j]; 1933 1934 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1935 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1936 1937 CallingConv::ID CC = F->getCallingConv(); 1938 1939 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1940 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1941 SmallVector<SDValue, 4> Parts(NumParts); 1942 getCopyToParts(DAG, getCurSDLoc(), 1943 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1944 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1945 1946 // 'inreg' on function refers to return value 1947 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1948 if (RetInReg) 1949 Flags.setInReg(); 1950 1951 if (I.getOperand(0)->getType()->isPointerTy()) { 1952 Flags.setPointer(); 1953 Flags.setPointerAddrSpace( 1954 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1955 } 1956 1957 if (NeedsRegBlock) { 1958 Flags.setInConsecutiveRegs(); 1959 if (j == NumValues - 1) 1960 Flags.setInConsecutiveRegsLast(); 1961 } 1962 1963 // Propagate extension type if any 1964 if (ExtendKind == ISD::SIGN_EXTEND) 1965 Flags.setSExt(); 1966 else if (ExtendKind == ISD::ZERO_EXTEND) 1967 Flags.setZExt(); 1968 1969 for (unsigned i = 0; i < NumParts; ++i) { 1970 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1971 VT, /*isfixed=*/true, 0, 0)); 1972 OutVals.push_back(Parts[i]); 1973 } 1974 } 1975 } 1976 } 1977 1978 // Push in swifterror virtual register as the last element of Outs. This makes 1979 // sure swifterror virtual register will be returned in the swifterror 1980 // physical register. 1981 const Function *F = I.getParent()->getParent(); 1982 if (TLI.supportSwiftError() && 1983 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1984 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1985 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1986 Flags.setSwiftError(); 1987 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1988 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1989 true /*isfixed*/, 1 /*origidx*/, 1990 0 /*partOffs*/)); 1991 // Create SDNode for the swifterror virtual register. 1992 OutVals.push_back( 1993 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1994 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1995 EVT(TLI.getPointerTy(DL)))); 1996 } 1997 1998 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1999 CallingConv::ID CallConv = 2000 DAG.getMachineFunction().getFunction().getCallingConv(); 2001 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2002 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2003 2004 // Verify that the target's LowerReturn behaved as expected. 2005 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2006 "LowerReturn didn't return a valid chain!"); 2007 2008 // Update the DAG with the new chain value resulting from return lowering. 2009 DAG.setRoot(Chain); 2010 } 2011 2012 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2013 /// created for it, emit nodes to copy the value into the virtual 2014 /// registers. 2015 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2016 // Skip empty types 2017 if (V->getType()->isEmptyTy()) 2018 return; 2019 2020 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2021 if (VMI != FuncInfo.ValueMap.end()) { 2022 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2023 CopyValueToVirtualRegister(V, VMI->second); 2024 } 2025 } 2026 2027 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2028 /// the current basic block, add it to ValueMap now so that we'll get a 2029 /// CopyTo/FromReg. 2030 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2031 // No need to export constants. 2032 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2033 2034 // Already exported? 2035 if (FuncInfo.isExportedInst(V)) return; 2036 2037 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2038 CopyValueToVirtualRegister(V, Reg); 2039 } 2040 2041 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2042 const BasicBlock *FromBB) { 2043 // The operands of the setcc have to be in this block. We don't know 2044 // how to export them from some other block. 2045 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2046 // Can export from current BB. 2047 if (VI->getParent() == FromBB) 2048 return true; 2049 2050 // Is already exported, noop. 2051 return FuncInfo.isExportedInst(V); 2052 } 2053 2054 // If this is an argument, we can export it if the BB is the entry block or 2055 // if it is already exported. 2056 if (isa<Argument>(V)) { 2057 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2058 return true; 2059 2060 // Otherwise, can only export this if it is already exported. 2061 return FuncInfo.isExportedInst(V); 2062 } 2063 2064 // Otherwise, constants can always be exported. 2065 return true; 2066 } 2067 2068 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2069 BranchProbability 2070 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2071 const MachineBasicBlock *Dst) const { 2072 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2073 const BasicBlock *SrcBB = Src->getBasicBlock(); 2074 const BasicBlock *DstBB = Dst->getBasicBlock(); 2075 if (!BPI) { 2076 // If BPI is not available, set the default probability as 1 / N, where N is 2077 // the number of successors. 2078 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2079 return BranchProbability(1, SuccSize); 2080 } 2081 return BPI->getEdgeProbability(SrcBB, DstBB); 2082 } 2083 2084 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2085 MachineBasicBlock *Dst, 2086 BranchProbability Prob) { 2087 if (!FuncInfo.BPI) 2088 Src->addSuccessorWithoutProb(Dst); 2089 else { 2090 if (Prob.isUnknown()) 2091 Prob = getEdgeProbability(Src, Dst); 2092 Src->addSuccessor(Dst, Prob); 2093 } 2094 } 2095 2096 static bool InBlock(const Value *V, const BasicBlock *BB) { 2097 if (const Instruction *I = dyn_cast<Instruction>(V)) 2098 return I->getParent() == BB; 2099 return true; 2100 } 2101 2102 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2103 /// This function emits a branch and is used at the leaves of an OR or an 2104 /// AND operator tree. 2105 void 2106 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2107 MachineBasicBlock *TBB, 2108 MachineBasicBlock *FBB, 2109 MachineBasicBlock *CurBB, 2110 MachineBasicBlock *SwitchBB, 2111 BranchProbability TProb, 2112 BranchProbability FProb, 2113 bool InvertCond) { 2114 const BasicBlock *BB = CurBB->getBasicBlock(); 2115 2116 // If the leaf of the tree is a comparison, merge the condition into 2117 // the caseblock. 2118 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2119 // The operands of the cmp have to be in this block. We don't know 2120 // how to export them from some other block. If this is the first block 2121 // of the sequence, no exporting is needed. 2122 if (CurBB == SwitchBB || 2123 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2124 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2125 ISD::CondCode Condition; 2126 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2127 ICmpInst::Predicate Pred = 2128 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2129 Condition = getICmpCondCode(Pred); 2130 } else { 2131 const FCmpInst *FC = cast<FCmpInst>(Cond); 2132 FCmpInst::Predicate Pred = 2133 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2134 Condition = getFCmpCondCode(Pred); 2135 if (TM.Options.NoNaNsFPMath) 2136 Condition = getFCmpCodeWithoutNaN(Condition); 2137 } 2138 2139 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2140 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2141 SL->SwitchCases.push_back(CB); 2142 return; 2143 } 2144 } 2145 2146 // Create a CaseBlock record representing this branch. 2147 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2148 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2149 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2150 SL->SwitchCases.push_back(CB); 2151 } 2152 2153 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2154 MachineBasicBlock *TBB, 2155 MachineBasicBlock *FBB, 2156 MachineBasicBlock *CurBB, 2157 MachineBasicBlock *SwitchBB, 2158 Instruction::BinaryOps Opc, 2159 BranchProbability TProb, 2160 BranchProbability FProb, 2161 bool InvertCond) { 2162 // Skip over not part of the tree and remember to invert op and operands at 2163 // next level. 2164 Value *NotCond; 2165 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2166 InBlock(NotCond, CurBB->getBasicBlock())) { 2167 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2168 !InvertCond); 2169 return; 2170 } 2171 2172 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2173 const Value *BOpOp0, *BOpOp1; 2174 // Compute the effective opcode for Cond, taking into account whether it needs 2175 // to be inverted, e.g. 2176 // and (not (or A, B)), C 2177 // gets lowered as 2178 // and (and (not A, not B), C) 2179 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2180 if (BOp) { 2181 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2182 ? Instruction::And 2183 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2184 ? Instruction::Or 2185 : (Instruction::BinaryOps)0); 2186 if (InvertCond) { 2187 if (BOpc == Instruction::And) 2188 BOpc = Instruction::Or; 2189 else if (BOpc == Instruction::Or) 2190 BOpc = Instruction::And; 2191 } 2192 } 2193 2194 // If this node is not part of the or/and tree, emit it as a branch. 2195 // Note that all nodes in the tree should have same opcode. 2196 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2197 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2198 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2199 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2200 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2201 TProb, FProb, InvertCond); 2202 return; 2203 } 2204 2205 // Create TmpBB after CurBB. 2206 MachineFunction::iterator BBI(CurBB); 2207 MachineFunction &MF = DAG.getMachineFunction(); 2208 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2209 CurBB->getParent()->insert(++BBI, TmpBB); 2210 2211 if (Opc == Instruction::Or) { 2212 // Codegen X | Y as: 2213 // BB1: 2214 // jmp_if_X TBB 2215 // jmp TmpBB 2216 // TmpBB: 2217 // jmp_if_Y TBB 2218 // jmp FBB 2219 // 2220 2221 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2222 // The requirement is that 2223 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2224 // = TrueProb for original BB. 2225 // Assuming the original probabilities are A and B, one choice is to set 2226 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2227 // A/(1+B) and 2B/(1+B). This choice assumes that 2228 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2229 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2230 // TmpBB, but the math is more complicated. 2231 2232 auto NewTrueProb = TProb / 2; 2233 auto NewFalseProb = TProb / 2 + FProb; 2234 // Emit the LHS condition. 2235 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2236 NewFalseProb, InvertCond); 2237 2238 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2239 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2240 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2241 // Emit the RHS condition into TmpBB. 2242 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2243 Probs[1], InvertCond); 2244 } else { 2245 assert(Opc == Instruction::And && "Unknown merge op!"); 2246 // Codegen X & Y as: 2247 // BB1: 2248 // jmp_if_X TmpBB 2249 // jmp FBB 2250 // TmpBB: 2251 // jmp_if_Y TBB 2252 // jmp FBB 2253 // 2254 // This requires creation of TmpBB after CurBB. 2255 2256 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2257 // The requirement is that 2258 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2259 // = FalseProb for original BB. 2260 // Assuming the original probabilities are A and B, one choice is to set 2261 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2262 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2263 // TrueProb for BB1 * FalseProb for TmpBB. 2264 2265 auto NewTrueProb = TProb + FProb / 2; 2266 auto NewFalseProb = FProb / 2; 2267 // Emit the LHS condition. 2268 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2269 NewFalseProb, InvertCond); 2270 2271 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2272 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2273 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2274 // Emit the RHS condition into TmpBB. 2275 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2276 Probs[1], InvertCond); 2277 } 2278 } 2279 2280 /// If the set of cases should be emitted as a series of branches, return true. 2281 /// If we should emit this as a bunch of and/or'd together conditions, return 2282 /// false. 2283 bool 2284 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2285 if (Cases.size() != 2) return true; 2286 2287 // If this is two comparisons of the same values or'd or and'd together, they 2288 // will get folded into a single comparison, so don't emit two blocks. 2289 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2290 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2291 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2292 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2293 return false; 2294 } 2295 2296 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2297 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2298 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2299 Cases[0].CC == Cases[1].CC && 2300 isa<Constant>(Cases[0].CmpRHS) && 2301 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2302 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2303 return false; 2304 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2305 return false; 2306 } 2307 2308 return true; 2309 } 2310 2311 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2312 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2313 2314 // Update machine-CFG edges. 2315 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2316 2317 if (I.isUnconditional()) { 2318 // Update machine-CFG edges. 2319 BrMBB->addSuccessor(Succ0MBB); 2320 2321 // If this is not a fall-through branch or optimizations are switched off, 2322 // emit the branch. 2323 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2324 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2325 MVT::Other, getControlRoot(), 2326 DAG.getBasicBlock(Succ0MBB))); 2327 2328 return; 2329 } 2330 2331 // If this condition is one of the special cases we handle, do special stuff 2332 // now. 2333 const Value *CondVal = I.getCondition(); 2334 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2335 2336 // If this is a series of conditions that are or'd or and'd together, emit 2337 // this as a sequence of branches instead of setcc's with and/or operations. 2338 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2339 // unpredictable branches, and vector extracts because those jumps are likely 2340 // expensive for any target), this should improve performance. 2341 // For example, instead of something like: 2342 // cmp A, B 2343 // C = seteq 2344 // cmp D, E 2345 // F = setle 2346 // or C, F 2347 // jnz foo 2348 // Emit: 2349 // cmp A, B 2350 // je foo 2351 // cmp D, E 2352 // jle foo 2353 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2354 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2355 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2356 Value *Vec; 2357 const Value *BOp0, *BOp1; 2358 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2359 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2360 Opcode = Instruction::And; 2361 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2362 Opcode = Instruction::Or; 2363 2364 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2365 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2366 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2367 getEdgeProbability(BrMBB, Succ0MBB), 2368 getEdgeProbability(BrMBB, Succ1MBB), 2369 /*InvertCond=*/false); 2370 // If the compares in later blocks need to use values not currently 2371 // exported from this block, export them now. This block should always 2372 // be the first entry. 2373 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2374 2375 // Allow some cases to be rejected. 2376 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2377 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2378 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2379 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2380 } 2381 2382 // Emit the branch for this block. 2383 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2384 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2385 return; 2386 } 2387 2388 // Okay, we decided not to do this, remove any inserted MBB's and clear 2389 // SwitchCases. 2390 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2391 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2392 2393 SL->SwitchCases.clear(); 2394 } 2395 } 2396 2397 // Create a CaseBlock record representing this branch. 2398 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2399 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2400 2401 // Use visitSwitchCase to actually insert the fast branch sequence for this 2402 // cond branch. 2403 visitSwitchCase(CB, BrMBB); 2404 } 2405 2406 /// visitSwitchCase - Emits the necessary code to represent a single node in 2407 /// the binary search tree resulting from lowering a switch instruction. 2408 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2409 MachineBasicBlock *SwitchBB) { 2410 SDValue Cond; 2411 SDValue CondLHS = getValue(CB.CmpLHS); 2412 SDLoc dl = CB.DL; 2413 2414 if (CB.CC == ISD::SETTRUE) { 2415 // Branch or fall through to TrueBB. 2416 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2417 SwitchBB->normalizeSuccProbs(); 2418 if (CB.TrueBB != NextBlock(SwitchBB)) { 2419 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2420 DAG.getBasicBlock(CB.TrueBB))); 2421 } 2422 return; 2423 } 2424 2425 auto &TLI = DAG.getTargetLoweringInfo(); 2426 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2427 2428 // Build the setcc now. 2429 if (!CB.CmpMHS) { 2430 // Fold "(X == true)" to X and "(X == false)" to !X to 2431 // handle common cases produced by branch lowering. 2432 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2433 CB.CC == ISD::SETEQ) 2434 Cond = CondLHS; 2435 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2436 CB.CC == ISD::SETEQ) { 2437 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2438 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2439 } else { 2440 SDValue CondRHS = getValue(CB.CmpRHS); 2441 2442 // If a pointer's DAG type is larger than its memory type then the DAG 2443 // values are zero-extended. This breaks signed comparisons so truncate 2444 // back to the underlying type before doing the compare. 2445 if (CondLHS.getValueType() != MemVT) { 2446 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2447 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2448 } 2449 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2450 } 2451 } else { 2452 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2453 2454 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2455 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2456 2457 SDValue CmpOp = getValue(CB.CmpMHS); 2458 EVT VT = CmpOp.getValueType(); 2459 2460 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2461 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2462 ISD::SETLE); 2463 } else { 2464 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2465 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2466 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2467 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2468 } 2469 } 2470 2471 // Update successor info 2472 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2473 // TrueBB and FalseBB are always different unless the incoming IR is 2474 // degenerate. This only happens when running llc on weird IR. 2475 if (CB.TrueBB != CB.FalseBB) 2476 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2477 SwitchBB->normalizeSuccProbs(); 2478 2479 // If the lhs block is the next block, invert the condition so that we can 2480 // fall through to the lhs instead of the rhs block. 2481 if (CB.TrueBB == NextBlock(SwitchBB)) { 2482 std::swap(CB.TrueBB, CB.FalseBB); 2483 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2484 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2485 } 2486 2487 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2488 MVT::Other, getControlRoot(), Cond, 2489 DAG.getBasicBlock(CB.TrueBB)); 2490 2491 // Insert the false branch. Do this even if it's a fall through branch, 2492 // this makes it easier to do DAG optimizations which require inverting 2493 // the branch condition. 2494 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2495 DAG.getBasicBlock(CB.FalseBB)); 2496 2497 DAG.setRoot(BrCond); 2498 } 2499 2500 /// visitJumpTable - Emit JumpTable node in the current MBB 2501 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2502 // Emit the code for the jump table 2503 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2504 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2505 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2506 JT.Reg, PTy); 2507 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2508 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2509 MVT::Other, Index.getValue(1), 2510 Table, Index); 2511 DAG.setRoot(BrJumpTable); 2512 } 2513 2514 /// visitJumpTableHeader - This function emits necessary code to produce index 2515 /// in the JumpTable from switch case. 2516 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2517 JumpTableHeader &JTH, 2518 MachineBasicBlock *SwitchBB) { 2519 SDLoc dl = getCurSDLoc(); 2520 2521 // Subtract the lowest switch case value from the value being switched on. 2522 SDValue SwitchOp = getValue(JTH.SValue); 2523 EVT VT = SwitchOp.getValueType(); 2524 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2525 DAG.getConstant(JTH.First, dl, VT)); 2526 2527 // The SDNode we just created, which holds the value being switched on minus 2528 // the smallest case value, needs to be copied to a virtual register so it 2529 // can be used as an index into the jump table in a subsequent basic block. 2530 // This value may be smaller or larger than the target's pointer type, and 2531 // therefore require extension or truncating. 2532 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2533 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2534 2535 unsigned JumpTableReg = 2536 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2537 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2538 JumpTableReg, SwitchOp); 2539 JT.Reg = JumpTableReg; 2540 2541 if (!JTH.OmitRangeCheck) { 2542 // Emit the range check for the jump table, and branch to the default block 2543 // for the switch statement if the value being switched on exceeds the 2544 // largest case in the switch. 2545 SDValue CMP = DAG.getSetCC( 2546 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2547 Sub.getValueType()), 2548 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2549 2550 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2551 MVT::Other, CopyTo, CMP, 2552 DAG.getBasicBlock(JT.Default)); 2553 2554 // Avoid emitting unnecessary branches to the next block. 2555 if (JT.MBB != NextBlock(SwitchBB)) 2556 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2557 DAG.getBasicBlock(JT.MBB)); 2558 2559 DAG.setRoot(BrCond); 2560 } else { 2561 // Avoid emitting unnecessary branches to the next block. 2562 if (JT.MBB != NextBlock(SwitchBB)) 2563 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2564 DAG.getBasicBlock(JT.MBB))); 2565 else 2566 DAG.setRoot(CopyTo); 2567 } 2568 } 2569 2570 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2571 /// variable if there exists one. 2572 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2573 SDValue &Chain) { 2574 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2575 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2576 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2577 MachineFunction &MF = DAG.getMachineFunction(); 2578 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2579 MachineSDNode *Node = 2580 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2581 if (Global) { 2582 MachinePointerInfo MPInfo(Global); 2583 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2584 MachineMemOperand::MODereferenceable; 2585 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2586 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2587 DAG.setNodeMemRefs(Node, {MemRef}); 2588 } 2589 if (PtrTy != PtrMemTy) 2590 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2591 return SDValue(Node, 0); 2592 } 2593 2594 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2595 /// tail spliced into a stack protector check success bb. 2596 /// 2597 /// For a high level explanation of how this fits into the stack protector 2598 /// generation see the comment on the declaration of class 2599 /// StackProtectorDescriptor. 2600 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2601 MachineBasicBlock *ParentBB) { 2602 2603 // First create the loads to the guard/stack slot for the comparison. 2604 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2605 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2606 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2607 2608 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2609 int FI = MFI.getStackProtectorIndex(); 2610 2611 SDValue Guard; 2612 SDLoc dl = getCurSDLoc(); 2613 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2614 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2615 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2616 2617 // Generate code to load the content of the guard slot. 2618 SDValue GuardVal = DAG.getLoad( 2619 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2620 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2621 MachineMemOperand::MOVolatile); 2622 2623 if (TLI.useStackGuardXorFP()) 2624 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2625 2626 // Retrieve guard check function, nullptr if instrumentation is inlined. 2627 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2628 // The target provides a guard check function to validate the guard value. 2629 // Generate a call to that function with the content of the guard slot as 2630 // argument. 2631 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2632 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2633 2634 TargetLowering::ArgListTy Args; 2635 TargetLowering::ArgListEntry Entry; 2636 Entry.Node = GuardVal; 2637 Entry.Ty = FnTy->getParamType(0); 2638 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2639 Entry.IsInReg = true; 2640 Args.push_back(Entry); 2641 2642 TargetLowering::CallLoweringInfo CLI(DAG); 2643 CLI.setDebugLoc(getCurSDLoc()) 2644 .setChain(DAG.getEntryNode()) 2645 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2646 getValue(GuardCheckFn), std::move(Args)); 2647 2648 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2649 DAG.setRoot(Result.second); 2650 return; 2651 } 2652 2653 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2654 // Otherwise, emit a volatile load to retrieve the stack guard value. 2655 SDValue Chain = DAG.getEntryNode(); 2656 if (TLI.useLoadStackGuardNode()) { 2657 Guard = getLoadStackGuard(DAG, dl, Chain); 2658 } else { 2659 const Value *IRGuard = TLI.getSDagStackGuard(M); 2660 SDValue GuardPtr = getValue(IRGuard); 2661 2662 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2663 MachinePointerInfo(IRGuard, 0), Align, 2664 MachineMemOperand::MOVolatile); 2665 } 2666 2667 // Perform the comparison via a getsetcc. 2668 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2669 *DAG.getContext(), 2670 Guard.getValueType()), 2671 Guard, GuardVal, ISD::SETNE); 2672 2673 // If the guard/stackslot do not equal, branch to failure MBB. 2674 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2675 MVT::Other, GuardVal.getOperand(0), 2676 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2677 // Otherwise branch to success MBB. 2678 SDValue Br = DAG.getNode(ISD::BR, dl, 2679 MVT::Other, BrCond, 2680 DAG.getBasicBlock(SPD.getSuccessMBB())); 2681 2682 DAG.setRoot(Br); 2683 } 2684 2685 /// Codegen the failure basic block for a stack protector check. 2686 /// 2687 /// A failure stack protector machine basic block consists simply of a call to 2688 /// __stack_chk_fail(). 2689 /// 2690 /// For a high level explanation of how this fits into the stack protector 2691 /// generation see the comment on the declaration of class 2692 /// StackProtectorDescriptor. 2693 void 2694 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2695 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2696 TargetLowering::MakeLibCallOptions CallOptions; 2697 CallOptions.setDiscardResult(true); 2698 SDValue Chain = 2699 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2700 None, CallOptions, getCurSDLoc()).second; 2701 // On PS4, the "return address" must still be within the calling function, 2702 // even if it's at the very end, so emit an explicit TRAP here. 2703 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2704 if (TM.getTargetTriple().isPS4CPU()) 2705 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2706 // WebAssembly needs an unreachable instruction after a non-returning call, 2707 // because the function return type can be different from __stack_chk_fail's 2708 // return type (void). 2709 if (TM.getTargetTriple().isWasm()) 2710 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2711 2712 DAG.setRoot(Chain); 2713 } 2714 2715 /// visitBitTestHeader - This function emits necessary code to produce value 2716 /// suitable for "bit tests" 2717 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2718 MachineBasicBlock *SwitchBB) { 2719 SDLoc dl = getCurSDLoc(); 2720 2721 // Subtract the minimum value. 2722 SDValue SwitchOp = getValue(B.SValue); 2723 EVT VT = SwitchOp.getValueType(); 2724 SDValue RangeSub = 2725 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2726 2727 // Determine the type of the test operands. 2728 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2729 bool UsePtrType = false; 2730 if (!TLI.isTypeLegal(VT)) { 2731 UsePtrType = true; 2732 } else { 2733 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2734 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2735 // Switch table case range are encoded into series of masks. 2736 // Just use pointer type, it's guaranteed to fit. 2737 UsePtrType = true; 2738 break; 2739 } 2740 } 2741 SDValue Sub = RangeSub; 2742 if (UsePtrType) { 2743 VT = TLI.getPointerTy(DAG.getDataLayout()); 2744 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2745 } 2746 2747 B.RegVT = VT.getSimpleVT(); 2748 B.Reg = FuncInfo.CreateReg(B.RegVT); 2749 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2750 2751 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2752 2753 if (!B.OmitRangeCheck) 2754 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2755 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2756 SwitchBB->normalizeSuccProbs(); 2757 2758 SDValue Root = CopyTo; 2759 if (!B.OmitRangeCheck) { 2760 // Conditional branch to the default block. 2761 SDValue RangeCmp = DAG.getSetCC(dl, 2762 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2763 RangeSub.getValueType()), 2764 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2765 ISD::SETUGT); 2766 2767 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2768 DAG.getBasicBlock(B.Default)); 2769 } 2770 2771 // Avoid emitting unnecessary branches to the next block. 2772 if (MBB != NextBlock(SwitchBB)) 2773 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2774 2775 DAG.setRoot(Root); 2776 } 2777 2778 /// visitBitTestCase - this function produces one "bit test" 2779 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2780 MachineBasicBlock* NextMBB, 2781 BranchProbability BranchProbToNext, 2782 unsigned Reg, 2783 BitTestCase &B, 2784 MachineBasicBlock *SwitchBB) { 2785 SDLoc dl = getCurSDLoc(); 2786 MVT VT = BB.RegVT; 2787 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2788 SDValue Cmp; 2789 unsigned PopCount = countPopulation(B.Mask); 2790 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2791 if (PopCount == 1) { 2792 // Testing for a single bit; just compare the shift count with what it 2793 // would need to be to shift a 1 bit in that position. 2794 Cmp = DAG.getSetCC( 2795 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2796 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2797 ISD::SETEQ); 2798 } else if (PopCount == BB.Range) { 2799 // There is only one zero bit in the range, test for it directly. 2800 Cmp = DAG.getSetCC( 2801 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2802 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2803 ISD::SETNE); 2804 } else { 2805 // Make desired shift 2806 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2807 DAG.getConstant(1, dl, VT), ShiftOp); 2808 2809 // Emit bit tests and jumps 2810 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2811 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2812 Cmp = DAG.getSetCC( 2813 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2814 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2815 } 2816 2817 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2818 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2819 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2820 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2821 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2822 // one as they are relative probabilities (and thus work more like weights), 2823 // and hence we need to normalize them to let the sum of them become one. 2824 SwitchBB->normalizeSuccProbs(); 2825 2826 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2827 MVT::Other, getControlRoot(), 2828 Cmp, DAG.getBasicBlock(B.TargetBB)); 2829 2830 // Avoid emitting unnecessary branches to the next block. 2831 if (NextMBB != NextBlock(SwitchBB)) 2832 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2833 DAG.getBasicBlock(NextMBB)); 2834 2835 DAG.setRoot(BrAnd); 2836 } 2837 2838 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2839 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2840 2841 // Retrieve successors. Look through artificial IR level blocks like 2842 // catchswitch for successors. 2843 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2844 const BasicBlock *EHPadBB = I.getSuccessor(1); 2845 2846 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2847 // have to do anything here to lower funclet bundles. 2848 assert(!I.hasOperandBundlesOtherThan( 2849 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2850 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2851 LLVMContext::OB_cfguardtarget, 2852 LLVMContext::OB_clang_arc_attachedcall}) && 2853 "Cannot lower invokes with arbitrary operand bundles yet!"); 2854 2855 const Value *Callee(I.getCalledOperand()); 2856 const Function *Fn = dyn_cast<Function>(Callee); 2857 if (isa<InlineAsm>(Callee)) 2858 visitInlineAsm(I); 2859 else if (Fn && Fn->isIntrinsic()) { 2860 switch (Fn->getIntrinsicID()) { 2861 default: 2862 llvm_unreachable("Cannot invoke this intrinsic"); 2863 case Intrinsic::donothing: 2864 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2865 break; 2866 case Intrinsic::experimental_patchpoint_void: 2867 case Intrinsic::experimental_patchpoint_i64: 2868 visitPatchpoint(I, EHPadBB); 2869 break; 2870 case Intrinsic::experimental_gc_statepoint: 2871 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2872 break; 2873 case Intrinsic::wasm_rethrow: { 2874 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2875 // special because it can be invoked, so we manually lower it to a DAG 2876 // node here. 2877 SmallVector<SDValue, 8> Ops; 2878 Ops.push_back(getRoot()); // inchain 2879 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2880 Ops.push_back( 2881 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2882 TLI.getPointerTy(DAG.getDataLayout()))); 2883 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2884 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2885 break; 2886 } 2887 } 2888 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2889 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2890 // Eventually we will support lowering the @llvm.experimental.deoptimize 2891 // intrinsic, and right now there are no plans to support other intrinsics 2892 // with deopt state. 2893 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2894 } else { 2895 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2896 } 2897 2898 // If the value of the invoke is used outside of its defining block, make it 2899 // available as a virtual register. 2900 // We already took care of the exported value for the statepoint instruction 2901 // during call to the LowerStatepoint. 2902 if (!isa<GCStatepointInst>(I)) { 2903 CopyToExportRegsIfNeeded(&I); 2904 } 2905 2906 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2907 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2908 BranchProbability EHPadBBProb = 2909 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2910 : BranchProbability::getZero(); 2911 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2912 2913 // Update successor info. 2914 addSuccessorWithProb(InvokeMBB, Return); 2915 for (auto &UnwindDest : UnwindDests) { 2916 UnwindDest.first->setIsEHPad(); 2917 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2918 } 2919 InvokeMBB->normalizeSuccProbs(); 2920 2921 // Drop into normal successor. 2922 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2923 DAG.getBasicBlock(Return))); 2924 } 2925 2926 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2927 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2928 2929 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2930 // have to do anything here to lower funclet bundles. 2931 assert(!I.hasOperandBundlesOtherThan( 2932 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2933 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2934 2935 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2936 visitInlineAsm(I); 2937 CopyToExportRegsIfNeeded(&I); 2938 2939 // Retrieve successors. 2940 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2941 2942 // Update successor info. 2943 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2944 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2945 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2946 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2947 Target->setIsInlineAsmBrIndirectTarget(); 2948 } 2949 CallBrMBB->normalizeSuccProbs(); 2950 2951 // Drop into default successor. 2952 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2953 MVT::Other, getControlRoot(), 2954 DAG.getBasicBlock(Return))); 2955 } 2956 2957 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2958 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2959 } 2960 2961 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2962 assert(FuncInfo.MBB->isEHPad() && 2963 "Call to landingpad not in landing pad!"); 2964 2965 // If there aren't registers to copy the values into (e.g., during SjLj 2966 // exceptions), then don't bother to create these DAG nodes. 2967 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2968 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2969 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2970 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2971 return; 2972 2973 // If landingpad's return type is token type, we don't create DAG nodes 2974 // for its exception pointer and selector value. The extraction of exception 2975 // pointer or selector value from token type landingpads is not currently 2976 // supported. 2977 if (LP.getType()->isTokenTy()) 2978 return; 2979 2980 SmallVector<EVT, 2> ValueVTs; 2981 SDLoc dl = getCurSDLoc(); 2982 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2983 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2984 2985 // Get the two live-in registers as SDValues. The physregs have already been 2986 // copied into virtual registers. 2987 SDValue Ops[2]; 2988 if (FuncInfo.ExceptionPointerVirtReg) { 2989 Ops[0] = DAG.getZExtOrTrunc( 2990 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2991 FuncInfo.ExceptionPointerVirtReg, 2992 TLI.getPointerTy(DAG.getDataLayout())), 2993 dl, ValueVTs[0]); 2994 } else { 2995 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2996 } 2997 Ops[1] = DAG.getZExtOrTrunc( 2998 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2999 FuncInfo.ExceptionSelectorVirtReg, 3000 TLI.getPointerTy(DAG.getDataLayout())), 3001 dl, ValueVTs[1]); 3002 3003 // Merge into one. 3004 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3005 DAG.getVTList(ValueVTs), Ops); 3006 setValue(&LP, Res); 3007 } 3008 3009 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3010 MachineBasicBlock *Last) { 3011 // Update JTCases. 3012 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3013 if (SL->JTCases[i].first.HeaderBB == First) 3014 SL->JTCases[i].first.HeaderBB = Last; 3015 3016 // Update BitTestCases. 3017 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3018 if (SL->BitTestCases[i].Parent == First) 3019 SL->BitTestCases[i].Parent = Last; 3020 } 3021 3022 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3023 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3024 3025 // Update machine-CFG edges with unique successors. 3026 SmallSet<BasicBlock*, 32> Done; 3027 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3028 BasicBlock *BB = I.getSuccessor(i); 3029 bool Inserted = Done.insert(BB).second; 3030 if (!Inserted) 3031 continue; 3032 3033 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3034 addSuccessorWithProb(IndirectBrMBB, Succ); 3035 } 3036 IndirectBrMBB->normalizeSuccProbs(); 3037 3038 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3039 MVT::Other, getControlRoot(), 3040 getValue(I.getAddress()))); 3041 } 3042 3043 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3044 if (!DAG.getTarget().Options.TrapUnreachable) 3045 return; 3046 3047 // We may be able to ignore unreachable behind a noreturn call. 3048 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3049 const BasicBlock &BB = *I.getParent(); 3050 if (&I != &BB.front()) { 3051 BasicBlock::const_iterator PredI = 3052 std::prev(BasicBlock::const_iterator(&I)); 3053 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3054 if (Call->doesNotReturn()) 3055 return; 3056 } 3057 } 3058 } 3059 3060 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3061 } 3062 3063 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3064 SDNodeFlags Flags; 3065 3066 SDValue Op = getValue(I.getOperand(0)); 3067 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3068 Op, Flags); 3069 setValue(&I, UnNodeValue); 3070 } 3071 3072 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3073 SDNodeFlags Flags; 3074 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3075 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3076 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3077 } 3078 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3079 Flags.setExact(ExactOp->isExact()); 3080 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3081 Flags.copyFMF(*FPOp); 3082 3083 SDValue Op1 = getValue(I.getOperand(0)); 3084 SDValue Op2 = getValue(I.getOperand(1)); 3085 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3086 Op1, Op2, Flags); 3087 setValue(&I, BinNodeValue); 3088 } 3089 3090 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3091 SDValue Op1 = getValue(I.getOperand(0)); 3092 SDValue Op2 = getValue(I.getOperand(1)); 3093 3094 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3095 Op1.getValueType(), DAG.getDataLayout()); 3096 3097 // Coerce the shift amount to the right type if we can. 3098 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3099 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3100 unsigned Op2Size = Op2.getValueSizeInBits(); 3101 SDLoc DL = getCurSDLoc(); 3102 3103 // If the operand is smaller than the shift count type, promote it. 3104 if (ShiftSize > Op2Size) 3105 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3106 3107 // If the operand is larger than the shift count type but the shift 3108 // count type has enough bits to represent any shift value, truncate 3109 // it now. This is a common case and it exposes the truncate to 3110 // optimization early. 3111 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3112 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3113 // Otherwise we'll need to temporarily settle for some other convenient 3114 // type. Type legalization will make adjustments once the shiftee is split. 3115 else 3116 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3117 } 3118 3119 bool nuw = false; 3120 bool nsw = false; 3121 bool exact = false; 3122 3123 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3124 3125 if (const OverflowingBinaryOperator *OFBinOp = 3126 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3127 nuw = OFBinOp->hasNoUnsignedWrap(); 3128 nsw = OFBinOp->hasNoSignedWrap(); 3129 } 3130 if (const PossiblyExactOperator *ExactOp = 3131 dyn_cast<const PossiblyExactOperator>(&I)) 3132 exact = ExactOp->isExact(); 3133 } 3134 SDNodeFlags Flags; 3135 Flags.setExact(exact); 3136 Flags.setNoSignedWrap(nsw); 3137 Flags.setNoUnsignedWrap(nuw); 3138 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3139 Flags); 3140 setValue(&I, Res); 3141 } 3142 3143 void SelectionDAGBuilder::visitSDiv(const User &I) { 3144 SDValue Op1 = getValue(I.getOperand(0)); 3145 SDValue Op2 = getValue(I.getOperand(1)); 3146 3147 SDNodeFlags Flags; 3148 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3149 cast<PossiblyExactOperator>(&I)->isExact()); 3150 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3151 Op2, Flags)); 3152 } 3153 3154 void SelectionDAGBuilder::visitICmp(const User &I) { 3155 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3156 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3157 predicate = IC->getPredicate(); 3158 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3159 predicate = ICmpInst::Predicate(IC->getPredicate()); 3160 SDValue Op1 = getValue(I.getOperand(0)); 3161 SDValue Op2 = getValue(I.getOperand(1)); 3162 ISD::CondCode Opcode = getICmpCondCode(predicate); 3163 3164 auto &TLI = DAG.getTargetLoweringInfo(); 3165 EVT MemVT = 3166 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3167 3168 // If a pointer's DAG type is larger than its memory type then the DAG values 3169 // are zero-extended. This breaks signed comparisons so truncate back to the 3170 // underlying type before doing the compare. 3171 if (Op1.getValueType() != MemVT) { 3172 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3173 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3174 } 3175 3176 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3177 I.getType()); 3178 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3179 } 3180 3181 void SelectionDAGBuilder::visitFCmp(const User &I) { 3182 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3183 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3184 predicate = FC->getPredicate(); 3185 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3186 predicate = FCmpInst::Predicate(FC->getPredicate()); 3187 SDValue Op1 = getValue(I.getOperand(0)); 3188 SDValue Op2 = getValue(I.getOperand(1)); 3189 3190 ISD::CondCode Condition = getFCmpCondCode(predicate); 3191 auto *FPMO = cast<FPMathOperator>(&I); 3192 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3193 Condition = getFCmpCodeWithoutNaN(Condition); 3194 3195 SDNodeFlags Flags; 3196 Flags.copyFMF(*FPMO); 3197 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3198 3199 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3200 I.getType()); 3201 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3202 } 3203 3204 // Check if the condition of the select has one use or two users that are both 3205 // selects with the same condition. 3206 static bool hasOnlySelectUsers(const Value *Cond) { 3207 return llvm::all_of(Cond->users(), [](const Value *V) { 3208 return isa<SelectInst>(V); 3209 }); 3210 } 3211 3212 void SelectionDAGBuilder::visitSelect(const User &I) { 3213 SmallVector<EVT, 4> ValueVTs; 3214 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3215 ValueVTs); 3216 unsigned NumValues = ValueVTs.size(); 3217 if (NumValues == 0) return; 3218 3219 SmallVector<SDValue, 4> Values(NumValues); 3220 SDValue Cond = getValue(I.getOperand(0)); 3221 SDValue LHSVal = getValue(I.getOperand(1)); 3222 SDValue RHSVal = getValue(I.getOperand(2)); 3223 SmallVector<SDValue, 1> BaseOps(1, Cond); 3224 ISD::NodeType OpCode = 3225 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3226 3227 bool IsUnaryAbs = false; 3228 bool Negate = false; 3229 3230 SDNodeFlags Flags; 3231 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3232 Flags.copyFMF(*FPOp); 3233 3234 // Min/max matching is only viable if all output VTs are the same. 3235 if (is_splat(ValueVTs)) { 3236 EVT VT = ValueVTs[0]; 3237 LLVMContext &Ctx = *DAG.getContext(); 3238 auto &TLI = DAG.getTargetLoweringInfo(); 3239 3240 // We care about the legality of the operation after it has been type 3241 // legalized. 3242 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3243 VT = TLI.getTypeToTransformTo(Ctx, VT); 3244 3245 // If the vselect is legal, assume we want to leave this as a vector setcc + 3246 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3247 // min/max is legal on the scalar type. 3248 bool UseScalarMinMax = VT.isVector() && 3249 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3250 3251 Value *LHS, *RHS; 3252 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3253 ISD::NodeType Opc = ISD::DELETED_NODE; 3254 switch (SPR.Flavor) { 3255 case SPF_UMAX: Opc = ISD::UMAX; break; 3256 case SPF_UMIN: Opc = ISD::UMIN; break; 3257 case SPF_SMAX: Opc = ISD::SMAX; break; 3258 case SPF_SMIN: Opc = ISD::SMIN; break; 3259 case SPF_FMINNUM: 3260 switch (SPR.NaNBehavior) { 3261 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3262 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3263 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3264 case SPNB_RETURNS_ANY: { 3265 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3266 Opc = ISD::FMINNUM; 3267 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3268 Opc = ISD::FMINIMUM; 3269 else if (UseScalarMinMax) 3270 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3271 ISD::FMINNUM : ISD::FMINIMUM; 3272 break; 3273 } 3274 } 3275 break; 3276 case SPF_FMAXNUM: 3277 switch (SPR.NaNBehavior) { 3278 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3279 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3280 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3281 case SPNB_RETURNS_ANY: 3282 3283 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3284 Opc = ISD::FMAXNUM; 3285 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3286 Opc = ISD::FMAXIMUM; 3287 else if (UseScalarMinMax) 3288 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3289 ISD::FMAXNUM : ISD::FMAXIMUM; 3290 break; 3291 } 3292 break; 3293 case SPF_NABS: 3294 Negate = true; 3295 LLVM_FALLTHROUGH; 3296 case SPF_ABS: 3297 IsUnaryAbs = true; 3298 Opc = ISD::ABS; 3299 break; 3300 default: break; 3301 } 3302 3303 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3304 (TLI.isOperationLegalOrCustom(Opc, VT) || 3305 (UseScalarMinMax && 3306 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3307 // If the underlying comparison instruction is used by any other 3308 // instruction, the consumed instructions won't be destroyed, so it is 3309 // not profitable to convert to a min/max. 3310 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3311 OpCode = Opc; 3312 LHSVal = getValue(LHS); 3313 RHSVal = getValue(RHS); 3314 BaseOps.clear(); 3315 } 3316 3317 if (IsUnaryAbs) { 3318 OpCode = Opc; 3319 LHSVal = getValue(LHS); 3320 BaseOps.clear(); 3321 } 3322 } 3323 3324 if (IsUnaryAbs) { 3325 for (unsigned i = 0; i != NumValues; ++i) { 3326 SDLoc dl = getCurSDLoc(); 3327 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3328 Values[i] = 3329 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3330 if (Negate) 3331 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3332 Values[i]); 3333 } 3334 } else { 3335 for (unsigned i = 0; i != NumValues; ++i) { 3336 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3337 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3338 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3339 Values[i] = DAG.getNode( 3340 OpCode, getCurSDLoc(), 3341 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3342 } 3343 } 3344 3345 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3346 DAG.getVTList(ValueVTs), Values)); 3347 } 3348 3349 void SelectionDAGBuilder::visitTrunc(const User &I) { 3350 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3351 SDValue N = getValue(I.getOperand(0)); 3352 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3353 I.getType()); 3354 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3355 } 3356 3357 void SelectionDAGBuilder::visitZExt(const User &I) { 3358 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3359 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3360 SDValue N = getValue(I.getOperand(0)); 3361 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3362 I.getType()); 3363 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3364 } 3365 3366 void SelectionDAGBuilder::visitSExt(const User &I) { 3367 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3368 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3369 SDValue N = getValue(I.getOperand(0)); 3370 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3371 I.getType()); 3372 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3373 } 3374 3375 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3376 // FPTrunc is never a no-op cast, no need to check 3377 SDValue N = getValue(I.getOperand(0)); 3378 SDLoc dl = getCurSDLoc(); 3379 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3380 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3381 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3382 DAG.getTargetConstant( 3383 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3384 } 3385 3386 void SelectionDAGBuilder::visitFPExt(const User &I) { 3387 // FPExt is never a no-op cast, no need to check 3388 SDValue N = getValue(I.getOperand(0)); 3389 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3390 I.getType()); 3391 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3392 } 3393 3394 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3395 // FPToUI is never a no-op cast, no need to check 3396 SDValue N = getValue(I.getOperand(0)); 3397 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3398 I.getType()); 3399 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3400 } 3401 3402 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3403 // FPToSI is never a no-op cast, no need to check 3404 SDValue N = getValue(I.getOperand(0)); 3405 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3406 I.getType()); 3407 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3408 } 3409 3410 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3411 // UIToFP is never a no-op cast, no need to check 3412 SDValue N = getValue(I.getOperand(0)); 3413 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3414 I.getType()); 3415 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3416 } 3417 3418 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3419 // SIToFP is never a no-op cast, no need to check 3420 SDValue N = getValue(I.getOperand(0)); 3421 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3422 I.getType()); 3423 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3424 } 3425 3426 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3427 // What to do depends on the size of the integer and the size of the pointer. 3428 // We can either truncate, zero extend, or no-op, accordingly. 3429 SDValue N = getValue(I.getOperand(0)); 3430 auto &TLI = DAG.getTargetLoweringInfo(); 3431 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3432 I.getType()); 3433 EVT PtrMemVT = 3434 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3435 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3436 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3437 setValue(&I, N); 3438 } 3439 3440 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3441 // What to do depends on the size of the integer and the size of the pointer. 3442 // We can either truncate, zero extend, or no-op, accordingly. 3443 SDValue N = getValue(I.getOperand(0)); 3444 auto &TLI = DAG.getTargetLoweringInfo(); 3445 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3446 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3447 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3448 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3449 setValue(&I, N); 3450 } 3451 3452 void SelectionDAGBuilder::visitBitCast(const User &I) { 3453 SDValue N = getValue(I.getOperand(0)); 3454 SDLoc dl = getCurSDLoc(); 3455 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3456 I.getType()); 3457 3458 // BitCast assures us that source and destination are the same size so this is 3459 // either a BITCAST or a no-op. 3460 if (DestVT != N.getValueType()) 3461 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3462 DestVT, N)); // convert types. 3463 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3464 // might fold any kind of constant expression to an integer constant and that 3465 // is not what we are looking for. Only recognize a bitcast of a genuine 3466 // constant integer as an opaque constant. 3467 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3468 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3469 /*isOpaque*/true)); 3470 else 3471 setValue(&I, N); // noop cast. 3472 } 3473 3474 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3475 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3476 const Value *SV = I.getOperand(0); 3477 SDValue N = getValue(SV); 3478 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3479 3480 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3481 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3482 3483 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3484 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3485 3486 setValue(&I, N); 3487 } 3488 3489 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3490 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3491 SDValue InVec = getValue(I.getOperand(0)); 3492 SDValue InVal = getValue(I.getOperand(1)); 3493 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3494 TLI.getVectorIdxTy(DAG.getDataLayout())); 3495 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3496 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3497 InVec, InVal, InIdx)); 3498 } 3499 3500 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3501 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3502 SDValue InVec = getValue(I.getOperand(0)); 3503 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3504 TLI.getVectorIdxTy(DAG.getDataLayout())); 3505 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3506 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3507 InVec, InIdx)); 3508 } 3509 3510 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3511 SDValue Src1 = getValue(I.getOperand(0)); 3512 SDValue Src2 = getValue(I.getOperand(1)); 3513 ArrayRef<int> Mask; 3514 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3515 Mask = SVI->getShuffleMask(); 3516 else 3517 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3518 SDLoc DL = getCurSDLoc(); 3519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3520 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3521 EVT SrcVT = Src1.getValueType(); 3522 3523 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3524 VT.isScalableVector()) { 3525 // Canonical splat form of first element of first input vector. 3526 SDValue FirstElt = 3527 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3528 DAG.getVectorIdxConstant(0, DL)); 3529 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3530 return; 3531 } 3532 3533 // For now, we only handle splats for scalable vectors. 3534 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3535 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3536 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3537 3538 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3539 unsigned MaskNumElts = Mask.size(); 3540 3541 if (SrcNumElts == MaskNumElts) { 3542 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3543 return; 3544 } 3545 3546 // Normalize the shuffle vector since mask and vector length don't match. 3547 if (SrcNumElts < MaskNumElts) { 3548 // Mask is longer than the source vectors. We can use concatenate vector to 3549 // make the mask and vectors lengths match. 3550 3551 if (MaskNumElts % SrcNumElts == 0) { 3552 // Mask length is a multiple of the source vector length. 3553 // Check if the shuffle is some kind of concatenation of the input 3554 // vectors. 3555 unsigned NumConcat = MaskNumElts / SrcNumElts; 3556 bool IsConcat = true; 3557 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3558 for (unsigned i = 0; i != MaskNumElts; ++i) { 3559 int Idx = Mask[i]; 3560 if (Idx < 0) 3561 continue; 3562 // Ensure the indices in each SrcVT sized piece are sequential and that 3563 // the same source is used for the whole piece. 3564 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3565 (ConcatSrcs[i / SrcNumElts] >= 0 && 3566 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3567 IsConcat = false; 3568 break; 3569 } 3570 // Remember which source this index came from. 3571 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3572 } 3573 3574 // The shuffle is concatenating multiple vectors together. Just emit 3575 // a CONCAT_VECTORS operation. 3576 if (IsConcat) { 3577 SmallVector<SDValue, 8> ConcatOps; 3578 for (auto Src : ConcatSrcs) { 3579 if (Src < 0) 3580 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3581 else if (Src == 0) 3582 ConcatOps.push_back(Src1); 3583 else 3584 ConcatOps.push_back(Src2); 3585 } 3586 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3587 return; 3588 } 3589 } 3590 3591 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3592 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3593 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3594 PaddedMaskNumElts); 3595 3596 // Pad both vectors with undefs to make them the same length as the mask. 3597 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3598 3599 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3600 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3601 MOps1[0] = Src1; 3602 MOps2[0] = Src2; 3603 3604 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3605 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3606 3607 // Readjust mask for new input vector length. 3608 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3609 for (unsigned i = 0; i != MaskNumElts; ++i) { 3610 int Idx = Mask[i]; 3611 if (Idx >= (int)SrcNumElts) 3612 Idx -= SrcNumElts - PaddedMaskNumElts; 3613 MappedOps[i] = Idx; 3614 } 3615 3616 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3617 3618 // If the concatenated vector was padded, extract a subvector with the 3619 // correct number of elements. 3620 if (MaskNumElts != PaddedMaskNumElts) 3621 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3622 DAG.getVectorIdxConstant(0, DL)); 3623 3624 setValue(&I, Result); 3625 return; 3626 } 3627 3628 if (SrcNumElts > MaskNumElts) { 3629 // Analyze the access pattern of the vector to see if we can extract 3630 // two subvectors and do the shuffle. 3631 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3632 bool CanExtract = true; 3633 for (int Idx : Mask) { 3634 unsigned Input = 0; 3635 if (Idx < 0) 3636 continue; 3637 3638 if (Idx >= (int)SrcNumElts) { 3639 Input = 1; 3640 Idx -= SrcNumElts; 3641 } 3642 3643 // If all the indices come from the same MaskNumElts sized portion of 3644 // the sources we can use extract. Also make sure the extract wouldn't 3645 // extract past the end of the source. 3646 int NewStartIdx = alignDown(Idx, MaskNumElts); 3647 if (NewStartIdx + MaskNumElts > SrcNumElts || 3648 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3649 CanExtract = false; 3650 // Make sure we always update StartIdx as we use it to track if all 3651 // elements are undef. 3652 StartIdx[Input] = NewStartIdx; 3653 } 3654 3655 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3656 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3657 return; 3658 } 3659 if (CanExtract) { 3660 // Extract appropriate subvector and generate a vector shuffle 3661 for (unsigned Input = 0; Input < 2; ++Input) { 3662 SDValue &Src = Input == 0 ? Src1 : Src2; 3663 if (StartIdx[Input] < 0) 3664 Src = DAG.getUNDEF(VT); 3665 else { 3666 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3667 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3668 } 3669 } 3670 3671 // Calculate new mask. 3672 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3673 for (int &Idx : MappedOps) { 3674 if (Idx >= (int)SrcNumElts) 3675 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3676 else if (Idx >= 0) 3677 Idx -= StartIdx[0]; 3678 } 3679 3680 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3681 return; 3682 } 3683 } 3684 3685 // We can't use either concat vectors or extract subvectors so fall back to 3686 // replacing the shuffle with extract and build vector. 3687 // to insert and build vector. 3688 EVT EltVT = VT.getVectorElementType(); 3689 SmallVector<SDValue,8> Ops; 3690 for (int Idx : Mask) { 3691 SDValue Res; 3692 3693 if (Idx < 0) { 3694 Res = DAG.getUNDEF(EltVT); 3695 } else { 3696 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3697 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3698 3699 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3700 DAG.getVectorIdxConstant(Idx, DL)); 3701 } 3702 3703 Ops.push_back(Res); 3704 } 3705 3706 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3707 } 3708 3709 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3710 ArrayRef<unsigned> Indices; 3711 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3712 Indices = IV->getIndices(); 3713 else 3714 Indices = cast<ConstantExpr>(&I)->getIndices(); 3715 3716 const Value *Op0 = I.getOperand(0); 3717 const Value *Op1 = I.getOperand(1); 3718 Type *AggTy = I.getType(); 3719 Type *ValTy = Op1->getType(); 3720 bool IntoUndef = isa<UndefValue>(Op0); 3721 bool FromUndef = isa<UndefValue>(Op1); 3722 3723 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3724 3725 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3726 SmallVector<EVT, 4> AggValueVTs; 3727 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3728 SmallVector<EVT, 4> ValValueVTs; 3729 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3730 3731 unsigned NumAggValues = AggValueVTs.size(); 3732 unsigned NumValValues = ValValueVTs.size(); 3733 SmallVector<SDValue, 4> Values(NumAggValues); 3734 3735 // Ignore an insertvalue that produces an empty object 3736 if (!NumAggValues) { 3737 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3738 return; 3739 } 3740 3741 SDValue Agg = getValue(Op0); 3742 unsigned i = 0; 3743 // Copy the beginning value(s) from the original aggregate. 3744 for (; i != LinearIndex; ++i) 3745 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3746 SDValue(Agg.getNode(), Agg.getResNo() + i); 3747 // Copy values from the inserted value(s). 3748 if (NumValValues) { 3749 SDValue Val = getValue(Op1); 3750 for (; i != LinearIndex + NumValValues; ++i) 3751 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3752 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3753 } 3754 // Copy remaining value(s) from the original aggregate. 3755 for (; i != NumAggValues; ++i) 3756 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3757 SDValue(Agg.getNode(), Agg.getResNo() + i); 3758 3759 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3760 DAG.getVTList(AggValueVTs), Values)); 3761 } 3762 3763 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3764 ArrayRef<unsigned> Indices; 3765 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3766 Indices = EV->getIndices(); 3767 else 3768 Indices = cast<ConstantExpr>(&I)->getIndices(); 3769 3770 const Value *Op0 = I.getOperand(0); 3771 Type *AggTy = Op0->getType(); 3772 Type *ValTy = I.getType(); 3773 bool OutOfUndef = isa<UndefValue>(Op0); 3774 3775 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3776 3777 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3778 SmallVector<EVT, 4> ValValueVTs; 3779 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3780 3781 unsigned NumValValues = ValValueVTs.size(); 3782 3783 // Ignore a extractvalue that produces an empty object 3784 if (!NumValValues) { 3785 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3786 return; 3787 } 3788 3789 SmallVector<SDValue, 4> Values(NumValValues); 3790 3791 SDValue Agg = getValue(Op0); 3792 // Copy out the selected value(s). 3793 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3794 Values[i - LinearIndex] = 3795 OutOfUndef ? 3796 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3797 SDValue(Agg.getNode(), Agg.getResNo() + i); 3798 3799 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3800 DAG.getVTList(ValValueVTs), Values)); 3801 } 3802 3803 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3804 Value *Op0 = I.getOperand(0); 3805 // Note that the pointer operand may be a vector of pointers. Take the scalar 3806 // element which holds a pointer. 3807 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3808 SDValue N = getValue(Op0); 3809 SDLoc dl = getCurSDLoc(); 3810 auto &TLI = DAG.getTargetLoweringInfo(); 3811 3812 // Normalize Vector GEP - all scalar operands should be converted to the 3813 // splat vector. 3814 bool IsVectorGEP = I.getType()->isVectorTy(); 3815 ElementCount VectorElementCount = 3816 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3817 : ElementCount::getFixed(0); 3818 3819 if (IsVectorGEP && !N.getValueType().isVector()) { 3820 LLVMContext &Context = *DAG.getContext(); 3821 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3822 if (VectorElementCount.isScalable()) 3823 N = DAG.getSplatVector(VT, dl, N); 3824 else 3825 N = DAG.getSplatBuildVector(VT, dl, N); 3826 } 3827 3828 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3829 GTI != E; ++GTI) { 3830 const Value *Idx = GTI.getOperand(); 3831 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3832 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3833 if (Field) { 3834 // N = N + Offset 3835 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3836 3837 // In an inbounds GEP with an offset that is nonnegative even when 3838 // interpreted as signed, assume there is no unsigned overflow. 3839 SDNodeFlags Flags; 3840 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3841 Flags.setNoUnsignedWrap(true); 3842 3843 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3844 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3845 } 3846 } else { 3847 // IdxSize is the width of the arithmetic according to IR semantics. 3848 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3849 // (and fix up the result later). 3850 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3851 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3852 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3853 // We intentionally mask away the high bits here; ElementSize may not 3854 // fit in IdxTy. 3855 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3856 bool ElementScalable = ElementSize.isScalable(); 3857 3858 // If this is a scalar constant or a splat vector of constants, 3859 // handle it quickly. 3860 const auto *C = dyn_cast<Constant>(Idx); 3861 if (C && isa<VectorType>(C->getType())) 3862 C = C->getSplatValue(); 3863 3864 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3865 if (CI && CI->isZero()) 3866 continue; 3867 if (CI && !ElementScalable) { 3868 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3869 LLVMContext &Context = *DAG.getContext(); 3870 SDValue OffsVal; 3871 if (IsVectorGEP) 3872 OffsVal = DAG.getConstant( 3873 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3874 else 3875 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3876 3877 // In an inbounds GEP with an offset that is nonnegative even when 3878 // interpreted as signed, assume there is no unsigned overflow. 3879 SDNodeFlags Flags; 3880 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3881 Flags.setNoUnsignedWrap(true); 3882 3883 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3884 3885 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3886 continue; 3887 } 3888 3889 // N = N + Idx * ElementMul; 3890 SDValue IdxN = getValue(Idx); 3891 3892 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3893 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3894 VectorElementCount); 3895 if (VectorElementCount.isScalable()) 3896 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3897 else 3898 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3899 } 3900 3901 // If the index is smaller or larger than intptr_t, truncate or extend 3902 // it. 3903 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3904 3905 if (ElementScalable) { 3906 EVT VScaleTy = N.getValueType().getScalarType(); 3907 SDValue VScale = DAG.getNode( 3908 ISD::VSCALE, dl, VScaleTy, 3909 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3910 if (IsVectorGEP) 3911 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3912 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3913 } else { 3914 // If this is a multiply by a power of two, turn it into a shl 3915 // immediately. This is a very common case. 3916 if (ElementMul != 1) { 3917 if (ElementMul.isPowerOf2()) { 3918 unsigned Amt = ElementMul.logBase2(); 3919 IdxN = DAG.getNode(ISD::SHL, dl, 3920 N.getValueType(), IdxN, 3921 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3922 } else { 3923 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3924 IdxN.getValueType()); 3925 IdxN = DAG.getNode(ISD::MUL, dl, 3926 N.getValueType(), IdxN, Scale); 3927 } 3928 } 3929 } 3930 3931 N = DAG.getNode(ISD::ADD, dl, 3932 N.getValueType(), N, IdxN); 3933 } 3934 } 3935 3936 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3937 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3938 if (IsVectorGEP) { 3939 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3940 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3941 } 3942 3943 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3944 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3945 3946 setValue(&I, N); 3947 } 3948 3949 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3950 // If this is a fixed sized alloca in the entry block of the function, 3951 // allocate it statically on the stack. 3952 if (FuncInfo.StaticAllocaMap.count(&I)) 3953 return; // getValue will auto-populate this. 3954 3955 SDLoc dl = getCurSDLoc(); 3956 Type *Ty = I.getAllocatedType(); 3957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3958 auto &DL = DAG.getDataLayout(); 3959 uint64_t TySize = DL.getTypeAllocSize(Ty); 3960 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3961 3962 SDValue AllocSize = getValue(I.getArraySize()); 3963 3964 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3965 if (AllocSize.getValueType() != IntPtr) 3966 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3967 3968 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3969 AllocSize, 3970 DAG.getConstant(TySize, dl, IntPtr)); 3971 3972 // Handle alignment. If the requested alignment is less than or equal to 3973 // the stack alignment, ignore it. If the size is greater than or equal to 3974 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3975 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3976 if (*Alignment <= StackAlign) 3977 Alignment = None; 3978 3979 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3980 // Round the size of the allocation up to the stack alignment size 3981 // by add SA-1 to the size. This doesn't overflow because we're computing 3982 // an address inside an alloca. 3983 SDNodeFlags Flags; 3984 Flags.setNoUnsignedWrap(true); 3985 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3986 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3987 3988 // Mask out the low bits for alignment purposes. 3989 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3990 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3991 3992 SDValue Ops[] = { 3993 getRoot(), AllocSize, 3994 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3995 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3996 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3997 setValue(&I, DSA); 3998 DAG.setRoot(DSA.getValue(1)); 3999 4000 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4001 } 4002 4003 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4004 if (I.isAtomic()) 4005 return visitAtomicLoad(I); 4006 4007 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4008 const Value *SV = I.getOperand(0); 4009 if (TLI.supportSwiftError()) { 4010 // Swifterror values can come from either a function parameter with 4011 // swifterror attribute or an alloca with swifterror attribute. 4012 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4013 if (Arg->hasSwiftErrorAttr()) 4014 return visitLoadFromSwiftError(I); 4015 } 4016 4017 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4018 if (Alloca->isSwiftError()) 4019 return visitLoadFromSwiftError(I); 4020 } 4021 } 4022 4023 SDValue Ptr = getValue(SV); 4024 4025 Type *Ty = I.getType(); 4026 Align Alignment = I.getAlign(); 4027 4028 AAMDNodes AAInfo; 4029 I.getAAMetadata(AAInfo); 4030 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4031 4032 SmallVector<EVT, 4> ValueVTs, MemVTs; 4033 SmallVector<uint64_t, 4> Offsets; 4034 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4035 unsigned NumValues = ValueVTs.size(); 4036 if (NumValues == 0) 4037 return; 4038 4039 bool isVolatile = I.isVolatile(); 4040 4041 SDValue Root; 4042 bool ConstantMemory = false; 4043 if (isVolatile) 4044 // Serialize volatile loads with other side effects. 4045 Root = getRoot(); 4046 else if (NumValues > MaxParallelChains) 4047 Root = getMemoryRoot(); 4048 else if (AA && 4049 AA->pointsToConstantMemory(MemoryLocation( 4050 SV, 4051 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4052 AAInfo))) { 4053 // Do not serialize (non-volatile) loads of constant memory with anything. 4054 Root = DAG.getEntryNode(); 4055 ConstantMemory = true; 4056 } else { 4057 // Do not serialize non-volatile loads against each other. 4058 Root = DAG.getRoot(); 4059 } 4060 4061 SDLoc dl = getCurSDLoc(); 4062 4063 if (isVolatile) 4064 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4065 4066 // An aggregate load cannot wrap around the address space, so offsets to its 4067 // parts don't wrap either. 4068 SDNodeFlags Flags; 4069 Flags.setNoUnsignedWrap(true); 4070 4071 SmallVector<SDValue, 4> Values(NumValues); 4072 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4073 EVT PtrVT = Ptr.getValueType(); 4074 4075 MachineMemOperand::Flags MMOFlags 4076 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4077 4078 unsigned ChainI = 0; 4079 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4080 // Serializing loads here may result in excessive register pressure, and 4081 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4082 // could recover a bit by hoisting nodes upward in the chain by recognizing 4083 // they are side-effect free or do not alias. The optimizer should really 4084 // avoid this case by converting large object/array copies to llvm.memcpy 4085 // (MaxParallelChains should always remain as failsafe). 4086 if (ChainI == MaxParallelChains) { 4087 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4088 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4089 makeArrayRef(Chains.data(), ChainI)); 4090 Root = Chain; 4091 ChainI = 0; 4092 } 4093 SDValue A = DAG.getNode(ISD::ADD, dl, 4094 PtrVT, Ptr, 4095 DAG.getConstant(Offsets[i], dl, PtrVT), 4096 Flags); 4097 4098 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4099 MachinePointerInfo(SV, Offsets[i]), Alignment, 4100 MMOFlags, AAInfo, Ranges); 4101 Chains[ChainI] = L.getValue(1); 4102 4103 if (MemVTs[i] != ValueVTs[i]) 4104 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4105 4106 Values[i] = L; 4107 } 4108 4109 if (!ConstantMemory) { 4110 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4111 makeArrayRef(Chains.data(), ChainI)); 4112 if (isVolatile) 4113 DAG.setRoot(Chain); 4114 else 4115 PendingLoads.push_back(Chain); 4116 } 4117 4118 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4119 DAG.getVTList(ValueVTs), Values)); 4120 } 4121 4122 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4123 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4124 "call visitStoreToSwiftError when backend supports swifterror"); 4125 4126 SmallVector<EVT, 4> ValueVTs; 4127 SmallVector<uint64_t, 4> Offsets; 4128 const Value *SrcV = I.getOperand(0); 4129 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4130 SrcV->getType(), ValueVTs, &Offsets); 4131 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4132 "expect a single EVT for swifterror"); 4133 4134 SDValue Src = getValue(SrcV); 4135 // Create a virtual register, then update the virtual register. 4136 Register VReg = 4137 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4138 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4139 // Chain can be getRoot or getControlRoot. 4140 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4141 SDValue(Src.getNode(), Src.getResNo())); 4142 DAG.setRoot(CopyNode); 4143 } 4144 4145 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4146 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4147 "call visitLoadFromSwiftError when backend supports swifterror"); 4148 4149 assert(!I.isVolatile() && 4150 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4151 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4152 "Support volatile, non temporal, invariant for load_from_swift_error"); 4153 4154 const Value *SV = I.getOperand(0); 4155 Type *Ty = I.getType(); 4156 AAMDNodes AAInfo; 4157 I.getAAMetadata(AAInfo); 4158 assert( 4159 (!AA || 4160 !AA->pointsToConstantMemory(MemoryLocation( 4161 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4162 AAInfo))) && 4163 "load_from_swift_error should not be constant memory"); 4164 4165 SmallVector<EVT, 4> ValueVTs; 4166 SmallVector<uint64_t, 4> Offsets; 4167 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4168 ValueVTs, &Offsets); 4169 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4170 "expect a single EVT for swifterror"); 4171 4172 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4173 SDValue L = DAG.getCopyFromReg( 4174 getRoot(), getCurSDLoc(), 4175 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4176 4177 setValue(&I, L); 4178 } 4179 4180 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4181 if (I.isAtomic()) 4182 return visitAtomicStore(I); 4183 4184 const Value *SrcV = I.getOperand(0); 4185 const Value *PtrV = I.getOperand(1); 4186 4187 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4188 if (TLI.supportSwiftError()) { 4189 // Swifterror values can come from either a function parameter with 4190 // swifterror attribute or an alloca with swifterror attribute. 4191 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4192 if (Arg->hasSwiftErrorAttr()) 4193 return visitStoreToSwiftError(I); 4194 } 4195 4196 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4197 if (Alloca->isSwiftError()) 4198 return visitStoreToSwiftError(I); 4199 } 4200 } 4201 4202 SmallVector<EVT, 4> ValueVTs, MemVTs; 4203 SmallVector<uint64_t, 4> Offsets; 4204 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4205 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4206 unsigned NumValues = ValueVTs.size(); 4207 if (NumValues == 0) 4208 return; 4209 4210 // Get the lowered operands. Note that we do this after 4211 // checking if NumResults is zero, because with zero results 4212 // the operands won't have values in the map. 4213 SDValue Src = getValue(SrcV); 4214 SDValue Ptr = getValue(PtrV); 4215 4216 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4217 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4218 SDLoc dl = getCurSDLoc(); 4219 Align Alignment = I.getAlign(); 4220 AAMDNodes AAInfo; 4221 I.getAAMetadata(AAInfo); 4222 4223 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4224 4225 // An aggregate load cannot wrap around the address space, so offsets to its 4226 // parts don't wrap either. 4227 SDNodeFlags Flags; 4228 Flags.setNoUnsignedWrap(true); 4229 4230 unsigned ChainI = 0; 4231 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4232 // See visitLoad comments. 4233 if (ChainI == MaxParallelChains) { 4234 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4235 makeArrayRef(Chains.data(), ChainI)); 4236 Root = Chain; 4237 ChainI = 0; 4238 } 4239 SDValue Add = 4240 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4241 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4242 if (MemVTs[i] != ValueVTs[i]) 4243 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4244 SDValue St = 4245 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4246 Alignment, MMOFlags, AAInfo); 4247 Chains[ChainI] = St; 4248 } 4249 4250 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4251 makeArrayRef(Chains.data(), ChainI)); 4252 DAG.setRoot(StoreNode); 4253 } 4254 4255 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4256 bool IsCompressing) { 4257 SDLoc sdl = getCurSDLoc(); 4258 4259 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4260 MaybeAlign &Alignment) { 4261 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4262 Src0 = I.getArgOperand(0); 4263 Ptr = I.getArgOperand(1); 4264 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4265 Mask = I.getArgOperand(3); 4266 }; 4267 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4268 MaybeAlign &Alignment) { 4269 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4270 Src0 = I.getArgOperand(0); 4271 Ptr = I.getArgOperand(1); 4272 Mask = I.getArgOperand(2); 4273 Alignment = None; 4274 }; 4275 4276 Value *PtrOperand, *MaskOperand, *Src0Operand; 4277 MaybeAlign Alignment; 4278 if (IsCompressing) 4279 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4280 else 4281 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4282 4283 SDValue Ptr = getValue(PtrOperand); 4284 SDValue Src0 = getValue(Src0Operand); 4285 SDValue Mask = getValue(MaskOperand); 4286 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4287 4288 EVT VT = Src0.getValueType(); 4289 if (!Alignment) 4290 Alignment = DAG.getEVTAlign(VT); 4291 4292 AAMDNodes AAInfo; 4293 I.getAAMetadata(AAInfo); 4294 4295 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4296 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4297 // TODO: Make MachineMemOperands aware of scalable 4298 // vectors. 4299 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4300 SDValue StoreNode = 4301 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4302 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4303 DAG.setRoot(StoreNode); 4304 setValue(&I, StoreNode); 4305 } 4306 4307 // Get a uniform base for the Gather/Scatter intrinsic. 4308 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4309 // We try to represent it as a base pointer + vector of indices. 4310 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4311 // The first operand of the GEP may be a single pointer or a vector of pointers 4312 // Example: 4313 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4314 // or 4315 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4316 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4317 // 4318 // When the first GEP operand is a single pointer - it is the uniform base we 4319 // are looking for. If first operand of the GEP is a splat vector - we 4320 // extract the splat value and use it as a uniform base. 4321 // In all other cases the function returns 'false'. 4322 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4323 ISD::MemIndexType &IndexType, SDValue &Scale, 4324 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4325 SelectionDAG& DAG = SDB->DAG; 4326 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4327 const DataLayout &DL = DAG.getDataLayout(); 4328 4329 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4330 4331 // Handle splat constant pointer. 4332 if (auto *C = dyn_cast<Constant>(Ptr)) { 4333 C = C->getSplatValue(); 4334 if (!C) 4335 return false; 4336 4337 Base = SDB->getValue(C); 4338 4339 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4340 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4341 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4342 IndexType = ISD::SIGNED_SCALED; 4343 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4344 return true; 4345 } 4346 4347 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4348 if (!GEP || GEP->getParent() != CurBB) 4349 return false; 4350 4351 if (GEP->getNumOperands() != 2) 4352 return false; 4353 4354 const Value *BasePtr = GEP->getPointerOperand(); 4355 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4356 4357 // Make sure the base is scalar and the index is a vector. 4358 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4359 return false; 4360 4361 Base = SDB->getValue(BasePtr); 4362 Index = SDB->getValue(IndexVal); 4363 IndexType = ISD::SIGNED_SCALED; 4364 Scale = DAG.getTargetConstant( 4365 DL.getTypeAllocSize(GEP->getResultElementType()), 4366 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4367 return true; 4368 } 4369 4370 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4371 SDLoc sdl = getCurSDLoc(); 4372 4373 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4374 const Value *Ptr = I.getArgOperand(1); 4375 SDValue Src0 = getValue(I.getArgOperand(0)); 4376 SDValue Mask = getValue(I.getArgOperand(3)); 4377 EVT VT = Src0.getValueType(); 4378 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4379 ->getMaybeAlignValue() 4380 .getValueOr(DAG.getEVTAlign(VT)); 4381 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4382 4383 AAMDNodes AAInfo; 4384 I.getAAMetadata(AAInfo); 4385 4386 SDValue Base; 4387 SDValue Index; 4388 ISD::MemIndexType IndexType; 4389 SDValue Scale; 4390 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4391 I.getParent()); 4392 4393 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4394 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4395 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4396 // TODO: Make MachineMemOperands aware of scalable 4397 // vectors. 4398 MemoryLocation::UnknownSize, Alignment, AAInfo); 4399 if (!UniformBase) { 4400 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4401 Index = getValue(Ptr); 4402 IndexType = ISD::SIGNED_UNSCALED; 4403 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4404 } 4405 4406 EVT IdxVT = Index.getValueType(); 4407 EVT EltTy = IdxVT.getVectorElementType(); 4408 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4409 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4410 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4411 } 4412 4413 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4414 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4415 Ops, MMO, IndexType, false); 4416 DAG.setRoot(Scatter); 4417 setValue(&I, Scatter); 4418 } 4419 4420 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4421 SDLoc sdl = getCurSDLoc(); 4422 4423 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4424 MaybeAlign &Alignment) { 4425 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4426 Ptr = I.getArgOperand(0); 4427 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4428 Mask = I.getArgOperand(2); 4429 Src0 = I.getArgOperand(3); 4430 }; 4431 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4432 MaybeAlign &Alignment) { 4433 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4434 Ptr = I.getArgOperand(0); 4435 Alignment = None; 4436 Mask = I.getArgOperand(1); 4437 Src0 = I.getArgOperand(2); 4438 }; 4439 4440 Value *PtrOperand, *MaskOperand, *Src0Operand; 4441 MaybeAlign Alignment; 4442 if (IsExpanding) 4443 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4444 else 4445 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4446 4447 SDValue Ptr = getValue(PtrOperand); 4448 SDValue Src0 = getValue(Src0Operand); 4449 SDValue Mask = getValue(MaskOperand); 4450 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4451 4452 EVT VT = Src0.getValueType(); 4453 if (!Alignment) 4454 Alignment = DAG.getEVTAlign(VT); 4455 4456 AAMDNodes AAInfo; 4457 I.getAAMetadata(AAInfo); 4458 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4459 4460 // Do not serialize masked loads of constant memory with anything. 4461 MemoryLocation ML; 4462 if (VT.isScalableVector()) 4463 ML = MemoryLocation::getAfter(PtrOperand); 4464 else 4465 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4466 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4467 AAInfo); 4468 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4469 4470 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4471 4472 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4473 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4474 // TODO: Make MachineMemOperands aware of scalable 4475 // vectors. 4476 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4477 4478 SDValue Load = 4479 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4480 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4481 if (AddToChain) 4482 PendingLoads.push_back(Load.getValue(1)); 4483 setValue(&I, Load); 4484 } 4485 4486 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4487 SDLoc sdl = getCurSDLoc(); 4488 4489 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4490 const Value *Ptr = I.getArgOperand(0); 4491 SDValue Src0 = getValue(I.getArgOperand(3)); 4492 SDValue Mask = getValue(I.getArgOperand(2)); 4493 4494 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4495 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4496 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4497 ->getMaybeAlignValue() 4498 .getValueOr(DAG.getEVTAlign(VT)); 4499 4500 AAMDNodes AAInfo; 4501 I.getAAMetadata(AAInfo); 4502 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4503 4504 SDValue Root = DAG.getRoot(); 4505 SDValue Base; 4506 SDValue Index; 4507 ISD::MemIndexType IndexType; 4508 SDValue Scale; 4509 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4510 I.getParent()); 4511 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4512 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4513 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4514 // TODO: Make MachineMemOperands aware of scalable 4515 // vectors. 4516 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4517 4518 if (!UniformBase) { 4519 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4520 Index = getValue(Ptr); 4521 IndexType = ISD::SIGNED_UNSCALED; 4522 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4523 } 4524 4525 EVT IdxVT = Index.getValueType(); 4526 EVT EltTy = IdxVT.getVectorElementType(); 4527 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4528 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4529 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4530 } 4531 4532 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4533 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4534 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4535 4536 PendingLoads.push_back(Gather.getValue(1)); 4537 setValue(&I, Gather); 4538 } 4539 4540 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4541 SDLoc dl = getCurSDLoc(); 4542 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4543 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4544 SyncScope::ID SSID = I.getSyncScopeID(); 4545 4546 SDValue InChain = getRoot(); 4547 4548 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4549 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4550 4551 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4552 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4553 4554 MachineFunction &MF = DAG.getMachineFunction(); 4555 MachineMemOperand *MMO = MF.getMachineMemOperand( 4556 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4557 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4558 FailureOrdering); 4559 4560 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4561 dl, MemVT, VTs, InChain, 4562 getValue(I.getPointerOperand()), 4563 getValue(I.getCompareOperand()), 4564 getValue(I.getNewValOperand()), MMO); 4565 4566 SDValue OutChain = L.getValue(2); 4567 4568 setValue(&I, L); 4569 DAG.setRoot(OutChain); 4570 } 4571 4572 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4573 SDLoc dl = getCurSDLoc(); 4574 ISD::NodeType NT; 4575 switch (I.getOperation()) { 4576 default: llvm_unreachable("Unknown atomicrmw operation"); 4577 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4578 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4579 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4580 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4581 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4582 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4583 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4584 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4585 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4586 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4587 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4588 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4589 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4590 } 4591 AtomicOrdering Ordering = I.getOrdering(); 4592 SyncScope::ID SSID = I.getSyncScopeID(); 4593 4594 SDValue InChain = getRoot(); 4595 4596 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4597 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4598 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4599 4600 MachineFunction &MF = DAG.getMachineFunction(); 4601 MachineMemOperand *MMO = MF.getMachineMemOperand( 4602 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4603 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4604 4605 SDValue L = 4606 DAG.getAtomic(NT, dl, MemVT, InChain, 4607 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4608 MMO); 4609 4610 SDValue OutChain = L.getValue(1); 4611 4612 setValue(&I, L); 4613 DAG.setRoot(OutChain); 4614 } 4615 4616 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4617 SDLoc dl = getCurSDLoc(); 4618 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4619 SDValue Ops[3]; 4620 Ops[0] = getRoot(); 4621 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4622 TLI.getFenceOperandTy(DAG.getDataLayout())); 4623 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4624 TLI.getFenceOperandTy(DAG.getDataLayout())); 4625 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4626 } 4627 4628 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4629 SDLoc dl = getCurSDLoc(); 4630 AtomicOrdering Order = I.getOrdering(); 4631 SyncScope::ID SSID = I.getSyncScopeID(); 4632 4633 SDValue InChain = getRoot(); 4634 4635 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4636 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4637 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4638 4639 if (!TLI.supportsUnalignedAtomics() && 4640 I.getAlignment() < MemVT.getSizeInBits() / 8) 4641 report_fatal_error("Cannot generate unaligned atomic load"); 4642 4643 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4644 4645 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4646 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4647 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4648 4649 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4650 4651 SDValue Ptr = getValue(I.getPointerOperand()); 4652 4653 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4654 // TODO: Once this is better exercised by tests, it should be merged with 4655 // the normal path for loads to prevent future divergence. 4656 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4657 if (MemVT != VT) 4658 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4659 4660 setValue(&I, L); 4661 SDValue OutChain = L.getValue(1); 4662 if (!I.isUnordered()) 4663 DAG.setRoot(OutChain); 4664 else 4665 PendingLoads.push_back(OutChain); 4666 return; 4667 } 4668 4669 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4670 Ptr, MMO); 4671 4672 SDValue OutChain = L.getValue(1); 4673 if (MemVT != VT) 4674 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4675 4676 setValue(&I, L); 4677 DAG.setRoot(OutChain); 4678 } 4679 4680 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4681 SDLoc dl = getCurSDLoc(); 4682 4683 AtomicOrdering Ordering = I.getOrdering(); 4684 SyncScope::ID SSID = I.getSyncScopeID(); 4685 4686 SDValue InChain = getRoot(); 4687 4688 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4689 EVT MemVT = 4690 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4691 4692 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4693 report_fatal_error("Cannot generate unaligned atomic store"); 4694 4695 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4696 4697 MachineFunction &MF = DAG.getMachineFunction(); 4698 MachineMemOperand *MMO = MF.getMachineMemOperand( 4699 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4700 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4701 4702 SDValue Val = getValue(I.getValueOperand()); 4703 if (Val.getValueType() != MemVT) 4704 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4705 SDValue Ptr = getValue(I.getPointerOperand()); 4706 4707 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4708 // TODO: Once this is better exercised by tests, it should be merged with 4709 // the normal path for stores to prevent future divergence. 4710 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4711 DAG.setRoot(S); 4712 return; 4713 } 4714 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4715 Ptr, Val, MMO); 4716 4717 4718 DAG.setRoot(OutChain); 4719 } 4720 4721 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4722 /// node. 4723 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4724 unsigned Intrinsic) { 4725 // Ignore the callsite's attributes. A specific call site may be marked with 4726 // readnone, but the lowering code will expect the chain based on the 4727 // definition. 4728 const Function *F = I.getCalledFunction(); 4729 bool HasChain = !F->doesNotAccessMemory(); 4730 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4731 4732 // Build the operand list. 4733 SmallVector<SDValue, 8> Ops; 4734 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4735 if (OnlyLoad) { 4736 // We don't need to serialize loads against other loads. 4737 Ops.push_back(DAG.getRoot()); 4738 } else { 4739 Ops.push_back(getRoot()); 4740 } 4741 } 4742 4743 // Info is set by getTgtMemInstrinsic 4744 TargetLowering::IntrinsicInfo Info; 4745 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4746 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4747 DAG.getMachineFunction(), 4748 Intrinsic); 4749 4750 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4751 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4752 Info.opc == ISD::INTRINSIC_W_CHAIN) 4753 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4754 TLI.getPointerTy(DAG.getDataLayout()))); 4755 4756 // Add all operands of the call to the operand list. 4757 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4758 const Value *Arg = I.getArgOperand(i); 4759 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4760 Ops.push_back(getValue(Arg)); 4761 continue; 4762 } 4763 4764 // Use TargetConstant instead of a regular constant for immarg. 4765 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4766 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4767 assert(CI->getBitWidth() <= 64 && 4768 "large intrinsic immediates not handled"); 4769 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4770 } else { 4771 Ops.push_back( 4772 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4773 } 4774 } 4775 4776 SmallVector<EVT, 4> ValueVTs; 4777 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4778 4779 if (HasChain) 4780 ValueVTs.push_back(MVT::Other); 4781 4782 SDVTList VTs = DAG.getVTList(ValueVTs); 4783 4784 // Create the node. 4785 SDValue Result; 4786 if (IsTgtIntrinsic) { 4787 // This is target intrinsic that touches memory 4788 AAMDNodes AAInfo; 4789 I.getAAMetadata(AAInfo); 4790 Result = 4791 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4792 MachinePointerInfo(Info.ptrVal, Info.offset), 4793 Info.align, Info.flags, Info.size, AAInfo); 4794 } else if (!HasChain) { 4795 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4796 } else if (!I.getType()->isVoidTy()) { 4797 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4798 } else { 4799 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4800 } 4801 4802 if (HasChain) { 4803 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4804 if (OnlyLoad) 4805 PendingLoads.push_back(Chain); 4806 else 4807 DAG.setRoot(Chain); 4808 } 4809 4810 if (!I.getType()->isVoidTy()) { 4811 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4812 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4813 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4814 } else 4815 Result = lowerRangeToAssertZExt(DAG, I, Result); 4816 4817 MaybeAlign Alignment = I.getRetAlign(); 4818 if (!Alignment) 4819 Alignment = F->getAttributes().getRetAlignment(); 4820 // Insert `assertalign` node if there's an alignment. 4821 if (InsertAssertAlign && Alignment) { 4822 Result = 4823 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4824 } 4825 4826 setValue(&I, Result); 4827 } 4828 } 4829 4830 /// GetSignificand - Get the significand and build it into a floating-point 4831 /// number with exponent of 1: 4832 /// 4833 /// Op = (Op & 0x007fffff) | 0x3f800000; 4834 /// 4835 /// where Op is the hexadecimal representation of floating point value. 4836 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4837 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4838 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4839 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4840 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4841 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4842 } 4843 4844 /// GetExponent - Get the exponent: 4845 /// 4846 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4847 /// 4848 /// where Op is the hexadecimal representation of floating point value. 4849 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4850 const TargetLowering &TLI, const SDLoc &dl) { 4851 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4852 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4853 SDValue t1 = DAG.getNode( 4854 ISD::SRL, dl, MVT::i32, t0, 4855 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4856 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4857 DAG.getConstant(127, dl, MVT::i32)); 4858 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4859 } 4860 4861 /// getF32Constant - Get 32-bit floating point constant. 4862 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4863 const SDLoc &dl) { 4864 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4865 MVT::f32); 4866 } 4867 4868 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4869 SelectionDAG &DAG) { 4870 // TODO: What fast-math-flags should be set on the floating-point nodes? 4871 4872 // IntegerPartOfX = ((int32_t)(t0); 4873 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4874 4875 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4876 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4877 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4878 4879 // IntegerPartOfX <<= 23; 4880 IntegerPartOfX = DAG.getNode( 4881 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4882 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4883 DAG.getDataLayout()))); 4884 4885 SDValue TwoToFractionalPartOfX; 4886 if (LimitFloatPrecision <= 6) { 4887 // For floating-point precision of 6: 4888 // 4889 // TwoToFractionalPartOfX = 4890 // 0.997535578f + 4891 // (0.735607626f + 0.252464424f * x) * x; 4892 // 4893 // error 0.0144103317, which is 6 bits 4894 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4895 getF32Constant(DAG, 0x3e814304, dl)); 4896 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4897 getF32Constant(DAG, 0x3f3c50c8, dl)); 4898 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4899 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4900 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4901 } else if (LimitFloatPrecision <= 12) { 4902 // For floating-point precision of 12: 4903 // 4904 // TwoToFractionalPartOfX = 4905 // 0.999892986f + 4906 // (0.696457318f + 4907 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4908 // 4909 // error 0.000107046256, which is 13 to 14 bits 4910 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4911 getF32Constant(DAG, 0x3da235e3, dl)); 4912 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4913 getF32Constant(DAG, 0x3e65b8f3, dl)); 4914 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4915 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4916 getF32Constant(DAG, 0x3f324b07, dl)); 4917 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4918 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4919 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4920 } else { // LimitFloatPrecision <= 18 4921 // For floating-point precision of 18: 4922 // 4923 // TwoToFractionalPartOfX = 4924 // 0.999999982f + 4925 // (0.693148872f + 4926 // (0.240227044f + 4927 // (0.554906021e-1f + 4928 // (0.961591928e-2f + 4929 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4930 // error 2.47208000*10^(-7), which is better than 18 bits 4931 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4932 getF32Constant(DAG, 0x3924b03e, dl)); 4933 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4934 getF32Constant(DAG, 0x3ab24b87, dl)); 4935 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4936 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4937 getF32Constant(DAG, 0x3c1d8c17, dl)); 4938 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4939 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4940 getF32Constant(DAG, 0x3d634a1d, dl)); 4941 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4942 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4943 getF32Constant(DAG, 0x3e75fe14, dl)); 4944 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4945 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4946 getF32Constant(DAG, 0x3f317234, dl)); 4947 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4948 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4949 getF32Constant(DAG, 0x3f800000, dl)); 4950 } 4951 4952 // Add the exponent into the result in integer domain. 4953 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4954 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4955 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4956 } 4957 4958 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4959 /// limited-precision mode. 4960 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4961 const TargetLowering &TLI, SDNodeFlags Flags) { 4962 if (Op.getValueType() == MVT::f32 && 4963 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4964 4965 // Put the exponent in the right bit position for later addition to the 4966 // final result: 4967 // 4968 // t0 = Op * log2(e) 4969 4970 // TODO: What fast-math-flags should be set here? 4971 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4972 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4973 return getLimitedPrecisionExp2(t0, dl, DAG); 4974 } 4975 4976 // No special expansion. 4977 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 4978 } 4979 4980 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4981 /// limited-precision mode. 4982 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4983 const TargetLowering &TLI, SDNodeFlags Flags) { 4984 // TODO: What fast-math-flags should be set on the floating-point nodes? 4985 4986 if (Op.getValueType() == MVT::f32 && 4987 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4988 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4989 4990 // Scale the exponent by log(2). 4991 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4992 SDValue LogOfExponent = 4993 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4994 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4995 4996 // Get the significand and build it into a floating-point number with 4997 // exponent of 1. 4998 SDValue X = GetSignificand(DAG, Op1, dl); 4999 5000 SDValue LogOfMantissa; 5001 if (LimitFloatPrecision <= 6) { 5002 // For floating-point precision of 6: 5003 // 5004 // LogofMantissa = 5005 // -1.1609546f + 5006 // (1.4034025f - 0.23903021f * x) * x; 5007 // 5008 // error 0.0034276066, which is better than 8 bits 5009 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5010 getF32Constant(DAG, 0xbe74c456, dl)); 5011 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5012 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5013 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5014 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5015 getF32Constant(DAG, 0x3f949a29, dl)); 5016 } else if (LimitFloatPrecision <= 12) { 5017 // For floating-point precision of 12: 5018 // 5019 // LogOfMantissa = 5020 // -1.7417939f + 5021 // (2.8212026f + 5022 // (-1.4699568f + 5023 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5024 // 5025 // error 0.000061011436, which is 14 bits 5026 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5027 getF32Constant(DAG, 0xbd67b6d6, dl)); 5028 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5029 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5030 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5031 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5032 getF32Constant(DAG, 0x3fbc278b, dl)); 5033 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5034 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5035 getF32Constant(DAG, 0x40348e95, dl)); 5036 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5037 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5038 getF32Constant(DAG, 0x3fdef31a, dl)); 5039 } else { // LimitFloatPrecision <= 18 5040 // For floating-point precision of 18: 5041 // 5042 // LogOfMantissa = 5043 // -2.1072184f + 5044 // (4.2372794f + 5045 // (-3.7029485f + 5046 // (2.2781945f + 5047 // (-0.87823314f + 5048 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5049 // 5050 // error 0.0000023660568, which is better than 18 bits 5051 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5052 getF32Constant(DAG, 0xbc91e5ac, dl)); 5053 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5054 getF32Constant(DAG, 0x3e4350aa, dl)); 5055 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5056 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5057 getF32Constant(DAG, 0x3f60d3e3, dl)); 5058 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5059 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5060 getF32Constant(DAG, 0x4011cdf0, dl)); 5061 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5062 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5063 getF32Constant(DAG, 0x406cfd1c, dl)); 5064 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5065 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5066 getF32Constant(DAG, 0x408797cb, dl)); 5067 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5068 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5069 getF32Constant(DAG, 0x4006dcab, dl)); 5070 } 5071 5072 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5073 } 5074 5075 // No special expansion. 5076 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5077 } 5078 5079 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5080 /// limited-precision mode. 5081 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5082 const TargetLowering &TLI, SDNodeFlags Flags) { 5083 // TODO: What fast-math-flags should be set on the floating-point nodes? 5084 5085 if (Op.getValueType() == MVT::f32 && 5086 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5087 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5088 5089 // Get the exponent. 5090 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5091 5092 // Get the significand and build it into a floating-point number with 5093 // exponent of 1. 5094 SDValue X = GetSignificand(DAG, Op1, dl); 5095 5096 // Different possible minimax approximations of significand in 5097 // floating-point for various degrees of accuracy over [1,2]. 5098 SDValue Log2ofMantissa; 5099 if (LimitFloatPrecision <= 6) { 5100 // For floating-point precision of 6: 5101 // 5102 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5103 // 5104 // error 0.0049451742, which is more than 7 bits 5105 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5106 getF32Constant(DAG, 0xbeb08fe0, dl)); 5107 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5108 getF32Constant(DAG, 0x40019463, dl)); 5109 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5110 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5111 getF32Constant(DAG, 0x3fd6633d, dl)); 5112 } else if (LimitFloatPrecision <= 12) { 5113 // For floating-point precision of 12: 5114 // 5115 // Log2ofMantissa = 5116 // -2.51285454f + 5117 // (4.07009056f + 5118 // (-2.12067489f + 5119 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5120 // 5121 // error 0.0000876136000, which is better than 13 bits 5122 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5123 getF32Constant(DAG, 0xbda7262e, dl)); 5124 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5125 getF32Constant(DAG, 0x3f25280b, dl)); 5126 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5127 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5128 getF32Constant(DAG, 0x4007b923, dl)); 5129 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5130 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5131 getF32Constant(DAG, 0x40823e2f, dl)); 5132 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5133 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5134 getF32Constant(DAG, 0x4020d29c, dl)); 5135 } else { // LimitFloatPrecision <= 18 5136 // For floating-point precision of 18: 5137 // 5138 // Log2ofMantissa = 5139 // -3.0400495f + 5140 // (6.1129976f + 5141 // (-5.3420409f + 5142 // (3.2865683f + 5143 // (-1.2669343f + 5144 // (0.27515199f - 5145 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5146 // 5147 // error 0.0000018516, which is better than 18 bits 5148 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5149 getF32Constant(DAG, 0xbcd2769e, dl)); 5150 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5151 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5152 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5153 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5154 getF32Constant(DAG, 0x3fa22ae7, dl)); 5155 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5156 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5157 getF32Constant(DAG, 0x40525723, dl)); 5158 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5159 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5160 getF32Constant(DAG, 0x40aaf200, dl)); 5161 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5162 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5163 getF32Constant(DAG, 0x40c39dad, dl)); 5164 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5165 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5166 getF32Constant(DAG, 0x4042902c, dl)); 5167 } 5168 5169 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5170 } 5171 5172 // No special expansion. 5173 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5174 } 5175 5176 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5177 /// limited-precision mode. 5178 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5179 const TargetLowering &TLI, SDNodeFlags Flags) { 5180 // TODO: What fast-math-flags should be set on the floating-point nodes? 5181 5182 if (Op.getValueType() == MVT::f32 && 5183 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5184 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5185 5186 // Scale the exponent by log10(2) [0.30102999f]. 5187 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5188 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5189 getF32Constant(DAG, 0x3e9a209a, dl)); 5190 5191 // Get the significand and build it into a floating-point number with 5192 // exponent of 1. 5193 SDValue X = GetSignificand(DAG, Op1, dl); 5194 5195 SDValue Log10ofMantissa; 5196 if (LimitFloatPrecision <= 6) { 5197 // For floating-point precision of 6: 5198 // 5199 // Log10ofMantissa = 5200 // -0.50419619f + 5201 // (0.60948995f - 0.10380950f * x) * x; 5202 // 5203 // error 0.0014886165, which is 6 bits 5204 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5205 getF32Constant(DAG, 0xbdd49a13, dl)); 5206 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5207 getF32Constant(DAG, 0x3f1c0789, dl)); 5208 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5209 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5210 getF32Constant(DAG, 0x3f011300, dl)); 5211 } else if (LimitFloatPrecision <= 12) { 5212 // For floating-point precision of 12: 5213 // 5214 // Log10ofMantissa = 5215 // -0.64831180f + 5216 // (0.91751397f + 5217 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5218 // 5219 // error 0.00019228036, which is better than 12 bits 5220 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5221 getF32Constant(DAG, 0x3d431f31, dl)); 5222 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5223 getF32Constant(DAG, 0x3ea21fb2, dl)); 5224 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5225 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5226 getF32Constant(DAG, 0x3f6ae232, dl)); 5227 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5228 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5229 getF32Constant(DAG, 0x3f25f7c3, dl)); 5230 } else { // LimitFloatPrecision <= 18 5231 // For floating-point precision of 18: 5232 // 5233 // Log10ofMantissa = 5234 // -0.84299375f + 5235 // (1.5327582f + 5236 // (-1.0688956f + 5237 // (0.49102474f + 5238 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5239 // 5240 // error 0.0000037995730, which is better than 18 bits 5241 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5242 getF32Constant(DAG, 0x3c5d51ce, dl)); 5243 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5244 getF32Constant(DAG, 0x3e00685a, dl)); 5245 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5246 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5247 getF32Constant(DAG, 0x3efb6798, dl)); 5248 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5249 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5250 getF32Constant(DAG, 0x3f88d192, dl)); 5251 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5252 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5253 getF32Constant(DAG, 0x3fc4316c, dl)); 5254 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5255 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5256 getF32Constant(DAG, 0x3f57ce70, dl)); 5257 } 5258 5259 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5260 } 5261 5262 // No special expansion. 5263 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5264 } 5265 5266 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5267 /// limited-precision mode. 5268 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5269 const TargetLowering &TLI, SDNodeFlags Flags) { 5270 if (Op.getValueType() == MVT::f32 && 5271 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5272 return getLimitedPrecisionExp2(Op, dl, DAG); 5273 5274 // No special expansion. 5275 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5276 } 5277 5278 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5279 /// limited-precision mode with x == 10.0f. 5280 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5281 SelectionDAG &DAG, const TargetLowering &TLI, 5282 SDNodeFlags Flags) { 5283 bool IsExp10 = false; 5284 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5285 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5286 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5287 APFloat Ten(10.0f); 5288 IsExp10 = LHSC->isExactlyValue(Ten); 5289 } 5290 } 5291 5292 // TODO: What fast-math-flags should be set on the FMUL node? 5293 if (IsExp10) { 5294 // Put the exponent in the right bit position for later addition to the 5295 // final result: 5296 // 5297 // #define LOG2OF10 3.3219281f 5298 // t0 = Op * LOG2OF10; 5299 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5300 getF32Constant(DAG, 0x40549a78, dl)); 5301 return getLimitedPrecisionExp2(t0, dl, DAG); 5302 } 5303 5304 // No special expansion. 5305 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5306 } 5307 5308 /// ExpandPowI - Expand a llvm.powi intrinsic. 5309 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5310 SelectionDAG &DAG) { 5311 // If RHS is a constant, we can expand this out to a multiplication tree, 5312 // otherwise we end up lowering to a call to __powidf2 (for example). When 5313 // optimizing for size, we only want to do this if the expansion would produce 5314 // a small number of multiplies, otherwise we do the full expansion. 5315 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5316 // Get the exponent as a positive value. 5317 unsigned Val = RHSC->getSExtValue(); 5318 if ((int)Val < 0) Val = -Val; 5319 5320 // powi(x, 0) -> 1.0 5321 if (Val == 0) 5322 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5323 5324 bool OptForSize = DAG.shouldOptForSize(); 5325 if (!OptForSize || 5326 // If optimizing for size, don't insert too many multiplies. 5327 // This inserts up to 5 multiplies. 5328 countPopulation(Val) + Log2_32(Val) < 7) { 5329 // We use the simple binary decomposition method to generate the multiply 5330 // sequence. There are more optimal ways to do this (for example, 5331 // powi(x,15) generates one more multiply than it should), but this has 5332 // the benefit of being both really simple and much better than a libcall. 5333 SDValue Res; // Logically starts equal to 1.0 5334 SDValue CurSquare = LHS; 5335 // TODO: Intrinsics should have fast-math-flags that propagate to these 5336 // nodes. 5337 while (Val) { 5338 if (Val & 1) { 5339 if (Res.getNode()) 5340 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5341 else 5342 Res = CurSquare; // 1.0*CurSquare. 5343 } 5344 5345 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5346 CurSquare, CurSquare); 5347 Val >>= 1; 5348 } 5349 5350 // If the original was negative, invert the result, producing 1/(x*x*x). 5351 if (RHSC->getSExtValue() < 0) 5352 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5353 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5354 return Res; 5355 } 5356 } 5357 5358 // Otherwise, expand to a libcall. 5359 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5360 } 5361 5362 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5363 SDValue LHS, SDValue RHS, SDValue Scale, 5364 SelectionDAG &DAG, const TargetLowering &TLI) { 5365 EVT VT = LHS.getValueType(); 5366 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5367 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5368 LLVMContext &Ctx = *DAG.getContext(); 5369 5370 // If the type is legal but the operation isn't, this node might survive all 5371 // the way to operation legalization. If we end up there and we do not have 5372 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5373 // node. 5374 5375 // Coax the legalizer into expanding the node during type legalization instead 5376 // by bumping the size by one bit. This will force it to Promote, enabling the 5377 // early expansion and avoiding the need to expand later. 5378 5379 // We don't have to do this if Scale is 0; that can always be expanded, unless 5380 // it's a saturating signed operation. Those can experience true integer 5381 // division overflow, a case which we must avoid. 5382 5383 // FIXME: We wouldn't have to do this (or any of the early 5384 // expansion/promotion) if it was possible to expand a libcall of an 5385 // illegal type during operation legalization. But it's not, so things 5386 // get a bit hacky. 5387 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5388 if ((ScaleInt > 0 || (Saturating && Signed)) && 5389 (TLI.isTypeLegal(VT) || 5390 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5391 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5392 Opcode, VT, ScaleInt); 5393 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5394 EVT PromVT; 5395 if (VT.isScalarInteger()) 5396 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5397 else if (VT.isVector()) { 5398 PromVT = VT.getVectorElementType(); 5399 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5400 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5401 } else 5402 llvm_unreachable("Wrong VT for DIVFIX?"); 5403 if (Signed) { 5404 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5405 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5406 } else { 5407 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5408 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5409 } 5410 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5411 // For saturating operations, we need to shift up the LHS to get the 5412 // proper saturation width, and then shift down again afterwards. 5413 if (Saturating) 5414 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5415 DAG.getConstant(1, DL, ShiftTy)); 5416 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5417 if (Saturating) 5418 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5419 DAG.getConstant(1, DL, ShiftTy)); 5420 return DAG.getZExtOrTrunc(Res, DL, VT); 5421 } 5422 } 5423 5424 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5425 } 5426 5427 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5428 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5429 static void 5430 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5431 const SDValue &N) { 5432 switch (N.getOpcode()) { 5433 case ISD::CopyFromReg: { 5434 SDValue Op = N.getOperand(1); 5435 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5436 Op.getValueType().getSizeInBits()); 5437 return; 5438 } 5439 case ISD::BITCAST: 5440 case ISD::AssertZext: 5441 case ISD::AssertSext: 5442 case ISD::TRUNCATE: 5443 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5444 return; 5445 case ISD::BUILD_PAIR: 5446 case ISD::BUILD_VECTOR: 5447 case ISD::CONCAT_VECTORS: 5448 for (SDValue Op : N->op_values()) 5449 getUnderlyingArgRegs(Regs, Op); 5450 return; 5451 default: 5452 return; 5453 } 5454 } 5455 5456 /// If the DbgValueInst is a dbg_value of a function argument, create the 5457 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5458 /// instruction selection, they will be inserted to the entry BB. 5459 /// We don't currently support this for variadic dbg_values, as they shouldn't 5460 /// appear for function arguments or in the prologue. 5461 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5462 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5463 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5464 const Argument *Arg = dyn_cast<Argument>(V); 5465 if (!Arg) 5466 return false; 5467 5468 if (!IsDbgDeclare) { 5469 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5470 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5471 // the entry block. 5472 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5473 if (!IsInEntryBlock) 5474 return false; 5475 5476 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5477 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5478 // variable that also is a param. 5479 // 5480 // Although, if we are at the top of the entry block already, we can still 5481 // emit using ArgDbgValue. This might catch some situations when the 5482 // dbg.value refers to an argument that isn't used in the entry block, so 5483 // any CopyToReg node would be optimized out and the only way to express 5484 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5485 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5486 // we should only emit as ArgDbgValue if the Variable is an argument to the 5487 // current function, and the dbg.value intrinsic is found in the entry 5488 // block. 5489 bool VariableIsFunctionInputArg = Variable->isParameter() && 5490 !DL->getInlinedAt(); 5491 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5492 if (!IsInPrologue && !VariableIsFunctionInputArg) 5493 return false; 5494 5495 // Here we assume that a function argument on IR level only can be used to 5496 // describe one input parameter on source level. If we for example have 5497 // source code like this 5498 // 5499 // struct A { long x, y; }; 5500 // void foo(struct A a, long b) { 5501 // ... 5502 // b = a.x; 5503 // ... 5504 // } 5505 // 5506 // and IR like this 5507 // 5508 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5509 // entry: 5510 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5511 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5512 // call void @llvm.dbg.value(metadata i32 %b, "b", 5513 // ... 5514 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5515 // ... 5516 // 5517 // then the last dbg.value is describing a parameter "b" using a value that 5518 // is an argument. But since we already has used %a1 to describe a parameter 5519 // we should not handle that last dbg.value here (that would result in an 5520 // incorrect hoisting of the DBG_VALUE to the function entry). 5521 // Notice that we allow one dbg.value per IR level argument, to accommodate 5522 // for the situation with fragments above. 5523 if (VariableIsFunctionInputArg) { 5524 unsigned ArgNo = Arg->getArgNo(); 5525 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5526 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5527 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5528 return false; 5529 FuncInfo.DescribedArgs.set(ArgNo); 5530 } 5531 } 5532 5533 MachineFunction &MF = DAG.getMachineFunction(); 5534 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5535 5536 bool IsIndirect = false; 5537 Optional<MachineOperand> Op; 5538 // Some arguments' frame index is recorded during argument lowering. 5539 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5540 if (FI != std::numeric_limits<int>::max()) 5541 Op = MachineOperand::CreateFI(FI); 5542 5543 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5544 if (!Op && N.getNode()) { 5545 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5546 Register Reg; 5547 if (ArgRegsAndSizes.size() == 1) 5548 Reg = ArgRegsAndSizes.front().first; 5549 5550 if (Reg && Reg.isVirtual()) { 5551 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5552 Register PR = RegInfo.getLiveInPhysReg(Reg); 5553 if (PR) 5554 Reg = PR; 5555 } 5556 if (Reg) { 5557 Op = MachineOperand::CreateReg(Reg, false); 5558 IsIndirect = IsDbgDeclare; 5559 } 5560 } 5561 5562 if (!Op && N.getNode()) { 5563 // Check if frame index is available. 5564 SDValue LCandidate = peekThroughBitcasts(N); 5565 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5566 if (FrameIndexSDNode *FINode = 5567 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5568 Op = MachineOperand::CreateFI(FINode->getIndex()); 5569 } 5570 5571 if (!Op) { 5572 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5573 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5574 SplitRegs) { 5575 unsigned Offset = 0; 5576 for (auto RegAndSize : SplitRegs) { 5577 // If the expression is already a fragment, the current register 5578 // offset+size might extend beyond the fragment. In this case, only 5579 // the register bits that are inside the fragment are relevant. 5580 int RegFragmentSizeInBits = RegAndSize.second; 5581 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5582 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5583 // The register is entirely outside the expression fragment, 5584 // so is irrelevant for debug info. 5585 if (Offset >= ExprFragmentSizeInBits) 5586 break; 5587 // The register is partially outside the expression fragment, only 5588 // the low bits within the fragment are relevant for debug info. 5589 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5590 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5591 } 5592 } 5593 5594 auto FragmentExpr = DIExpression::createFragmentExpression( 5595 Expr, Offset, RegFragmentSizeInBits); 5596 Offset += RegAndSize.second; 5597 // If a valid fragment expression cannot be created, the variable's 5598 // correct value cannot be determined and so it is set as Undef. 5599 if (!FragmentExpr) { 5600 SDDbgValue *SDV = DAG.getConstantDbgValue( 5601 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5602 DAG.AddDbgValue(SDV, false); 5603 continue; 5604 } 5605 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5606 FuncInfo.ArgDbgValues.push_back( 5607 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5608 RegAndSize.first, Variable, *FragmentExpr)); 5609 } 5610 }; 5611 5612 // Check if ValueMap has reg number. 5613 DenseMap<const Value *, Register>::const_iterator 5614 VMI = FuncInfo.ValueMap.find(V); 5615 if (VMI != FuncInfo.ValueMap.end()) { 5616 const auto &TLI = DAG.getTargetLoweringInfo(); 5617 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5618 V->getType(), None); 5619 if (RFV.occupiesMultipleRegs()) { 5620 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5621 return true; 5622 } 5623 5624 Op = MachineOperand::CreateReg(VMI->second, false); 5625 IsIndirect = IsDbgDeclare; 5626 } else if (ArgRegsAndSizes.size() > 1) { 5627 // This was split due to the calling convention, and no virtual register 5628 // mapping exists for the value. 5629 splitMultiRegDbgValue(ArgRegsAndSizes); 5630 return true; 5631 } 5632 } 5633 5634 if (!Op) 5635 return false; 5636 5637 assert(Variable->isValidLocationForIntrinsic(DL) && 5638 "Expected inlined-at fields to agree"); 5639 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5640 FuncInfo.ArgDbgValues.push_back( 5641 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5642 *Op, Variable, Expr)); 5643 5644 return true; 5645 } 5646 5647 /// Return the appropriate SDDbgValue based on N. 5648 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5649 DILocalVariable *Variable, 5650 DIExpression *Expr, 5651 const DebugLoc &dl, 5652 unsigned DbgSDNodeOrder) { 5653 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5654 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5655 // stack slot locations. 5656 // 5657 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5658 // debug values here after optimization: 5659 // 5660 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5661 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5662 // 5663 // Both describe the direct values of their associated variables. 5664 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5665 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5666 } 5667 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5668 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5669 } 5670 5671 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5672 switch (Intrinsic) { 5673 case Intrinsic::smul_fix: 5674 return ISD::SMULFIX; 5675 case Intrinsic::umul_fix: 5676 return ISD::UMULFIX; 5677 case Intrinsic::smul_fix_sat: 5678 return ISD::SMULFIXSAT; 5679 case Intrinsic::umul_fix_sat: 5680 return ISD::UMULFIXSAT; 5681 case Intrinsic::sdiv_fix: 5682 return ISD::SDIVFIX; 5683 case Intrinsic::udiv_fix: 5684 return ISD::UDIVFIX; 5685 case Intrinsic::sdiv_fix_sat: 5686 return ISD::SDIVFIXSAT; 5687 case Intrinsic::udiv_fix_sat: 5688 return ISD::UDIVFIXSAT; 5689 default: 5690 llvm_unreachable("Unhandled fixed point intrinsic"); 5691 } 5692 } 5693 5694 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5695 const char *FunctionName) { 5696 assert(FunctionName && "FunctionName must not be nullptr"); 5697 SDValue Callee = DAG.getExternalSymbol( 5698 FunctionName, 5699 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5700 LowerCallTo(I, Callee, I.isTailCall()); 5701 } 5702 5703 /// Given a @llvm.call.preallocated.setup, return the corresponding 5704 /// preallocated call. 5705 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5706 assert(cast<CallBase>(PreallocatedSetup) 5707 ->getCalledFunction() 5708 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5709 "expected call_preallocated_setup Value"); 5710 for (auto *U : PreallocatedSetup->users()) { 5711 auto *UseCall = cast<CallBase>(U); 5712 const Function *Fn = UseCall->getCalledFunction(); 5713 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5714 return UseCall; 5715 } 5716 } 5717 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5718 } 5719 5720 /// Lower the call to the specified intrinsic function. 5721 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5722 unsigned Intrinsic) { 5723 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5724 SDLoc sdl = getCurSDLoc(); 5725 DebugLoc dl = getCurDebugLoc(); 5726 SDValue Res; 5727 5728 SDNodeFlags Flags; 5729 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5730 Flags.copyFMF(*FPOp); 5731 5732 switch (Intrinsic) { 5733 default: 5734 // By default, turn this into a target intrinsic node. 5735 visitTargetIntrinsic(I, Intrinsic); 5736 return; 5737 case Intrinsic::vscale: { 5738 match(&I, m_VScale(DAG.getDataLayout())); 5739 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5740 setValue(&I, 5741 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5742 return; 5743 } 5744 case Intrinsic::vastart: visitVAStart(I); return; 5745 case Intrinsic::vaend: visitVAEnd(I); return; 5746 case Intrinsic::vacopy: visitVACopy(I); return; 5747 case Intrinsic::returnaddress: 5748 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5749 TLI.getPointerTy(DAG.getDataLayout()), 5750 getValue(I.getArgOperand(0)))); 5751 return; 5752 case Intrinsic::addressofreturnaddress: 5753 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5754 TLI.getPointerTy(DAG.getDataLayout()))); 5755 return; 5756 case Intrinsic::sponentry: 5757 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5758 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5759 return; 5760 case Intrinsic::frameaddress: 5761 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5762 TLI.getFrameIndexTy(DAG.getDataLayout()), 5763 getValue(I.getArgOperand(0)))); 5764 return; 5765 case Intrinsic::read_volatile_register: 5766 case Intrinsic::read_register: { 5767 Value *Reg = I.getArgOperand(0); 5768 SDValue Chain = getRoot(); 5769 SDValue RegName = 5770 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5771 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5772 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5773 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5774 setValue(&I, Res); 5775 DAG.setRoot(Res.getValue(1)); 5776 return; 5777 } 5778 case Intrinsic::write_register: { 5779 Value *Reg = I.getArgOperand(0); 5780 Value *RegValue = I.getArgOperand(1); 5781 SDValue Chain = getRoot(); 5782 SDValue RegName = 5783 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5784 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5785 RegName, getValue(RegValue))); 5786 return; 5787 } 5788 case Intrinsic::memcpy: { 5789 const auto &MCI = cast<MemCpyInst>(I); 5790 SDValue Op1 = getValue(I.getArgOperand(0)); 5791 SDValue Op2 = getValue(I.getArgOperand(1)); 5792 SDValue Op3 = getValue(I.getArgOperand(2)); 5793 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5794 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5795 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5796 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5797 bool isVol = MCI.isVolatile(); 5798 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5799 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5800 // node. 5801 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5802 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5803 /* AlwaysInline */ false, isTC, 5804 MachinePointerInfo(I.getArgOperand(0)), 5805 MachinePointerInfo(I.getArgOperand(1))); 5806 updateDAGForMaybeTailCall(MC); 5807 return; 5808 } 5809 case Intrinsic::memcpy_inline: { 5810 const auto &MCI = cast<MemCpyInlineInst>(I); 5811 SDValue Dst = getValue(I.getArgOperand(0)); 5812 SDValue Src = getValue(I.getArgOperand(1)); 5813 SDValue Size = getValue(I.getArgOperand(2)); 5814 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5815 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5816 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5817 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5818 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5819 bool isVol = MCI.isVolatile(); 5820 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5821 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5822 // node. 5823 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5824 /* AlwaysInline */ true, isTC, 5825 MachinePointerInfo(I.getArgOperand(0)), 5826 MachinePointerInfo(I.getArgOperand(1))); 5827 updateDAGForMaybeTailCall(MC); 5828 return; 5829 } 5830 case Intrinsic::memset: { 5831 const auto &MSI = cast<MemSetInst>(I); 5832 SDValue Op1 = getValue(I.getArgOperand(0)); 5833 SDValue Op2 = getValue(I.getArgOperand(1)); 5834 SDValue Op3 = getValue(I.getArgOperand(2)); 5835 // @llvm.memset defines 0 and 1 to both mean no alignment. 5836 Align Alignment = MSI.getDestAlign().valueOrOne(); 5837 bool isVol = MSI.isVolatile(); 5838 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5839 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5840 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5841 MachinePointerInfo(I.getArgOperand(0))); 5842 updateDAGForMaybeTailCall(MS); 5843 return; 5844 } 5845 case Intrinsic::memmove: { 5846 const auto &MMI = cast<MemMoveInst>(I); 5847 SDValue Op1 = getValue(I.getArgOperand(0)); 5848 SDValue Op2 = getValue(I.getArgOperand(1)); 5849 SDValue Op3 = getValue(I.getArgOperand(2)); 5850 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5851 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5852 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5853 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5854 bool isVol = MMI.isVolatile(); 5855 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5856 // FIXME: Support passing different dest/src alignments to the memmove DAG 5857 // node. 5858 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5859 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5860 isTC, MachinePointerInfo(I.getArgOperand(0)), 5861 MachinePointerInfo(I.getArgOperand(1))); 5862 updateDAGForMaybeTailCall(MM); 5863 return; 5864 } 5865 case Intrinsic::memcpy_element_unordered_atomic: { 5866 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5867 SDValue Dst = getValue(MI.getRawDest()); 5868 SDValue Src = getValue(MI.getRawSource()); 5869 SDValue Length = getValue(MI.getLength()); 5870 5871 unsigned DstAlign = MI.getDestAlignment(); 5872 unsigned SrcAlign = MI.getSourceAlignment(); 5873 Type *LengthTy = MI.getLength()->getType(); 5874 unsigned ElemSz = MI.getElementSizeInBytes(); 5875 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5876 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5877 SrcAlign, Length, LengthTy, ElemSz, isTC, 5878 MachinePointerInfo(MI.getRawDest()), 5879 MachinePointerInfo(MI.getRawSource())); 5880 updateDAGForMaybeTailCall(MC); 5881 return; 5882 } 5883 case Intrinsic::memmove_element_unordered_atomic: { 5884 auto &MI = cast<AtomicMemMoveInst>(I); 5885 SDValue Dst = getValue(MI.getRawDest()); 5886 SDValue Src = getValue(MI.getRawSource()); 5887 SDValue Length = getValue(MI.getLength()); 5888 5889 unsigned DstAlign = MI.getDestAlignment(); 5890 unsigned SrcAlign = MI.getSourceAlignment(); 5891 Type *LengthTy = MI.getLength()->getType(); 5892 unsigned ElemSz = MI.getElementSizeInBytes(); 5893 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5894 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5895 SrcAlign, Length, LengthTy, ElemSz, isTC, 5896 MachinePointerInfo(MI.getRawDest()), 5897 MachinePointerInfo(MI.getRawSource())); 5898 updateDAGForMaybeTailCall(MC); 5899 return; 5900 } 5901 case Intrinsic::memset_element_unordered_atomic: { 5902 auto &MI = cast<AtomicMemSetInst>(I); 5903 SDValue Dst = getValue(MI.getRawDest()); 5904 SDValue Val = getValue(MI.getValue()); 5905 SDValue Length = getValue(MI.getLength()); 5906 5907 unsigned DstAlign = MI.getDestAlignment(); 5908 Type *LengthTy = MI.getLength()->getType(); 5909 unsigned ElemSz = MI.getElementSizeInBytes(); 5910 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5911 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5912 LengthTy, ElemSz, isTC, 5913 MachinePointerInfo(MI.getRawDest())); 5914 updateDAGForMaybeTailCall(MC); 5915 return; 5916 } 5917 case Intrinsic::call_preallocated_setup: { 5918 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5919 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5920 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5921 getRoot(), SrcValue); 5922 setValue(&I, Res); 5923 DAG.setRoot(Res); 5924 return; 5925 } 5926 case Intrinsic::call_preallocated_arg: { 5927 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5928 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5929 SDValue Ops[3]; 5930 Ops[0] = getRoot(); 5931 Ops[1] = SrcValue; 5932 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5933 MVT::i32); // arg index 5934 SDValue Res = DAG.getNode( 5935 ISD::PREALLOCATED_ARG, sdl, 5936 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5937 setValue(&I, Res); 5938 DAG.setRoot(Res.getValue(1)); 5939 return; 5940 } 5941 case Intrinsic::dbg_addr: 5942 case Intrinsic::dbg_declare: { 5943 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 5944 // they are non-variadic. 5945 const auto &DI = cast<DbgVariableIntrinsic>(I); 5946 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 5947 DILocalVariable *Variable = DI.getVariable(); 5948 DIExpression *Expression = DI.getExpression(); 5949 dropDanglingDebugInfo(Variable, Expression); 5950 assert(Variable && "Missing variable"); 5951 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5952 << "\n"); 5953 // Check if address has undef value. 5954 const Value *Address = DI.getVariableLocationOp(0); 5955 if (!Address || isa<UndefValue>(Address) || 5956 (Address->use_empty() && !isa<Argument>(Address))) { 5957 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5958 << " (bad/undef/unused-arg address)\n"); 5959 return; 5960 } 5961 5962 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5963 5964 // Check if this variable can be described by a frame index, typically 5965 // either as a static alloca or a byval parameter. 5966 int FI = std::numeric_limits<int>::max(); 5967 if (const auto *AI = 5968 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5969 if (AI->isStaticAlloca()) { 5970 auto I = FuncInfo.StaticAllocaMap.find(AI); 5971 if (I != FuncInfo.StaticAllocaMap.end()) 5972 FI = I->second; 5973 } 5974 } else if (const auto *Arg = dyn_cast<Argument>( 5975 Address->stripInBoundsConstantOffsets())) { 5976 FI = FuncInfo.getArgumentFrameIndex(Arg); 5977 } 5978 5979 // llvm.dbg.addr is control dependent and always generates indirect 5980 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5981 // the MachineFunction variable table. 5982 if (FI != std::numeric_limits<int>::max()) { 5983 if (Intrinsic == Intrinsic::dbg_addr) { 5984 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5985 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 5986 dl, SDNodeOrder); 5987 DAG.AddDbgValue(SDV, isParameter); 5988 } else { 5989 LLVM_DEBUG(dbgs() << "Skipping " << DI 5990 << " (variable info stashed in MF side table)\n"); 5991 } 5992 return; 5993 } 5994 5995 SDValue &N = NodeMap[Address]; 5996 if (!N.getNode() && isa<Argument>(Address)) 5997 // Check unused arguments map. 5998 N = UnusedArgNodeMap[Address]; 5999 SDDbgValue *SDV; 6000 if (N.getNode()) { 6001 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6002 Address = BCI->getOperand(0); 6003 // Parameters are handled specially. 6004 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6005 if (isParameter && FINode) { 6006 // Byval parameter. We have a frame index at this point. 6007 SDV = 6008 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6009 /*IsIndirect*/ true, dl, SDNodeOrder); 6010 } else if (isa<Argument>(Address)) { 6011 // Address is an argument, so try to emit its dbg value using 6012 // virtual register info from the FuncInfo.ValueMap. 6013 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6014 return; 6015 } else { 6016 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6017 true, dl, SDNodeOrder); 6018 } 6019 DAG.AddDbgValue(SDV, isParameter); 6020 } else { 6021 // If Address is an argument then try to emit its dbg value using 6022 // virtual register info from the FuncInfo.ValueMap. 6023 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6024 N)) { 6025 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6026 << " (could not emit func-arg dbg_value)\n"); 6027 } 6028 } 6029 return; 6030 } 6031 case Intrinsic::dbg_label: { 6032 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6033 DILabel *Label = DI.getLabel(); 6034 assert(Label && "Missing label"); 6035 6036 SDDbgLabel *SDV; 6037 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6038 DAG.AddDbgLabel(SDV); 6039 return; 6040 } 6041 case Intrinsic::dbg_value: { 6042 const DbgValueInst &DI = cast<DbgValueInst>(I); 6043 assert(DI.getVariable() && "Missing variable"); 6044 6045 DILocalVariable *Variable = DI.getVariable(); 6046 DIExpression *Expression = DI.getExpression(); 6047 dropDanglingDebugInfo(Variable, Expression); 6048 SmallVector<Value *, 4> Values(DI.getValues()); 6049 if (Values.empty()) 6050 return; 6051 6052 if (std::count(Values.begin(), Values.end(), nullptr)) 6053 return; 6054 6055 bool IsVariadic = DI.hasArgList(); 6056 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6057 SDNodeOrder, IsVariadic)) 6058 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6059 return; 6060 } 6061 6062 case Intrinsic::eh_typeid_for: { 6063 // Find the type id for the given typeinfo. 6064 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6065 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6066 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6067 setValue(&I, Res); 6068 return; 6069 } 6070 6071 case Intrinsic::eh_return_i32: 6072 case Intrinsic::eh_return_i64: 6073 DAG.getMachineFunction().setCallsEHReturn(true); 6074 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6075 MVT::Other, 6076 getControlRoot(), 6077 getValue(I.getArgOperand(0)), 6078 getValue(I.getArgOperand(1)))); 6079 return; 6080 case Intrinsic::eh_unwind_init: 6081 DAG.getMachineFunction().setCallsUnwindInit(true); 6082 return; 6083 case Intrinsic::eh_dwarf_cfa: 6084 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6085 TLI.getPointerTy(DAG.getDataLayout()), 6086 getValue(I.getArgOperand(0)))); 6087 return; 6088 case Intrinsic::eh_sjlj_callsite: { 6089 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6090 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6091 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6092 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6093 6094 MMI.setCurrentCallSite(CI->getZExtValue()); 6095 return; 6096 } 6097 case Intrinsic::eh_sjlj_functioncontext: { 6098 // Get and store the index of the function context. 6099 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6100 AllocaInst *FnCtx = 6101 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6102 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6103 MFI.setFunctionContextIndex(FI); 6104 return; 6105 } 6106 case Intrinsic::eh_sjlj_setjmp: { 6107 SDValue Ops[2]; 6108 Ops[0] = getRoot(); 6109 Ops[1] = getValue(I.getArgOperand(0)); 6110 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6111 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6112 setValue(&I, Op.getValue(0)); 6113 DAG.setRoot(Op.getValue(1)); 6114 return; 6115 } 6116 case Intrinsic::eh_sjlj_longjmp: 6117 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6118 getRoot(), getValue(I.getArgOperand(0)))); 6119 return; 6120 case Intrinsic::eh_sjlj_setup_dispatch: 6121 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6122 getRoot())); 6123 return; 6124 case Intrinsic::masked_gather: 6125 visitMaskedGather(I); 6126 return; 6127 case Intrinsic::masked_load: 6128 visitMaskedLoad(I); 6129 return; 6130 case Intrinsic::masked_scatter: 6131 visitMaskedScatter(I); 6132 return; 6133 case Intrinsic::masked_store: 6134 visitMaskedStore(I); 6135 return; 6136 case Intrinsic::masked_expandload: 6137 visitMaskedLoad(I, true /* IsExpanding */); 6138 return; 6139 case Intrinsic::masked_compressstore: 6140 visitMaskedStore(I, true /* IsCompressing */); 6141 return; 6142 case Intrinsic::powi: 6143 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6144 getValue(I.getArgOperand(1)), DAG)); 6145 return; 6146 case Intrinsic::log: 6147 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6148 return; 6149 case Intrinsic::log2: 6150 setValue(&I, 6151 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6152 return; 6153 case Intrinsic::log10: 6154 setValue(&I, 6155 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6156 return; 6157 case Intrinsic::exp: 6158 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6159 return; 6160 case Intrinsic::exp2: 6161 setValue(&I, 6162 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6163 return; 6164 case Intrinsic::pow: 6165 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6166 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6167 return; 6168 case Intrinsic::sqrt: 6169 case Intrinsic::fabs: 6170 case Intrinsic::sin: 6171 case Intrinsic::cos: 6172 case Intrinsic::floor: 6173 case Intrinsic::ceil: 6174 case Intrinsic::trunc: 6175 case Intrinsic::rint: 6176 case Intrinsic::nearbyint: 6177 case Intrinsic::round: 6178 case Intrinsic::roundeven: 6179 case Intrinsic::canonicalize: { 6180 unsigned Opcode; 6181 switch (Intrinsic) { 6182 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6183 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6184 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6185 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6186 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6187 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6188 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6189 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6190 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6191 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6192 case Intrinsic::round: Opcode = ISD::FROUND; break; 6193 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6194 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6195 } 6196 6197 setValue(&I, DAG.getNode(Opcode, sdl, 6198 getValue(I.getArgOperand(0)).getValueType(), 6199 getValue(I.getArgOperand(0)), Flags)); 6200 return; 6201 } 6202 case Intrinsic::lround: 6203 case Intrinsic::llround: 6204 case Intrinsic::lrint: 6205 case Intrinsic::llrint: { 6206 unsigned Opcode; 6207 switch (Intrinsic) { 6208 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6209 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6210 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6211 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6212 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6213 } 6214 6215 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6216 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6217 getValue(I.getArgOperand(0)))); 6218 return; 6219 } 6220 case Intrinsic::minnum: 6221 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6222 getValue(I.getArgOperand(0)).getValueType(), 6223 getValue(I.getArgOperand(0)), 6224 getValue(I.getArgOperand(1)), Flags)); 6225 return; 6226 case Intrinsic::maxnum: 6227 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6228 getValue(I.getArgOperand(0)).getValueType(), 6229 getValue(I.getArgOperand(0)), 6230 getValue(I.getArgOperand(1)), Flags)); 6231 return; 6232 case Intrinsic::minimum: 6233 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6234 getValue(I.getArgOperand(0)).getValueType(), 6235 getValue(I.getArgOperand(0)), 6236 getValue(I.getArgOperand(1)), Flags)); 6237 return; 6238 case Intrinsic::maximum: 6239 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6240 getValue(I.getArgOperand(0)).getValueType(), 6241 getValue(I.getArgOperand(0)), 6242 getValue(I.getArgOperand(1)), Flags)); 6243 return; 6244 case Intrinsic::copysign: 6245 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6246 getValue(I.getArgOperand(0)).getValueType(), 6247 getValue(I.getArgOperand(0)), 6248 getValue(I.getArgOperand(1)), Flags)); 6249 return; 6250 case Intrinsic::fma: 6251 setValue(&I, DAG.getNode( 6252 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6253 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6254 getValue(I.getArgOperand(2)), Flags)); 6255 return; 6256 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6257 case Intrinsic::INTRINSIC: 6258 #include "llvm/IR/ConstrainedOps.def" 6259 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6260 return; 6261 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6262 #include "llvm/IR/VPIntrinsics.def" 6263 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6264 return; 6265 case Intrinsic::fmuladd: { 6266 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6267 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6268 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6269 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6270 getValue(I.getArgOperand(0)).getValueType(), 6271 getValue(I.getArgOperand(0)), 6272 getValue(I.getArgOperand(1)), 6273 getValue(I.getArgOperand(2)), Flags)); 6274 } else { 6275 // TODO: Intrinsic calls should have fast-math-flags. 6276 SDValue Mul = DAG.getNode( 6277 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6278 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6279 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6280 getValue(I.getArgOperand(0)).getValueType(), 6281 Mul, getValue(I.getArgOperand(2)), Flags); 6282 setValue(&I, Add); 6283 } 6284 return; 6285 } 6286 case Intrinsic::convert_to_fp16: 6287 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6288 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6289 getValue(I.getArgOperand(0)), 6290 DAG.getTargetConstant(0, sdl, 6291 MVT::i32)))); 6292 return; 6293 case Intrinsic::convert_from_fp16: 6294 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6295 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6296 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6297 getValue(I.getArgOperand(0))))); 6298 return; 6299 case Intrinsic::fptosi_sat: { 6300 EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6301 SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32); 6302 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, Type, 6303 getValue(I.getArgOperand(0)), SatW)); 6304 return; 6305 } 6306 case Intrinsic::fptoui_sat: { 6307 EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6308 SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32); 6309 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, Type, 6310 getValue(I.getArgOperand(0)), SatW)); 6311 return; 6312 } 6313 case Intrinsic::set_rounding: 6314 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6315 {getRoot(), getValue(I.getArgOperand(0))}); 6316 setValue(&I, Res); 6317 DAG.setRoot(Res.getValue(0)); 6318 return; 6319 case Intrinsic::pcmarker: { 6320 SDValue Tmp = getValue(I.getArgOperand(0)); 6321 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6322 return; 6323 } 6324 case Intrinsic::readcyclecounter: { 6325 SDValue Op = getRoot(); 6326 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6327 DAG.getVTList(MVT::i64, MVT::Other), Op); 6328 setValue(&I, Res); 6329 DAG.setRoot(Res.getValue(1)); 6330 return; 6331 } 6332 case Intrinsic::bitreverse: 6333 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6334 getValue(I.getArgOperand(0)).getValueType(), 6335 getValue(I.getArgOperand(0)))); 6336 return; 6337 case Intrinsic::bswap: 6338 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6339 getValue(I.getArgOperand(0)).getValueType(), 6340 getValue(I.getArgOperand(0)))); 6341 return; 6342 case Intrinsic::cttz: { 6343 SDValue Arg = getValue(I.getArgOperand(0)); 6344 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6345 EVT Ty = Arg.getValueType(); 6346 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6347 sdl, Ty, Arg)); 6348 return; 6349 } 6350 case Intrinsic::ctlz: { 6351 SDValue Arg = getValue(I.getArgOperand(0)); 6352 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6353 EVT Ty = Arg.getValueType(); 6354 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6355 sdl, Ty, Arg)); 6356 return; 6357 } 6358 case Intrinsic::ctpop: { 6359 SDValue Arg = getValue(I.getArgOperand(0)); 6360 EVT Ty = Arg.getValueType(); 6361 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6362 return; 6363 } 6364 case Intrinsic::fshl: 6365 case Intrinsic::fshr: { 6366 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6367 SDValue X = getValue(I.getArgOperand(0)); 6368 SDValue Y = getValue(I.getArgOperand(1)); 6369 SDValue Z = getValue(I.getArgOperand(2)); 6370 EVT VT = X.getValueType(); 6371 6372 if (X == Y) { 6373 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6374 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6375 } else { 6376 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6377 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6378 } 6379 return; 6380 } 6381 case Intrinsic::sadd_sat: { 6382 SDValue Op1 = getValue(I.getArgOperand(0)); 6383 SDValue Op2 = getValue(I.getArgOperand(1)); 6384 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6385 return; 6386 } 6387 case Intrinsic::uadd_sat: { 6388 SDValue Op1 = getValue(I.getArgOperand(0)); 6389 SDValue Op2 = getValue(I.getArgOperand(1)); 6390 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6391 return; 6392 } 6393 case Intrinsic::ssub_sat: { 6394 SDValue Op1 = getValue(I.getArgOperand(0)); 6395 SDValue Op2 = getValue(I.getArgOperand(1)); 6396 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6397 return; 6398 } 6399 case Intrinsic::usub_sat: { 6400 SDValue Op1 = getValue(I.getArgOperand(0)); 6401 SDValue Op2 = getValue(I.getArgOperand(1)); 6402 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6403 return; 6404 } 6405 case Intrinsic::sshl_sat: { 6406 SDValue Op1 = getValue(I.getArgOperand(0)); 6407 SDValue Op2 = getValue(I.getArgOperand(1)); 6408 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6409 return; 6410 } 6411 case Intrinsic::ushl_sat: { 6412 SDValue Op1 = getValue(I.getArgOperand(0)); 6413 SDValue Op2 = getValue(I.getArgOperand(1)); 6414 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6415 return; 6416 } 6417 case Intrinsic::smul_fix: 6418 case Intrinsic::umul_fix: 6419 case Intrinsic::smul_fix_sat: 6420 case Intrinsic::umul_fix_sat: { 6421 SDValue Op1 = getValue(I.getArgOperand(0)); 6422 SDValue Op2 = getValue(I.getArgOperand(1)); 6423 SDValue Op3 = getValue(I.getArgOperand(2)); 6424 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6425 Op1.getValueType(), Op1, Op2, Op3)); 6426 return; 6427 } 6428 case Intrinsic::sdiv_fix: 6429 case Intrinsic::udiv_fix: 6430 case Intrinsic::sdiv_fix_sat: 6431 case Intrinsic::udiv_fix_sat: { 6432 SDValue Op1 = getValue(I.getArgOperand(0)); 6433 SDValue Op2 = getValue(I.getArgOperand(1)); 6434 SDValue Op3 = getValue(I.getArgOperand(2)); 6435 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6436 Op1, Op2, Op3, DAG, TLI)); 6437 return; 6438 } 6439 case Intrinsic::smax: { 6440 SDValue Op1 = getValue(I.getArgOperand(0)); 6441 SDValue Op2 = getValue(I.getArgOperand(1)); 6442 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6443 return; 6444 } 6445 case Intrinsic::smin: { 6446 SDValue Op1 = getValue(I.getArgOperand(0)); 6447 SDValue Op2 = getValue(I.getArgOperand(1)); 6448 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6449 return; 6450 } 6451 case Intrinsic::umax: { 6452 SDValue Op1 = getValue(I.getArgOperand(0)); 6453 SDValue Op2 = getValue(I.getArgOperand(1)); 6454 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6455 return; 6456 } 6457 case Intrinsic::umin: { 6458 SDValue Op1 = getValue(I.getArgOperand(0)); 6459 SDValue Op2 = getValue(I.getArgOperand(1)); 6460 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6461 return; 6462 } 6463 case Intrinsic::abs: { 6464 // TODO: Preserve "int min is poison" arg in SDAG? 6465 SDValue Op1 = getValue(I.getArgOperand(0)); 6466 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6467 return; 6468 } 6469 case Intrinsic::stacksave: { 6470 SDValue Op = getRoot(); 6471 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6472 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6473 setValue(&I, Res); 6474 DAG.setRoot(Res.getValue(1)); 6475 return; 6476 } 6477 case Intrinsic::stackrestore: 6478 Res = getValue(I.getArgOperand(0)); 6479 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6480 return; 6481 case Intrinsic::get_dynamic_area_offset: { 6482 SDValue Op = getRoot(); 6483 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6484 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6485 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6486 // target. 6487 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6488 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6489 " intrinsic!"); 6490 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6491 Op); 6492 DAG.setRoot(Op); 6493 setValue(&I, Res); 6494 return; 6495 } 6496 case Intrinsic::stackguard: { 6497 MachineFunction &MF = DAG.getMachineFunction(); 6498 const Module &M = *MF.getFunction().getParent(); 6499 SDValue Chain = getRoot(); 6500 if (TLI.useLoadStackGuardNode()) { 6501 Res = getLoadStackGuard(DAG, sdl, Chain); 6502 } else { 6503 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6504 const Value *Global = TLI.getSDagStackGuard(M); 6505 Align Align = DL->getPrefTypeAlign(Global->getType()); 6506 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6507 MachinePointerInfo(Global, 0), Align, 6508 MachineMemOperand::MOVolatile); 6509 } 6510 if (TLI.useStackGuardXorFP()) 6511 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6512 DAG.setRoot(Chain); 6513 setValue(&I, Res); 6514 return; 6515 } 6516 case Intrinsic::stackprotector: { 6517 // Emit code into the DAG to store the stack guard onto the stack. 6518 MachineFunction &MF = DAG.getMachineFunction(); 6519 MachineFrameInfo &MFI = MF.getFrameInfo(); 6520 SDValue Src, Chain = getRoot(); 6521 6522 if (TLI.useLoadStackGuardNode()) 6523 Src = getLoadStackGuard(DAG, sdl, Chain); 6524 else 6525 Src = getValue(I.getArgOperand(0)); // The guard's value. 6526 6527 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6528 6529 int FI = FuncInfo.StaticAllocaMap[Slot]; 6530 MFI.setStackProtectorIndex(FI); 6531 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6532 6533 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6534 6535 // Store the stack protector onto the stack. 6536 Res = DAG.getStore( 6537 Chain, sdl, Src, FIN, 6538 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6539 MaybeAlign(), MachineMemOperand::MOVolatile); 6540 setValue(&I, Res); 6541 DAG.setRoot(Res); 6542 return; 6543 } 6544 case Intrinsic::objectsize: 6545 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6546 6547 case Intrinsic::is_constant: 6548 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6549 6550 case Intrinsic::annotation: 6551 case Intrinsic::ptr_annotation: 6552 case Intrinsic::launder_invariant_group: 6553 case Intrinsic::strip_invariant_group: 6554 // Drop the intrinsic, but forward the value 6555 setValue(&I, getValue(I.getOperand(0))); 6556 return; 6557 6558 case Intrinsic::assume: 6559 case Intrinsic::experimental_noalias_scope_decl: 6560 case Intrinsic::var_annotation: 6561 case Intrinsic::sideeffect: 6562 // Discard annotate attributes, noalias scope declarations, assumptions, and 6563 // artificial side-effects. 6564 return; 6565 6566 case Intrinsic::codeview_annotation: { 6567 // Emit a label associated with this metadata. 6568 MachineFunction &MF = DAG.getMachineFunction(); 6569 MCSymbol *Label = 6570 MF.getMMI().getContext().createTempSymbol("annotation", true); 6571 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6572 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6573 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6574 DAG.setRoot(Res); 6575 return; 6576 } 6577 6578 case Intrinsic::init_trampoline: { 6579 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6580 6581 SDValue Ops[6]; 6582 Ops[0] = getRoot(); 6583 Ops[1] = getValue(I.getArgOperand(0)); 6584 Ops[2] = getValue(I.getArgOperand(1)); 6585 Ops[3] = getValue(I.getArgOperand(2)); 6586 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6587 Ops[5] = DAG.getSrcValue(F); 6588 6589 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6590 6591 DAG.setRoot(Res); 6592 return; 6593 } 6594 case Intrinsic::adjust_trampoline: 6595 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6596 TLI.getPointerTy(DAG.getDataLayout()), 6597 getValue(I.getArgOperand(0)))); 6598 return; 6599 case Intrinsic::gcroot: { 6600 assert(DAG.getMachineFunction().getFunction().hasGC() && 6601 "only valid in functions with gc specified, enforced by Verifier"); 6602 assert(GFI && "implied by previous"); 6603 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6604 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6605 6606 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6607 GFI->addStackRoot(FI->getIndex(), TypeMap); 6608 return; 6609 } 6610 case Intrinsic::gcread: 6611 case Intrinsic::gcwrite: 6612 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6613 case Intrinsic::flt_rounds: 6614 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6615 setValue(&I, Res); 6616 DAG.setRoot(Res.getValue(1)); 6617 return; 6618 6619 case Intrinsic::expect: 6620 // Just replace __builtin_expect(exp, c) with EXP. 6621 setValue(&I, getValue(I.getArgOperand(0))); 6622 return; 6623 6624 case Intrinsic::ubsantrap: 6625 case Intrinsic::debugtrap: 6626 case Intrinsic::trap: { 6627 StringRef TrapFuncName = 6628 I.getAttributes() 6629 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6630 .getValueAsString(); 6631 if (TrapFuncName.empty()) { 6632 switch (Intrinsic) { 6633 case Intrinsic::trap: 6634 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6635 break; 6636 case Intrinsic::debugtrap: 6637 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6638 break; 6639 case Intrinsic::ubsantrap: 6640 DAG.setRoot(DAG.getNode( 6641 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6642 DAG.getTargetConstant( 6643 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6644 MVT::i32))); 6645 break; 6646 default: llvm_unreachable("unknown trap intrinsic"); 6647 } 6648 return; 6649 } 6650 TargetLowering::ArgListTy Args; 6651 if (Intrinsic == Intrinsic::ubsantrap) { 6652 Args.push_back(TargetLoweringBase::ArgListEntry()); 6653 Args[0].Val = I.getArgOperand(0); 6654 Args[0].Node = getValue(Args[0].Val); 6655 Args[0].Ty = Args[0].Val->getType(); 6656 } 6657 6658 TargetLowering::CallLoweringInfo CLI(DAG); 6659 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6660 CallingConv::C, I.getType(), 6661 DAG.getExternalSymbol(TrapFuncName.data(), 6662 TLI.getPointerTy(DAG.getDataLayout())), 6663 std::move(Args)); 6664 6665 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6666 DAG.setRoot(Result.second); 6667 return; 6668 } 6669 6670 case Intrinsic::uadd_with_overflow: 6671 case Intrinsic::sadd_with_overflow: 6672 case Intrinsic::usub_with_overflow: 6673 case Intrinsic::ssub_with_overflow: 6674 case Intrinsic::umul_with_overflow: 6675 case Intrinsic::smul_with_overflow: { 6676 ISD::NodeType Op; 6677 switch (Intrinsic) { 6678 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6679 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6680 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6681 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6682 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6683 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6684 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6685 } 6686 SDValue Op1 = getValue(I.getArgOperand(0)); 6687 SDValue Op2 = getValue(I.getArgOperand(1)); 6688 6689 EVT ResultVT = Op1.getValueType(); 6690 EVT OverflowVT = MVT::i1; 6691 if (ResultVT.isVector()) 6692 OverflowVT = EVT::getVectorVT( 6693 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6694 6695 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6696 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6697 return; 6698 } 6699 case Intrinsic::prefetch: { 6700 SDValue Ops[5]; 6701 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6702 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6703 Ops[0] = DAG.getRoot(); 6704 Ops[1] = getValue(I.getArgOperand(0)); 6705 Ops[2] = getValue(I.getArgOperand(1)); 6706 Ops[3] = getValue(I.getArgOperand(2)); 6707 Ops[4] = getValue(I.getArgOperand(3)); 6708 SDValue Result = DAG.getMemIntrinsicNode( 6709 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6710 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6711 /* align */ None, Flags); 6712 6713 // Chain the prefetch in parallell with any pending loads, to stay out of 6714 // the way of later optimizations. 6715 PendingLoads.push_back(Result); 6716 Result = getRoot(); 6717 DAG.setRoot(Result); 6718 return; 6719 } 6720 case Intrinsic::lifetime_start: 6721 case Intrinsic::lifetime_end: { 6722 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6723 // Stack coloring is not enabled in O0, discard region information. 6724 if (TM.getOptLevel() == CodeGenOpt::None) 6725 return; 6726 6727 const int64_t ObjectSize = 6728 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6729 Value *const ObjectPtr = I.getArgOperand(1); 6730 SmallVector<const Value *, 4> Allocas; 6731 getUnderlyingObjects(ObjectPtr, Allocas); 6732 6733 for (const Value *Alloca : Allocas) { 6734 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6735 6736 // Could not find an Alloca. 6737 if (!LifetimeObject) 6738 continue; 6739 6740 // First check that the Alloca is static, otherwise it won't have a 6741 // valid frame index. 6742 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6743 if (SI == FuncInfo.StaticAllocaMap.end()) 6744 return; 6745 6746 const int FrameIndex = SI->second; 6747 int64_t Offset; 6748 if (GetPointerBaseWithConstantOffset( 6749 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6750 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6751 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6752 Offset); 6753 DAG.setRoot(Res); 6754 } 6755 return; 6756 } 6757 case Intrinsic::pseudoprobe: { 6758 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6759 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6760 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6761 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6762 DAG.setRoot(Res); 6763 return; 6764 } 6765 case Intrinsic::invariant_start: 6766 // Discard region information. 6767 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6768 return; 6769 case Intrinsic::invariant_end: 6770 // Discard region information. 6771 return; 6772 case Intrinsic::clear_cache: 6773 /// FunctionName may be null. 6774 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6775 lowerCallToExternalSymbol(I, FunctionName); 6776 return; 6777 case Intrinsic::donothing: 6778 // ignore 6779 return; 6780 case Intrinsic::experimental_stackmap: 6781 visitStackmap(I); 6782 return; 6783 case Intrinsic::experimental_patchpoint_void: 6784 case Intrinsic::experimental_patchpoint_i64: 6785 visitPatchpoint(I); 6786 return; 6787 case Intrinsic::experimental_gc_statepoint: 6788 LowerStatepoint(cast<GCStatepointInst>(I)); 6789 return; 6790 case Intrinsic::experimental_gc_result: 6791 visitGCResult(cast<GCResultInst>(I)); 6792 return; 6793 case Intrinsic::experimental_gc_relocate: 6794 visitGCRelocate(cast<GCRelocateInst>(I)); 6795 return; 6796 case Intrinsic::instrprof_increment: 6797 llvm_unreachable("instrprof failed to lower an increment"); 6798 case Intrinsic::instrprof_value_profile: 6799 llvm_unreachable("instrprof failed to lower a value profiling call"); 6800 case Intrinsic::localescape: { 6801 MachineFunction &MF = DAG.getMachineFunction(); 6802 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6803 6804 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6805 // is the same on all targets. 6806 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6807 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6808 if (isa<ConstantPointerNull>(Arg)) 6809 continue; // Skip null pointers. They represent a hole in index space. 6810 AllocaInst *Slot = cast<AllocaInst>(Arg); 6811 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6812 "can only escape static allocas"); 6813 int FI = FuncInfo.StaticAllocaMap[Slot]; 6814 MCSymbol *FrameAllocSym = 6815 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6816 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6817 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6818 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6819 .addSym(FrameAllocSym) 6820 .addFrameIndex(FI); 6821 } 6822 6823 return; 6824 } 6825 6826 case Intrinsic::localrecover: { 6827 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6828 MachineFunction &MF = DAG.getMachineFunction(); 6829 6830 // Get the symbol that defines the frame offset. 6831 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6832 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6833 unsigned IdxVal = 6834 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6835 MCSymbol *FrameAllocSym = 6836 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6837 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6838 6839 Value *FP = I.getArgOperand(1); 6840 SDValue FPVal = getValue(FP); 6841 EVT PtrVT = FPVal.getValueType(); 6842 6843 // Create a MCSymbol for the label to avoid any target lowering 6844 // that would make this PC relative. 6845 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6846 SDValue OffsetVal = 6847 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6848 6849 // Add the offset to the FP. 6850 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6851 setValue(&I, Add); 6852 6853 return; 6854 } 6855 6856 case Intrinsic::eh_exceptionpointer: 6857 case Intrinsic::eh_exceptioncode: { 6858 // Get the exception pointer vreg, copy from it, and resize it to fit. 6859 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6860 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6861 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6862 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6863 SDValue N = 6864 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6865 if (Intrinsic == Intrinsic::eh_exceptioncode) 6866 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6867 setValue(&I, N); 6868 return; 6869 } 6870 case Intrinsic::xray_customevent: { 6871 // Here we want to make sure that the intrinsic behaves as if it has a 6872 // specific calling convention, and only for x86_64. 6873 // FIXME: Support other platforms later. 6874 const auto &Triple = DAG.getTarget().getTargetTriple(); 6875 if (Triple.getArch() != Triple::x86_64) 6876 return; 6877 6878 SDLoc DL = getCurSDLoc(); 6879 SmallVector<SDValue, 8> Ops; 6880 6881 // We want to say that we always want the arguments in registers. 6882 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6883 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6884 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6885 SDValue Chain = getRoot(); 6886 Ops.push_back(LogEntryVal); 6887 Ops.push_back(StrSizeVal); 6888 Ops.push_back(Chain); 6889 6890 // We need to enforce the calling convention for the callsite, so that 6891 // argument ordering is enforced correctly, and that register allocation can 6892 // see that some registers may be assumed clobbered and have to preserve 6893 // them across calls to the intrinsic. 6894 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6895 DL, NodeTys, Ops); 6896 SDValue patchableNode = SDValue(MN, 0); 6897 DAG.setRoot(patchableNode); 6898 setValue(&I, patchableNode); 6899 return; 6900 } 6901 case Intrinsic::xray_typedevent: { 6902 // Here we want to make sure that the intrinsic behaves as if it has a 6903 // specific calling convention, and only for x86_64. 6904 // FIXME: Support other platforms later. 6905 const auto &Triple = DAG.getTarget().getTargetTriple(); 6906 if (Triple.getArch() != Triple::x86_64) 6907 return; 6908 6909 SDLoc DL = getCurSDLoc(); 6910 SmallVector<SDValue, 8> Ops; 6911 6912 // We want to say that we always want the arguments in registers. 6913 // It's unclear to me how manipulating the selection DAG here forces callers 6914 // to provide arguments in registers instead of on the stack. 6915 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6916 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6917 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6918 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6919 SDValue Chain = getRoot(); 6920 Ops.push_back(LogTypeId); 6921 Ops.push_back(LogEntryVal); 6922 Ops.push_back(StrSizeVal); 6923 Ops.push_back(Chain); 6924 6925 // We need to enforce the calling convention for the callsite, so that 6926 // argument ordering is enforced correctly, and that register allocation can 6927 // see that some registers may be assumed clobbered and have to preserve 6928 // them across calls to the intrinsic. 6929 MachineSDNode *MN = DAG.getMachineNode( 6930 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6931 SDValue patchableNode = SDValue(MN, 0); 6932 DAG.setRoot(patchableNode); 6933 setValue(&I, patchableNode); 6934 return; 6935 } 6936 case Intrinsic::experimental_deoptimize: 6937 LowerDeoptimizeCall(&I); 6938 return; 6939 6940 case Intrinsic::vector_reduce_fadd: 6941 case Intrinsic::vector_reduce_fmul: 6942 case Intrinsic::vector_reduce_add: 6943 case Intrinsic::vector_reduce_mul: 6944 case Intrinsic::vector_reduce_and: 6945 case Intrinsic::vector_reduce_or: 6946 case Intrinsic::vector_reduce_xor: 6947 case Intrinsic::vector_reduce_smax: 6948 case Intrinsic::vector_reduce_smin: 6949 case Intrinsic::vector_reduce_umax: 6950 case Intrinsic::vector_reduce_umin: 6951 case Intrinsic::vector_reduce_fmax: 6952 case Intrinsic::vector_reduce_fmin: 6953 visitVectorReduce(I, Intrinsic); 6954 return; 6955 6956 case Intrinsic::icall_branch_funnel: { 6957 SmallVector<SDValue, 16> Ops; 6958 Ops.push_back(getValue(I.getArgOperand(0))); 6959 6960 int64_t Offset; 6961 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6962 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6963 if (!Base) 6964 report_fatal_error( 6965 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6966 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6967 6968 struct BranchFunnelTarget { 6969 int64_t Offset; 6970 SDValue Target; 6971 }; 6972 SmallVector<BranchFunnelTarget, 8> Targets; 6973 6974 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6975 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6976 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6977 if (ElemBase != Base) 6978 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6979 "to the same GlobalValue"); 6980 6981 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6982 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6983 if (!GA) 6984 report_fatal_error( 6985 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6986 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6987 GA->getGlobal(), getCurSDLoc(), 6988 Val.getValueType(), GA->getOffset())}); 6989 } 6990 llvm::sort(Targets, 6991 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6992 return T1.Offset < T2.Offset; 6993 }); 6994 6995 for (auto &T : Targets) { 6996 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6997 Ops.push_back(T.Target); 6998 } 6999 7000 Ops.push_back(DAG.getRoot()); // Chain 7001 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7002 getCurSDLoc(), MVT::Other, Ops), 7003 0); 7004 DAG.setRoot(N); 7005 setValue(&I, N); 7006 HasTailCall = true; 7007 return; 7008 } 7009 7010 case Intrinsic::wasm_landingpad_index: 7011 // Information this intrinsic contained has been transferred to 7012 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7013 // delete it now. 7014 return; 7015 7016 case Intrinsic::aarch64_settag: 7017 case Intrinsic::aarch64_settag_zero: { 7018 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7019 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7020 SDValue Val = TSI.EmitTargetCodeForSetTag( 7021 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7022 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7023 ZeroMemory); 7024 DAG.setRoot(Val); 7025 setValue(&I, Val); 7026 return; 7027 } 7028 case Intrinsic::ptrmask: { 7029 SDValue Ptr = getValue(I.getOperand(0)); 7030 SDValue Const = getValue(I.getOperand(1)); 7031 7032 EVT PtrVT = Ptr.getValueType(); 7033 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7034 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7035 return; 7036 } 7037 case Intrinsic::get_active_lane_mask: { 7038 auto DL = getCurSDLoc(); 7039 SDValue Index = getValue(I.getOperand(0)); 7040 SDValue TripCount = getValue(I.getOperand(1)); 7041 Type *ElementTy = I.getOperand(0)->getType(); 7042 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7043 unsigned VecWidth = VT.getVectorNumElements(); 7044 7045 SmallVector<SDValue, 16> OpsTripCount; 7046 SmallVector<SDValue, 16> OpsIndex; 7047 SmallVector<SDValue, 16> OpsStepConstants; 7048 for (unsigned i = 0; i < VecWidth; i++) { 7049 OpsTripCount.push_back(TripCount); 7050 OpsIndex.push_back(Index); 7051 OpsStepConstants.push_back( 7052 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7053 } 7054 7055 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7056 7057 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7058 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7059 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7060 SDValue VectorInduction = DAG.getNode( 7061 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7062 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7063 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7064 VectorTripCount, ISD::CondCode::SETULT); 7065 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7066 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7067 SetCC)); 7068 return; 7069 } 7070 case Intrinsic::experimental_vector_insert: { 7071 auto DL = getCurSDLoc(); 7072 7073 SDValue Vec = getValue(I.getOperand(0)); 7074 SDValue SubVec = getValue(I.getOperand(1)); 7075 SDValue Index = getValue(I.getOperand(2)); 7076 7077 // The intrinsic's index type is i64, but the SDNode requires an index type 7078 // suitable for the target. Convert the index as required. 7079 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7080 if (Index.getValueType() != VectorIdxTy) 7081 Index = DAG.getVectorIdxConstant( 7082 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7083 7084 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7085 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7086 Index)); 7087 return; 7088 } 7089 case Intrinsic::experimental_vector_extract: { 7090 auto DL = getCurSDLoc(); 7091 7092 SDValue Vec = getValue(I.getOperand(0)); 7093 SDValue Index = getValue(I.getOperand(1)); 7094 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7095 7096 // The intrinsic's index type is i64, but the SDNode requires an index type 7097 // suitable for the target. Convert the index as required. 7098 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7099 if (Index.getValueType() != VectorIdxTy) 7100 Index = DAG.getVectorIdxConstant( 7101 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7102 7103 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7104 return; 7105 } 7106 case Intrinsic::experimental_vector_reverse: 7107 visitVectorReverse(I); 7108 return; 7109 case Intrinsic::experimental_vector_splice: 7110 visitVectorSplice(I); 7111 return; 7112 } 7113 } 7114 7115 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7116 const ConstrainedFPIntrinsic &FPI) { 7117 SDLoc sdl = getCurSDLoc(); 7118 7119 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7120 SmallVector<EVT, 4> ValueVTs; 7121 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7122 ValueVTs.push_back(MVT::Other); // Out chain 7123 7124 // We do not need to serialize constrained FP intrinsics against 7125 // each other or against (nonvolatile) loads, so they can be 7126 // chained like loads. 7127 SDValue Chain = DAG.getRoot(); 7128 SmallVector<SDValue, 4> Opers; 7129 Opers.push_back(Chain); 7130 if (FPI.isUnaryOp()) { 7131 Opers.push_back(getValue(FPI.getArgOperand(0))); 7132 } else if (FPI.isTernaryOp()) { 7133 Opers.push_back(getValue(FPI.getArgOperand(0))); 7134 Opers.push_back(getValue(FPI.getArgOperand(1))); 7135 Opers.push_back(getValue(FPI.getArgOperand(2))); 7136 } else { 7137 Opers.push_back(getValue(FPI.getArgOperand(0))); 7138 Opers.push_back(getValue(FPI.getArgOperand(1))); 7139 } 7140 7141 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7142 assert(Result.getNode()->getNumValues() == 2); 7143 7144 // Push node to the appropriate list so that future instructions can be 7145 // chained up correctly. 7146 SDValue OutChain = Result.getValue(1); 7147 switch (EB) { 7148 case fp::ExceptionBehavior::ebIgnore: 7149 // The only reason why ebIgnore nodes still need to be chained is that 7150 // they might depend on the current rounding mode, and therefore must 7151 // not be moved across instruction that may change that mode. 7152 LLVM_FALLTHROUGH; 7153 case fp::ExceptionBehavior::ebMayTrap: 7154 // These must not be moved across calls or instructions that may change 7155 // floating-point exception masks. 7156 PendingConstrainedFP.push_back(OutChain); 7157 break; 7158 case fp::ExceptionBehavior::ebStrict: 7159 // These must not be moved across calls or instructions that may change 7160 // floating-point exception masks or read floating-point exception flags. 7161 // In addition, they cannot be optimized out even if unused. 7162 PendingConstrainedFPStrict.push_back(OutChain); 7163 break; 7164 } 7165 }; 7166 7167 SDVTList VTs = DAG.getVTList(ValueVTs); 7168 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7169 7170 SDNodeFlags Flags; 7171 if (EB == fp::ExceptionBehavior::ebIgnore) 7172 Flags.setNoFPExcept(true); 7173 7174 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7175 Flags.copyFMF(*FPOp); 7176 7177 unsigned Opcode; 7178 switch (FPI.getIntrinsicID()) { 7179 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7180 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7181 case Intrinsic::INTRINSIC: \ 7182 Opcode = ISD::STRICT_##DAGN; \ 7183 break; 7184 #include "llvm/IR/ConstrainedOps.def" 7185 case Intrinsic::experimental_constrained_fmuladd: { 7186 Opcode = ISD::STRICT_FMA; 7187 // Break fmuladd into fmul and fadd. 7188 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7189 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7190 ValueVTs[0])) { 7191 Opers.pop_back(); 7192 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7193 pushOutChain(Mul, EB); 7194 Opcode = ISD::STRICT_FADD; 7195 Opers.clear(); 7196 Opers.push_back(Mul.getValue(1)); 7197 Opers.push_back(Mul.getValue(0)); 7198 Opers.push_back(getValue(FPI.getArgOperand(2))); 7199 } 7200 break; 7201 } 7202 } 7203 7204 // A few strict DAG nodes carry additional operands that are not 7205 // set up by the default code above. 7206 switch (Opcode) { 7207 default: break; 7208 case ISD::STRICT_FP_ROUND: 7209 Opers.push_back( 7210 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7211 break; 7212 case ISD::STRICT_FSETCC: 7213 case ISD::STRICT_FSETCCS: { 7214 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7215 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7216 if (TM.Options.NoNaNsFPMath) 7217 Condition = getFCmpCodeWithoutNaN(Condition); 7218 Opers.push_back(DAG.getCondCode(Condition)); 7219 break; 7220 } 7221 } 7222 7223 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7224 pushOutChain(Result, EB); 7225 7226 SDValue FPResult = Result.getValue(0); 7227 setValue(&FPI, FPResult); 7228 } 7229 7230 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7231 Optional<unsigned> ResOPC; 7232 switch (VPIntrin.getIntrinsicID()) { 7233 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7234 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7235 #define END_REGISTER_VP_INTRINSIC(...) break; 7236 #include "llvm/IR/VPIntrinsics.def" 7237 } 7238 7239 if (!ResOPC.hasValue()) 7240 llvm_unreachable( 7241 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7242 7243 return ResOPC.getValue(); 7244 } 7245 7246 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7247 const VPIntrinsic &VPIntrin) { 7248 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7249 7250 SmallVector<EVT, 4> ValueVTs; 7251 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7252 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7253 SDVTList VTs = DAG.getVTList(ValueVTs); 7254 7255 // Request operands. 7256 SmallVector<SDValue, 7> OpValues; 7257 for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i) 7258 OpValues.push_back(getValue(VPIntrin.getArgOperand(i))); 7259 7260 SDLoc DL = getCurSDLoc(); 7261 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7262 setValue(&VPIntrin, Result); 7263 } 7264 7265 std::pair<SDValue, SDValue> 7266 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7267 const BasicBlock *EHPadBB) { 7268 MachineFunction &MF = DAG.getMachineFunction(); 7269 MachineModuleInfo &MMI = MF.getMMI(); 7270 MCSymbol *BeginLabel = nullptr; 7271 7272 if (EHPadBB) { 7273 // Insert a label before the invoke call to mark the try range. This can be 7274 // used to detect deletion of the invoke via the MachineModuleInfo. 7275 BeginLabel = MMI.getContext().createTempSymbol(); 7276 7277 // For SjLj, keep track of which landing pads go with which invokes 7278 // so as to maintain the ordering of pads in the LSDA. 7279 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7280 if (CallSiteIndex) { 7281 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7282 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7283 7284 // Now that the call site is handled, stop tracking it. 7285 MMI.setCurrentCallSite(0); 7286 } 7287 7288 // Both PendingLoads and PendingExports must be flushed here; 7289 // this call might not return. 7290 (void)getRoot(); 7291 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7292 7293 CLI.setChain(getRoot()); 7294 } 7295 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7296 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7297 7298 assert((CLI.IsTailCall || Result.second.getNode()) && 7299 "Non-null chain expected with non-tail call!"); 7300 assert((Result.second.getNode() || !Result.first.getNode()) && 7301 "Null value expected with tail call!"); 7302 7303 if (!Result.second.getNode()) { 7304 // As a special case, a null chain means that a tail call has been emitted 7305 // and the DAG root is already updated. 7306 HasTailCall = true; 7307 7308 // Since there's no actual continuation from this block, nothing can be 7309 // relying on us setting vregs for them. 7310 PendingExports.clear(); 7311 } else { 7312 DAG.setRoot(Result.second); 7313 } 7314 7315 if (EHPadBB) { 7316 // Insert a label at the end of the invoke call to mark the try range. This 7317 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7318 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7319 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7320 7321 // Inform MachineModuleInfo of range. 7322 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7323 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7324 // actually use outlined funclets and their LSDA info style. 7325 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7326 assert(CLI.CB); 7327 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7328 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7329 } else if (!isScopedEHPersonality(Pers)) { 7330 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7331 } 7332 } 7333 7334 return Result; 7335 } 7336 7337 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7338 bool isTailCall, 7339 const BasicBlock *EHPadBB) { 7340 auto &DL = DAG.getDataLayout(); 7341 FunctionType *FTy = CB.getFunctionType(); 7342 Type *RetTy = CB.getType(); 7343 7344 TargetLowering::ArgListTy Args; 7345 Args.reserve(CB.arg_size()); 7346 7347 const Value *SwiftErrorVal = nullptr; 7348 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7349 7350 if (isTailCall) { 7351 // Avoid emitting tail calls in functions with the disable-tail-calls 7352 // attribute. 7353 auto *Caller = CB.getParent()->getParent(); 7354 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7355 "true") 7356 isTailCall = false; 7357 7358 // We can't tail call inside a function with a swifterror argument. Lowering 7359 // does not support this yet. It would have to move into the swifterror 7360 // register before the call. 7361 if (TLI.supportSwiftError() && 7362 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7363 isTailCall = false; 7364 } 7365 7366 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7367 TargetLowering::ArgListEntry Entry; 7368 const Value *V = *I; 7369 7370 // Skip empty types 7371 if (V->getType()->isEmptyTy()) 7372 continue; 7373 7374 SDValue ArgNode = getValue(V); 7375 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7376 7377 Entry.setAttributes(&CB, I - CB.arg_begin()); 7378 7379 // Use swifterror virtual register as input to the call. 7380 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7381 SwiftErrorVal = V; 7382 // We find the virtual register for the actual swifterror argument. 7383 // Instead of using the Value, we use the virtual register instead. 7384 Entry.Node = 7385 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7386 EVT(TLI.getPointerTy(DL))); 7387 } 7388 7389 Args.push_back(Entry); 7390 7391 // If we have an explicit sret argument that is an Instruction, (i.e., it 7392 // might point to function-local memory), we can't meaningfully tail-call. 7393 if (Entry.IsSRet && isa<Instruction>(V)) 7394 isTailCall = false; 7395 } 7396 7397 // If call site has a cfguardtarget operand bundle, create and add an 7398 // additional ArgListEntry. 7399 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7400 TargetLowering::ArgListEntry Entry; 7401 Value *V = Bundle->Inputs[0]; 7402 SDValue ArgNode = getValue(V); 7403 Entry.Node = ArgNode; 7404 Entry.Ty = V->getType(); 7405 Entry.IsCFGuardTarget = true; 7406 Args.push_back(Entry); 7407 } 7408 7409 // Check if target-independent constraints permit a tail call here. 7410 // Target-dependent constraints are checked within TLI->LowerCallTo. 7411 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7412 isTailCall = false; 7413 7414 // Disable tail calls if there is an swifterror argument. Targets have not 7415 // been updated to support tail calls. 7416 if (TLI.supportSwiftError() && SwiftErrorVal) 7417 isTailCall = false; 7418 7419 TargetLowering::CallLoweringInfo CLI(DAG); 7420 CLI.setDebugLoc(getCurSDLoc()) 7421 .setChain(getRoot()) 7422 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7423 .setTailCall(isTailCall) 7424 .setConvergent(CB.isConvergent()) 7425 .setIsPreallocated( 7426 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7427 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7428 7429 if (Result.first.getNode()) { 7430 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7431 setValue(&CB, Result.first); 7432 } 7433 7434 // The last element of CLI.InVals has the SDValue for swifterror return. 7435 // Here we copy it to a virtual register and update SwiftErrorMap for 7436 // book-keeping. 7437 if (SwiftErrorVal && TLI.supportSwiftError()) { 7438 // Get the last element of InVals. 7439 SDValue Src = CLI.InVals.back(); 7440 Register VReg = 7441 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7442 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7443 DAG.setRoot(CopyNode); 7444 } 7445 } 7446 7447 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7448 SelectionDAGBuilder &Builder) { 7449 // Check to see if this load can be trivially constant folded, e.g. if the 7450 // input is from a string literal. 7451 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7452 // Cast pointer to the type we really want to load. 7453 Type *LoadTy = 7454 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7455 if (LoadVT.isVector()) 7456 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7457 7458 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7459 PointerType::getUnqual(LoadTy)); 7460 7461 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7462 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7463 return Builder.getValue(LoadCst); 7464 } 7465 7466 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7467 // still constant memory, the input chain can be the entry node. 7468 SDValue Root; 7469 bool ConstantMemory = false; 7470 7471 // Do not serialize (non-volatile) loads of constant memory with anything. 7472 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7473 Root = Builder.DAG.getEntryNode(); 7474 ConstantMemory = true; 7475 } else { 7476 // Do not serialize non-volatile loads against each other. 7477 Root = Builder.DAG.getRoot(); 7478 } 7479 7480 SDValue Ptr = Builder.getValue(PtrVal); 7481 SDValue LoadVal = 7482 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7483 MachinePointerInfo(PtrVal), Align(1)); 7484 7485 if (!ConstantMemory) 7486 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7487 return LoadVal; 7488 } 7489 7490 /// Record the value for an instruction that produces an integer result, 7491 /// converting the type where necessary. 7492 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7493 SDValue Value, 7494 bool IsSigned) { 7495 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7496 I.getType(), true); 7497 if (IsSigned) 7498 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7499 else 7500 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7501 setValue(&I, Value); 7502 } 7503 7504 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7505 /// true and lower it. Otherwise return false, and it will be lowered like a 7506 /// normal call. 7507 /// The caller already checked that \p I calls the appropriate LibFunc with a 7508 /// correct prototype. 7509 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7510 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7511 const Value *Size = I.getArgOperand(2); 7512 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7513 if (CSize && CSize->getZExtValue() == 0) { 7514 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7515 I.getType(), true); 7516 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7517 return true; 7518 } 7519 7520 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7521 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7522 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7523 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7524 if (Res.first.getNode()) { 7525 processIntegerCallValue(I, Res.first, true); 7526 PendingLoads.push_back(Res.second); 7527 return true; 7528 } 7529 7530 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7531 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7532 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7533 return false; 7534 7535 // If the target has a fast compare for the given size, it will return a 7536 // preferred load type for that size. Require that the load VT is legal and 7537 // that the target supports unaligned loads of that type. Otherwise, return 7538 // INVALID. 7539 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7540 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7541 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7542 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7543 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7544 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7545 // TODO: Check alignment of src and dest ptrs. 7546 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7547 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7548 if (!TLI.isTypeLegal(LVT) || 7549 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7550 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7551 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7552 } 7553 7554 return LVT; 7555 }; 7556 7557 // This turns into unaligned loads. We only do this if the target natively 7558 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7559 // we'll only produce a small number of byte loads. 7560 MVT LoadVT; 7561 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7562 switch (NumBitsToCompare) { 7563 default: 7564 return false; 7565 case 16: 7566 LoadVT = MVT::i16; 7567 break; 7568 case 32: 7569 LoadVT = MVT::i32; 7570 break; 7571 case 64: 7572 case 128: 7573 case 256: 7574 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7575 break; 7576 } 7577 7578 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7579 return false; 7580 7581 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7582 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7583 7584 // Bitcast to a wide integer type if the loads are vectors. 7585 if (LoadVT.isVector()) { 7586 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7587 LoadL = DAG.getBitcast(CmpVT, LoadL); 7588 LoadR = DAG.getBitcast(CmpVT, LoadR); 7589 } 7590 7591 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7592 processIntegerCallValue(I, Cmp, false); 7593 return true; 7594 } 7595 7596 /// See if we can lower a memchr call into an optimized form. If so, return 7597 /// true and lower it. Otherwise return false, and it will be lowered like a 7598 /// normal call. 7599 /// The caller already checked that \p I calls the appropriate LibFunc with a 7600 /// correct prototype. 7601 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7602 const Value *Src = I.getArgOperand(0); 7603 const Value *Char = I.getArgOperand(1); 7604 const Value *Length = I.getArgOperand(2); 7605 7606 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7607 std::pair<SDValue, SDValue> Res = 7608 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7609 getValue(Src), getValue(Char), getValue(Length), 7610 MachinePointerInfo(Src)); 7611 if (Res.first.getNode()) { 7612 setValue(&I, Res.first); 7613 PendingLoads.push_back(Res.second); 7614 return true; 7615 } 7616 7617 return false; 7618 } 7619 7620 /// See if we can lower a mempcpy call into an optimized form. If so, return 7621 /// true and lower it. Otherwise return false, and it will be lowered like a 7622 /// normal call. 7623 /// The caller already checked that \p I calls the appropriate LibFunc with a 7624 /// correct prototype. 7625 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7626 SDValue Dst = getValue(I.getArgOperand(0)); 7627 SDValue Src = getValue(I.getArgOperand(1)); 7628 SDValue Size = getValue(I.getArgOperand(2)); 7629 7630 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7631 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7632 // DAG::getMemcpy needs Alignment to be defined. 7633 Align Alignment = std::min(DstAlign, SrcAlign); 7634 7635 bool isVol = false; 7636 SDLoc sdl = getCurSDLoc(); 7637 7638 // In the mempcpy context we need to pass in a false value for isTailCall 7639 // because the return pointer needs to be adjusted by the size of 7640 // the copied memory. 7641 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7642 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7643 /*isTailCall=*/false, 7644 MachinePointerInfo(I.getArgOperand(0)), 7645 MachinePointerInfo(I.getArgOperand(1))); 7646 assert(MC.getNode() != nullptr && 7647 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7648 DAG.setRoot(MC); 7649 7650 // Check if Size needs to be truncated or extended. 7651 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7652 7653 // Adjust return pointer to point just past the last dst byte. 7654 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7655 Dst, Size); 7656 setValue(&I, DstPlusSize); 7657 return true; 7658 } 7659 7660 /// See if we can lower a strcpy call into an optimized form. If so, return 7661 /// true and lower it, otherwise return false and it will be lowered like a 7662 /// normal call. 7663 /// The caller already checked that \p I calls the appropriate LibFunc with a 7664 /// correct prototype. 7665 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7666 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7667 7668 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7669 std::pair<SDValue, SDValue> Res = 7670 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7671 getValue(Arg0), getValue(Arg1), 7672 MachinePointerInfo(Arg0), 7673 MachinePointerInfo(Arg1), isStpcpy); 7674 if (Res.first.getNode()) { 7675 setValue(&I, Res.first); 7676 DAG.setRoot(Res.second); 7677 return true; 7678 } 7679 7680 return false; 7681 } 7682 7683 /// See if we can lower a strcmp call into an optimized form. If so, return 7684 /// true and lower it, otherwise return false and it will be lowered like a 7685 /// normal call. 7686 /// The caller already checked that \p I calls the appropriate LibFunc with a 7687 /// correct prototype. 7688 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7689 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7690 7691 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7692 std::pair<SDValue, SDValue> Res = 7693 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7694 getValue(Arg0), getValue(Arg1), 7695 MachinePointerInfo(Arg0), 7696 MachinePointerInfo(Arg1)); 7697 if (Res.first.getNode()) { 7698 processIntegerCallValue(I, Res.first, true); 7699 PendingLoads.push_back(Res.second); 7700 return true; 7701 } 7702 7703 return false; 7704 } 7705 7706 /// See if we can lower a strlen call into an optimized form. If so, return 7707 /// true and lower it, otherwise return false and it will be lowered like a 7708 /// normal call. 7709 /// The caller already checked that \p I calls the appropriate LibFunc with a 7710 /// correct prototype. 7711 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7712 const Value *Arg0 = I.getArgOperand(0); 7713 7714 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7715 std::pair<SDValue, SDValue> Res = 7716 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7717 getValue(Arg0), MachinePointerInfo(Arg0)); 7718 if (Res.first.getNode()) { 7719 processIntegerCallValue(I, Res.first, false); 7720 PendingLoads.push_back(Res.second); 7721 return true; 7722 } 7723 7724 return false; 7725 } 7726 7727 /// See if we can lower a strnlen call into an optimized form. If so, return 7728 /// true and lower it, otherwise return false and it will be lowered like a 7729 /// normal call. 7730 /// The caller already checked that \p I calls the appropriate LibFunc with a 7731 /// correct prototype. 7732 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7733 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7734 7735 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7736 std::pair<SDValue, SDValue> Res = 7737 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7738 getValue(Arg0), getValue(Arg1), 7739 MachinePointerInfo(Arg0)); 7740 if (Res.first.getNode()) { 7741 processIntegerCallValue(I, Res.first, false); 7742 PendingLoads.push_back(Res.second); 7743 return true; 7744 } 7745 7746 return false; 7747 } 7748 7749 /// See if we can lower a unary floating-point operation into an SDNode with 7750 /// the specified Opcode. If so, return true and lower it, otherwise return 7751 /// false and it will be lowered like a normal call. 7752 /// The caller already checked that \p I calls the appropriate LibFunc with a 7753 /// correct prototype. 7754 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7755 unsigned Opcode) { 7756 // We already checked this call's prototype; verify it doesn't modify errno. 7757 if (!I.onlyReadsMemory()) 7758 return false; 7759 7760 SDNodeFlags Flags; 7761 Flags.copyFMF(cast<FPMathOperator>(I)); 7762 7763 SDValue Tmp = getValue(I.getArgOperand(0)); 7764 setValue(&I, 7765 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7766 return true; 7767 } 7768 7769 /// See if we can lower a binary floating-point operation into an SDNode with 7770 /// the specified Opcode. If so, return true and lower it. Otherwise return 7771 /// false, and it will be lowered like a normal call. 7772 /// The caller already checked that \p I calls the appropriate LibFunc with a 7773 /// correct prototype. 7774 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7775 unsigned Opcode) { 7776 // We already checked this call's prototype; verify it doesn't modify errno. 7777 if (!I.onlyReadsMemory()) 7778 return false; 7779 7780 SDNodeFlags Flags; 7781 Flags.copyFMF(cast<FPMathOperator>(I)); 7782 7783 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7784 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7785 EVT VT = Tmp0.getValueType(); 7786 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7787 return true; 7788 } 7789 7790 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7791 // Handle inline assembly differently. 7792 if (I.isInlineAsm()) { 7793 visitInlineAsm(I); 7794 return; 7795 } 7796 7797 if (Function *F = I.getCalledFunction()) { 7798 if (F->isDeclaration()) { 7799 // Is this an LLVM intrinsic or a target-specific intrinsic? 7800 unsigned IID = F->getIntrinsicID(); 7801 if (!IID) 7802 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7803 IID = II->getIntrinsicID(F); 7804 7805 if (IID) { 7806 visitIntrinsicCall(I, IID); 7807 return; 7808 } 7809 } 7810 7811 // Check for well-known libc/libm calls. If the function is internal, it 7812 // can't be a library call. Don't do the check if marked as nobuiltin for 7813 // some reason or the call site requires strict floating point semantics. 7814 LibFunc Func; 7815 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7816 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7817 LibInfo->hasOptimizedCodeGen(Func)) { 7818 switch (Func) { 7819 default: break; 7820 case LibFunc_bcmp: 7821 if (visitMemCmpBCmpCall(I)) 7822 return; 7823 break; 7824 case LibFunc_copysign: 7825 case LibFunc_copysignf: 7826 case LibFunc_copysignl: 7827 // We already checked this call's prototype; verify it doesn't modify 7828 // errno. 7829 if (I.onlyReadsMemory()) { 7830 SDValue LHS = getValue(I.getArgOperand(0)); 7831 SDValue RHS = getValue(I.getArgOperand(1)); 7832 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7833 LHS.getValueType(), LHS, RHS)); 7834 return; 7835 } 7836 break; 7837 case LibFunc_fabs: 7838 case LibFunc_fabsf: 7839 case LibFunc_fabsl: 7840 if (visitUnaryFloatCall(I, ISD::FABS)) 7841 return; 7842 break; 7843 case LibFunc_fmin: 7844 case LibFunc_fminf: 7845 case LibFunc_fminl: 7846 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7847 return; 7848 break; 7849 case LibFunc_fmax: 7850 case LibFunc_fmaxf: 7851 case LibFunc_fmaxl: 7852 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7853 return; 7854 break; 7855 case LibFunc_sin: 7856 case LibFunc_sinf: 7857 case LibFunc_sinl: 7858 if (visitUnaryFloatCall(I, ISD::FSIN)) 7859 return; 7860 break; 7861 case LibFunc_cos: 7862 case LibFunc_cosf: 7863 case LibFunc_cosl: 7864 if (visitUnaryFloatCall(I, ISD::FCOS)) 7865 return; 7866 break; 7867 case LibFunc_sqrt: 7868 case LibFunc_sqrtf: 7869 case LibFunc_sqrtl: 7870 case LibFunc_sqrt_finite: 7871 case LibFunc_sqrtf_finite: 7872 case LibFunc_sqrtl_finite: 7873 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7874 return; 7875 break; 7876 case LibFunc_floor: 7877 case LibFunc_floorf: 7878 case LibFunc_floorl: 7879 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7880 return; 7881 break; 7882 case LibFunc_nearbyint: 7883 case LibFunc_nearbyintf: 7884 case LibFunc_nearbyintl: 7885 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7886 return; 7887 break; 7888 case LibFunc_ceil: 7889 case LibFunc_ceilf: 7890 case LibFunc_ceill: 7891 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7892 return; 7893 break; 7894 case LibFunc_rint: 7895 case LibFunc_rintf: 7896 case LibFunc_rintl: 7897 if (visitUnaryFloatCall(I, ISD::FRINT)) 7898 return; 7899 break; 7900 case LibFunc_round: 7901 case LibFunc_roundf: 7902 case LibFunc_roundl: 7903 if (visitUnaryFloatCall(I, ISD::FROUND)) 7904 return; 7905 break; 7906 case LibFunc_trunc: 7907 case LibFunc_truncf: 7908 case LibFunc_truncl: 7909 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7910 return; 7911 break; 7912 case LibFunc_log2: 7913 case LibFunc_log2f: 7914 case LibFunc_log2l: 7915 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7916 return; 7917 break; 7918 case LibFunc_exp2: 7919 case LibFunc_exp2f: 7920 case LibFunc_exp2l: 7921 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7922 return; 7923 break; 7924 case LibFunc_memcmp: 7925 if (visitMemCmpBCmpCall(I)) 7926 return; 7927 break; 7928 case LibFunc_mempcpy: 7929 if (visitMemPCpyCall(I)) 7930 return; 7931 break; 7932 case LibFunc_memchr: 7933 if (visitMemChrCall(I)) 7934 return; 7935 break; 7936 case LibFunc_strcpy: 7937 if (visitStrCpyCall(I, false)) 7938 return; 7939 break; 7940 case LibFunc_stpcpy: 7941 if (visitStrCpyCall(I, true)) 7942 return; 7943 break; 7944 case LibFunc_strcmp: 7945 if (visitStrCmpCall(I)) 7946 return; 7947 break; 7948 case LibFunc_strlen: 7949 if (visitStrLenCall(I)) 7950 return; 7951 break; 7952 case LibFunc_strnlen: 7953 if (visitStrNLenCall(I)) 7954 return; 7955 break; 7956 } 7957 } 7958 } 7959 7960 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7961 // have to do anything here to lower funclet bundles. 7962 // CFGuardTarget bundles are lowered in LowerCallTo. 7963 assert(!I.hasOperandBundlesOtherThan( 7964 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7965 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 7966 LLVMContext::OB_clang_arc_attachedcall}) && 7967 "Cannot lower calls with arbitrary operand bundles!"); 7968 7969 SDValue Callee = getValue(I.getCalledOperand()); 7970 7971 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7972 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7973 else 7974 // Check if we can potentially perform a tail call. More detailed checking 7975 // is be done within LowerCallTo, after more information about the call is 7976 // known. 7977 LowerCallTo(I, Callee, I.isTailCall()); 7978 } 7979 7980 namespace { 7981 7982 /// AsmOperandInfo - This contains information for each constraint that we are 7983 /// lowering. 7984 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7985 public: 7986 /// CallOperand - If this is the result output operand or a clobber 7987 /// this is null, otherwise it is the incoming operand to the CallInst. 7988 /// This gets modified as the asm is processed. 7989 SDValue CallOperand; 7990 7991 /// AssignedRegs - If this is a register or register class operand, this 7992 /// contains the set of register corresponding to the operand. 7993 RegsForValue AssignedRegs; 7994 7995 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7996 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7997 } 7998 7999 /// Whether or not this operand accesses memory 8000 bool hasMemory(const TargetLowering &TLI) const { 8001 // Indirect operand accesses access memory. 8002 if (isIndirect) 8003 return true; 8004 8005 for (const auto &Code : Codes) 8006 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8007 return true; 8008 8009 return false; 8010 } 8011 8012 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8013 /// corresponds to. If there is no Value* for this operand, it returns 8014 /// MVT::Other. 8015 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8016 const DataLayout &DL) const { 8017 if (!CallOperandVal) return MVT::Other; 8018 8019 if (isa<BasicBlock>(CallOperandVal)) 8020 return TLI.getProgramPointerTy(DL); 8021 8022 llvm::Type *OpTy = CallOperandVal->getType(); 8023 8024 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8025 // If this is an indirect operand, the operand is a pointer to the 8026 // accessed type. 8027 if (isIndirect) { 8028 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8029 if (!PtrTy) 8030 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8031 OpTy = PtrTy->getElementType(); 8032 } 8033 8034 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8035 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8036 if (STy->getNumElements() == 1) 8037 OpTy = STy->getElementType(0); 8038 8039 // If OpTy is not a single value, it may be a struct/union that we 8040 // can tile with integers. 8041 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8042 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8043 switch (BitSize) { 8044 default: break; 8045 case 1: 8046 case 8: 8047 case 16: 8048 case 32: 8049 case 64: 8050 case 128: 8051 OpTy = IntegerType::get(Context, BitSize); 8052 break; 8053 } 8054 } 8055 8056 return TLI.getValueType(DL, OpTy, true); 8057 } 8058 }; 8059 8060 8061 } // end anonymous namespace 8062 8063 /// Make sure that the output operand \p OpInfo and its corresponding input 8064 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8065 /// out). 8066 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8067 SDISelAsmOperandInfo &MatchingOpInfo, 8068 SelectionDAG &DAG) { 8069 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8070 return; 8071 8072 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8073 const auto &TLI = DAG.getTargetLoweringInfo(); 8074 8075 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8076 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8077 OpInfo.ConstraintVT); 8078 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8079 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8080 MatchingOpInfo.ConstraintVT); 8081 if ((OpInfo.ConstraintVT.isInteger() != 8082 MatchingOpInfo.ConstraintVT.isInteger()) || 8083 (MatchRC.second != InputRC.second)) { 8084 // FIXME: error out in a more elegant fashion 8085 report_fatal_error("Unsupported asm: input constraint" 8086 " with a matching output constraint of" 8087 " incompatible type!"); 8088 } 8089 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8090 } 8091 8092 /// Get a direct memory input to behave well as an indirect operand. 8093 /// This may introduce stores, hence the need for a \p Chain. 8094 /// \return The (possibly updated) chain. 8095 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8096 SDISelAsmOperandInfo &OpInfo, 8097 SelectionDAG &DAG) { 8098 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8099 8100 // If we don't have an indirect input, put it in the constpool if we can, 8101 // otherwise spill it to a stack slot. 8102 // TODO: This isn't quite right. We need to handle these according to 8103 // the addressing mode that the constraint wants. Also, this may take 8104 // an additional register for the computation and we don't want that 8105 // either. 8106 8107 // If the operand is a float, integer, or vector constant, spill to a 8108 // constant pool entry to get its address. 8109 const Value *OpVal = OpInfo.CallOperandVal; 8110 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8111 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8112 OpInfo.CallOperand = DAG.getConstantPool( 8113 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8114 return Chain; 8115 } 8116 8117 // Otherwise, create a stack slot and emit a store to it before the asm. 8118 Type *Ty = OpVal->getType(); 8119 auto &DL = DAG.getDataLayout(); 8120 uint64_t TySize = DL.getTypeAllocSize(Ty); 8121 MachineFunction &MF = DAG.getMachineFunction(); 8122 int SSFI = MF.getFrameInfo().CreateStackObject( 8123 TySize, DL.getPrefTypeAlign(Ty), false); 8124 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8125 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8126 MachinePointerInfo::getFixedStack(MF, SSFI), 8127 TLI.getMemValueType(DL, Ty)); 8128 OpInfo.CallOperand = StackSlot; 8129 8130 return Chain; 8131 } 8132 8133 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8134 /// specified operand. We prefer to assign virtual registers, to allow the 8135 /// register allocator to handle the assignment process. However, if the asm 8136 /// uses features that we can't model on machineinstrs, we have SDISel do the 8137 /// allocation. This produces generally horrible, but correct, code. 8138 /// 8139 /// OpInfo describes the operand 8140 /// RefOpInfo describes the matching operand if any, the operand otherwise 8141 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8142 SDISelAsmOperandInfo &OpInfo, 8143 SDISelAsmOperandInfo &RefOpInfo) { 8144 LLVMContext &Context = *DAG.getContext(); 8145 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8146 8147 MachineFunction &MF = DAG.getMachineFunction(); 8148 SmallVector<unsigned, 4> Regs; 8149 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8150 8151 // No work to do for memory operations. 8152 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8153 return; 8154 8155 // If this is a constraint for a single physreg, or a constraint for a 8156 // register class, find it. 8157 unsigned AssignedReg; 8158 const TargetRegisterClass *RC; 8159 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8160 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8161 // RC is unset only on failure. Return immediately. 8162 if (!RC) 8163 return; 8164 8165 // Get the actual register value type. This is important, because the user 8166 // may have asked for (e.g.) the AX register in i32 type. We need to 8167 // remember that AX is actually i16 to get the right extension. 8168 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8169 8170 if (OpInfo.ConstraintVT != MVT::Other) { 8171 // If this is an FP operand in an integer register (or visa versa), or more 8172 // generally if the operand value disagrees with the register class we plan 8173 // to stick it in, fix the operand type. 8174 // 8175 // If this is an input value, the bitcast to the new type is done now. 8176 // Bitcast for output value is done at the end of visitInlineAsm(). 8177 if ((OpInfo.Type == InlineAsm::isOutput || 8178 OpInfo.Type == InlineAsm::isInput) && 8179 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8180 // Try to convert to the first EVT that the reg class contains. If the 8181 // types are identical size, use a bitcast to convert (e.g. two differing 8182 // vector types). Note: output bitcast is done at the end of 8183 // visitInlineAsm(). 8184 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8185 // Exclude indirect inputs while they are unsupported because the code 8186 // to perform the load is missing and thus OpInfo.CallOperand still 8187 // refers to the input address rather than the pointed-to value. 8188 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8189 OpInfo.CallOperand = 8190 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8191 OpInfo.ConstraintVT = RegVT; 8192 // If the operand is an FP value and we want it in integer registers, 8193 // use the corresponding integer type. This turns an f64 value into 8194 // i64, which can be passed with two i32 values on a 32-bit machine. 8195 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8196 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8197 if (OpInfo.Type == InlineAsm::isInput) 8198 OpInfo.CallOperand = 8199 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8200 OpInfo.ConstraintVT = VT; 8201 } 8202 } 8203 } 8204 8205 // No need to allocate a matching input constraint since the constraint it's 8206 // matching to has already been allocated. 8207 if (OpInfo.isMatchingInputConstraint()) 8208 return; 8209 8210 EVT ValueVT = OpInfo.ConstraintVT; 8211 if (OpInfo.ConstraintVT == MVT::Other) 8212 ValueVT = RegVT; 8213 8214 // Initialize NumRegs. 8215 unsigned NumRegs = 1; 8216 if (OpInfo.ConstraintVT != MVT::Other) 8217 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8218 8219 // If this is a constraint for a specific physical register, like {r17}, 8220 // assign it now. 8221 8222 // If this associated to a specific register, initialize iterator to correct 8223 // place. If virtual, make sure we have enough registers 8224 8225 // Initialize iterator if necessary 8226 TargetRegisterClass::iterator I = RC->begin(); 8227 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8228 8229 // Do not check for single registers. 8230 if (AssignedReg) { 8231 for (; *I != AssignedReg; ++I) 8232 assert(I != RC->end() && "AssignedReg should be member of RC"); 8233 } 8234 8235 for (; NumRegs; --NumRegs, ++I) { 8236 assert(I != RC->end() && "Ran out of registers to allocate!"); 8237 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8238 Regs.push_back(R); 8239 } 8240 8241 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8242 } 8243 8244 static unsigned 8245 findMatchingInlineAsmOperand(unsigned OperandNo, 8246 const std::vector<SDValue> &AsmNodeOperands) { 8247 // Scan until we find the definition we already emitted of this operand. 8248 unsigned CurOp = InlineAsm::Op_FirstOperand; 8249 for (; OperandNo; --OperandNo) { 8250 // Advance to the next operand. 8251 unsigned OpFlag = 8252 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8253 assert((InlineAsm::isRegDefKind(OpFlag) || 8254 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8255 InlineAsm::isMemKind(OpFlag)) && 8256 "Skipped past definitions?"); 8257 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8258 } 8259 return CurOp; 8260 } 8261 8262 namespace { 8263 8264 class ExtraFlags { 8265 unsigned Flags = 0; 8266 8267 public: 8268 explicit ExtraFlags(const CallBase &Call) { 8269 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8270 if (IA->hasSideEffects()) 8271 Flags |= InlineAsm::Extra_HasSideEffects; 8272 if (IA->isAlignStack()) 8273 Flags |= InlineAsm::Extra_IsAlignStack; 8274 if (Call.isConvergent()) 8275 Flags |= InlineAsm::Extra_IsConvergent; 8276 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8277 } 8278 8279 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8280 // Ideally, we would only check against memory constraints. However, the 8281 // meaning of an Other constraint can be target-specific and we can't easily 8282 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8283 // for Other constraints as well. 8284 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8285 OpInfo.ConstraintType == TargetLowering::C_Other) { 8286 if (OpInfo.Type == InlineAsm::isInput) 8287 Flags |= InlineAsm::Extra_MayLoad; 8288 else if (OpInfo.Type == InlineAsm::isOutput) 8289 Flags |= InlineAsm::Extra_MayStore; 8290 else if (OpInfo.Type == InlineAsm::isClobber) 8291 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8292 } 8293 } 8294 8295 unsigned get() const { return Flags; } 8296 }; 8297 8298 } // end anonymous namespace 8299 8300 /// visitInlineAsm - Handle a call to an InlineAsm object. 8301 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8302 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8303 8304 /// ConstraintOperands - Information about all of the constraints. 8305 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8306 8307 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8308 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8309 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8310 8311 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8312 // AsmDialect, MayLoad, MayStore). 8313 bool HasSideEffect = IA->hasSideEffects(); 8314 ExtraFlags ExtraInfo(Call); 8315 8316 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8317 unsigned ResNo = 0; // ResNo - The result number of the next output. 8318 unsigned NumMatchingOps = 0; 8319 for (auto &T : TargetConstraints) { 8320 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8321 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8322 8323 // Compute the value type for each operand. 8324 if (OpInfo.Type == InlineAsm::isInput || 8325 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8326 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8327 8328 // Process the call argument. BasicBlocks are labels, currently appearing 8329 // only in asm's. 8330 if (isa<CallBrInst>(Call) && 8331 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8332 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8333 NumMatchingOps) && 8334 (NumMatchingOps == 0 || 8335 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8336 NumMatchingOps))) { 8337 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8338 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8339 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8340 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8341 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8342 } else { 8343 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8344 } 8345 8346 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8347 DAG.getDataLayout()); 8348 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8349 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8350 // The return value of the call is this value. As such, there is no 8351 // corresponding argument. 8352 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8353 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8354 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8355 DAG.getDataLayout(), STy->getElementType(ResNo)); 8356 } else { 8357 assert(ResNo == 0 && "Asm only has one result!"); 8358 OpInfo.ConstraintVT = 8359 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8360 } 8361 ++ResNo; 8362 } else { 8363 OpInfo.ConstraintVT = MVT::Other; 8364 } 8365 8366 if (OpInfo.hasMatchingInput()) 8367 ++NumMatchingOps; 8368 8369 if (!HasSideEffect) 8370 HasSideEffect = OpInfo.hasMemory(TLI); 8371 8372 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8373 // FIXME: Could we compute this on OpInfo rather than T? 8374 8375 // Compute the constraint code and ConstraintType to use. 8376 TLI.ComputeConstraintToUse(T, SDValue()); 8377 8378 if (T.ConstraintType == TargetLowering::C_Immediate && 8379 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8380 // We've delayed emitting a diagnostic like the "n" constraint because 8381 // inlining could cause an integer showing up. 8382 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8383 "' expects an integer constant " 8384 "expression"); 8385 8386 ExtraInfo.update(T); 8387 } 8388 8389 8390 // We won't need to flush pending loads if this asm doesn't touch 8391 // memory and is nonvolatile. 8392 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8393 8394 bool IsCallBr = isa<CallBrInst>(Call); 8395 if (IsCallBr) { 8396 // If this is a callbr we need to flush pending exports since inlineasm_br 8397 // is a terminator. We need to do this before nodes are glued to 8398 // the inlineasm_br node. 8399 Chain = getControlRoot(); 8400 } 8401 8402 // Second pass over the constraints: compute which constraint option to use. 8403 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8404 // If this is an output operand with a matching input operand, look up the 8405 // matching input. If their types mismatch, e.g. one is an integer, the 8406 // other is floating point, or their sizes are different, flag it as an 8407 // error. 8408 if (OpInfo.hasMatchingInput()) { 8409 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8410 patchMatchingInput(OpInfo, Input, DAG); 8411 } 8412 8413 // Compute the constraint code and ConstraintType to use. 8414 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8415 8416 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8417 OpInfo.Type == InlineAsm::isClobber) 8418 continue; 8419 8420 // If this is a memory input, and if the operand is not indirect, do what we 8421 // need to provide an address for the memory input. 8422 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8423 !OpInfo.isIndirect) { 8424 assert((OpInfo.isMultipleAlternative || 8425 (OpInfo.Type == InlineAsm::isInput)) && 8426 "Can only indirectify direct input operands!"); 8427 8428 // Memory operands really want the address of the value. 8429 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8430 8431 // There is no longer a Value* corresponding to this operand. 8432 OpInfo.CallOperandVal = nullptr; 8433 8434 // It is now an indirect operand. 8435 OpInfo.isIndirect = true; 8436 } 8437 8438 } 8439 8440 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8441 std::vector<SDValue> AsmNodeOperands; 8442 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8443 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8444 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8445 8446 // If we have a !srcloc metadata node associated with it, we want to attach 8447 // this to the ultimately generated inline asm machineinstr. To do this, we 8448 // pass in the third operand as this (potentially null) inline asm MDNode. 8449 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8450 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8451 8452 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8453 // bits as operand 3. 8454 AsmNodeOperands.push_back(DAG.getTargetConstant( 8455 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8456 8457 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8458 // this, assign virtual and physical registers for inputs and otput. 8459 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8460 // Assign Registers. 8461 SDISelAsmOperandInfo &RefOpInfo = 8462 OpInfo.isMatchingInputConstraint() 8463 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8464 : OpInfo; 8465 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8466 8467 auto DetectWriteToReservedRegister = [&]() { 8468 const MachineFunction &MF = DAG.getMachineFunction(); 8469 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8470 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8471 if (Register::isPhysicalRegister(Reg) && 8472 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8473 const char *RegName = TRI.getName(Reg); 8474 emitInlineAsmError(Call, "write to reserved register '" + 8475 Twine(RegName) + "'"); 8476 return true; 8477 } 8478 } 8479 return false; 8480 }; 8481 8482 switch (OpInfo.Type) { 8483 case InlineAsm::isOutput: 8484 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8485 unsigned ConstraintID = 8486 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8487 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8488 "Failed to convert memory constraint code to constraint id."); 8489 8490 // Add information to the INLINEASM node to know about this output. 8491 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8492 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8493 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8494 MVT::i32)); 8495 AsmNodeOperands.push_back(OpInfo.CallOperand); 8496 } else { 8497 // Otherwise, this outputs to a register (directly for C_Register / 8498 // C_RegisterClass, and a target-defined fashion for 8499 // C_Immediate/C_Other). Find a register that we can use. 8500 if (OpInfo.AssignedRegs.Regs.empty()) { 8501 emitInlineAsmError( 8502 Call, "couldn't allocate output register for constraint '" + 8503 Twine(OpInfo.ConstraintCode) + "'"); 8504 return; 8505 } 8506 8507 if (DetectWriteToReservedRegister()) 8508 return; 8509 8510 // Add information to the INLINEASM node to know that this register is 8511 // set. 8512 OpInfo.AssignedRegs.AddInlineAsmOperands( 8513 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8514 : InlineAsm::Kind_RegDef, 8515 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8516 } 8517 break; 8518 8519 case InlineAsm::isInput: { 8520 SDValue InOperandVal = OpInfo.CallOperand; 8521 8522 if (OpInfo.isMatchingInputConstraint()) { 8523 // If this is required to match an output register we have already set, 8524 // just use its register. 8525 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8526 AsmNodeOperands); 8527 unsigned OpFlag = 8528 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8529 if (InlineAsm::isRegDefKind(OpFlag) || 8530 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8531 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8532 if (OpInfo.isIndirect) { 8533 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8534 emitInlineAsmError(Call, "inline asm not supported yet: " 8535 "don't know how to handle tied " 8536 "indirect register inputs"); 8537 return; 8538 } 8539 8540 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8541 SmallVector<unsigned, 4> Regs; 8542 8543 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8544 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8545 MachineRegisterInfo &RegInfo = 8546 DAG.getMachineFunction().getRegInfo(); 8547 for (unsigned i = 0; i != NumRegs; ++i) 8548 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8549 } else { 8550 emitInlineAsmError(Call, 8551 "inline asm error: This value type register " 8552 "class is not natively supported!"); 8553 return; 8554 } 8555 8556 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8557 8558 SDLoc dl = getCurSDLoc(); 8559 // Use the produced MatchedRegs object to 8560 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8561 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8562 true, OpInfo.getMatchedOperand(), dl, 8563 DAG, AsmNodeOperands); 8564 break; 8565 } 8566 8567 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8568 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8569 "Unexpected number of operands"); 8570 // Add information to the INLINEASM node to know about this input. 8571 // See InlineAsm.h isUseOperandTiedToDef. 8572 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8573 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8574 OpInfo.getMatchedOperand()); 8575 AsmNodeOperands.push_back(DAG.getTargetConstant( 8576 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8577 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8578 break; 8579 } 8580 8581 // Treat indirect 'X' constraint as memory. 8582 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8583 OpInfo.isIndirect) 8584 OpInfo.ConstraintType = TargetLowering::C_Memory; 8585 8586 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8587 OpInfo.ConstraintType == TargetLowering::C_Other) { 8588 std::vector<SDValue> Ops; 8589 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8590 Ops, DAG); 8591 if (Ops.empty()) { 8592 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8593 if (isa<ConstantSDNode>(InOperandVal)) { 8594 emitInlineAsmError(Call, "value out of range for constraint '" + 8595 Twine(OpInfo.ConstraintCode) + "'"); 8596 return; 8597 } 8598 8599 emitInlineAsmError(Call, 8600 "invalid operand for inline asm constraint '" + 8601 Twine(OpInfo.ConstraintCode) + "'"); 8602 return; 8603 } 8604 8605 // Add information to the INLINEASM node to know about this input. 8606 unsigned ResOpType = 8607 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8608 AsmNodeOperands.push_back(DAG.getTargetConstant( 8609 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8610 llvm::append_range(AsmNodeOperands, Ops); 8611 break; 8612 } 8613 8614 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8615 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8616 assert(InOperandVal.getValueType() == 8617 TLI.getPointerTy(DAG.getDataLayout()) && 8618 "Memory operands expect pointer values"); 8619 8620 unsigned ConstraintID = 8621 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8622 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8623 "Failed to convert memory constraint code to constraint id."); 8624 8625 // Add information to the INLINEASM node to know about this input. 8626 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8627 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8628 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8629 getCurSDLoc(), 8630 MVT::i32)); 8631 AsmNodeOperands.push_back(InOperandVal); 8632 break; 8633 } 8634 8635 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8636 OpInfo.ConstraintType == TargetLowering::C_Register) && 8637 "Unknown constraint type!"); 8638 8639 // TODO: Support this. 8640 if (OpInfo.isIndirect) { 8641 emitInlineAsmError( 8642 Call, "Don't know how to handle indirect register inputs yet " 8643 "for constraint '" + 8644 Twine(OpInfo.ConstraintCode) + "'"); 8645 return; 8646 } 8647 8648 // Copy the input into the appropriate registers. 8649 if (OpInfo.AssignedRegs.Regs.empty()) { 8650 emitInlineAsmError(Call, 8651 "couldn't allocate input reg for constraint '" + 8652 Twine(OpInfo.ConstraintCode) + "'"); 8653 return; 8654 } 8655 8656 if (DetectWriteToReservedRegister()) 8657 return; 8658 8659 SDLoc dl = getCurSDLoc(); 8660 8661 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8662 &Call); 8663 8664 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8665 dl, DAG, AsmNodeOperands); 8666 break; 8667 } 8668 case InlineAsm::isClobber: 8669 // Add the clobbered value to the operand list, so that the register 8670 // allocator is aware that the physreg got clobbered. 8671 if (!OpInfo.AssignedRegs.Regs.empty()) 8672 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8673 false, 0, getCurSDLoc(), DAG, 8674 AsmNodeOperands); 8675 break; 8676 } 8677 } 8678 8679 // Finish up input operands. Set the input chain and add the flag last. 8680 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8681 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8682 8683 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8684 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8685 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8686 Flag = Chain.getValue(1); 8687 8688 // Do additional work to generate outputs. 8689 8690 SmallVector<EVT, 1> ResultVTs; 8691 SmallVector<SDValue, 1> ResultValues; 8692 SmallVector<SDValue, 8> OutChains; 8693 8694 llvm::Type *CallResultType = Call.getType(); 8695 ArrayRef<Type *> ResultTypes; 8696 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8697 ResultTypes = StructResult->elements(); 8698 else if (!CallResultType->isVoidTy()) 8699 ResultTypes = makeArrayRef(CallResultType); 8700 8701 auto CurResultType = ResultTypes.begin(); 8702 auto handleRegAssign = [&](SDValue V) { 8703 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8704 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8705 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8706 ++CurResultType; 8707 // If the type of the inline asm call site return value is different but has 8708 // same size as the type of the asm output bitcast it. One example of this 8709 // is for vectors with different width / number of elements. This can 8710 // happen for register classes that can contain multiple different value 8711 // types. The preg or vreg allocated may not have the same VT as was 8712 // expected. 8713 // 8714 // This can also happen for a return value that disagrees with the register 8715 // class it is put in, eg. a double in a general-purpose register on a 8716 // 32-bit machine. 8717 if (ResultVT != V.getValueType() && 8718 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8719 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8720 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8721 V.getValueType().isInteger()) { 8722 // If a result value was tied to an input value, the computed result 8723 // may have a wider width than the expected result. Extract the 8724 // relevant portion. 8725 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8726 } 8727 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8728 ResultVTs.push_back(ResultVT); 8729 ResultValues.push_back(V); 8730 }; 8731 8732 // Deal with output operands. 8733 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8734 if (OpInfo.Type == InlineAsm::isOutput) { 8735 SDValue Val; 8736 // Skip trivial output operands. 8737 if (OpInfo.AssignedRegs.Regs.empty()) 8738 continue; 8739 8740 switch (OpInfo.ConstraintType) { 8741 case TargetLowering::C_Register: 8742 case TargetLowering::C_RegisterClass: 8743 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8744 Chain, &Flag, &Call); 8745 break; 8746 case TargetLowering::C_Immediate: 8747 case TargetLowering::C_Other: 8748 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8749 OpInfo, DAG); 8750 break; 8751 case TargetLowering::C_Memory: 8752 break; // Already handled. 8753 case TargetLowering::C_Unknown: 8754 assert(false && "Unexpected unknown constraint"); 8755 } 8756 8757 // Indirect output manifest as stores. Record output chains. 8758 if (OpInfo.isIndirect) { 8759 const Value *Ptr = OpInfo.CallOperandVal; 8760 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8761 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8762 MachinePointerInfo(Ptr)); 8763 OutChains.push_back(Store); 8764 } else { 8765 // generate CopyFromRegs to associated registers. 8766 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8767 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8768 for (const SDValue &V : Val->op_values()) 8769 handleRegAssign(V); 8770 } else 8771 handleRegAssign(Val); 8772 } 8773 } 8774 } 8775 8776 // Set results. 8777 if (!ResultValues.empty()) { 8778 assert(CurResultType == ResultTypes.end() && 8779 "Mismatch in number of ResultTypes"); 8780 assert(ResultValues.size() == ResultTypes.size() && 8781 "Mismatch in number of output operands in asm result"); 8782 8783 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8784 DAG.getVTList(ResultVTs), ResultValues); 8785 setValue(&Call, V); 8786 } 8787 8788 // Collect store chains. 8789 if (!OutChains.empty()) 8790 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8791 8792 // Only Update Root if inline assembly has a memory effect. 8793 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8794 DAG.setRoot(Chain); 8795 } 8796 8797 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8798 const Twine &Message) { 8799 LLVMContext &Ctx = *DAG.getContext(); 8800 Ctx.emitError(&Call, Message); 8801 8802 // Make sure we leave the DAG in a valid state 8803 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8804 SmallVector<EVT, 1> ValueVTs; 8805 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8806 8807 if (ValueVTs.empty()) 8808 return; 8809 8810 SmallVector<SDValue, 1> Ops; 8811 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8812 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8813 8814 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8815 } 8816 8817 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8818 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8819 MVT::Other, getRoot(), 8820 getValue(I.getArgOperand(0)), 8821 DAG.getSrcValue(I.getArgOperand(0)))); 8822 } 8823 8824 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8825 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8826 const DataLayout &DL = DAG.getDataLayout(); 8827 SDValue V = DAG.getVAArg( 8828 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8829 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8830 DL.getABITypeAlign(I.getType()).value()); 8831 DAG.setRoot(V.getValue(1)); 8832 8833 if (I.getType()->isPointerTy()) 8834 V = DAG.getPtrExtOrTrunc( 8835 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8836 setValue(&I, V); 8837 } 8838 8839 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8840 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8841 MVT::Other, getRoot(), 8842 getValue(I.getArgOperand(0)), 8843 DAG.getSrcValue(I.getArgOperand(0)))); 8844 } 8845 8846 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8847 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8848 MVT::Other, getRoot(), 8849 getValue(I.getArgOperand(0)), 8850 getValue(I.getArgOperand(1)), 8851 DAG.getSrcValue(I.getArgOperand(0)), 8852 DAG.getSrcValue(I.getArgOperand(1)))); 8853 } 8854 8855 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8856 const Instruction &I, 8857 SDValue Op) { 8858 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8859 if (!Range) 8860 return Op; 8861 8862 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8863 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8864 return Op; 8865 8866 APInt Lo = CR.getUnsignedMin(); 8867 if (!Lo.isMinValue()) 8868 return Op; 8869 8870 APInt Hi = CR.getUnsignedMax(); 8871 unsigned Bits = std::max(Hi.getActiveBits(), 8872 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8873 8874 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8875 8876 SDLoc SL = getCurSDLoc(); 8877 8878 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8879 DAG.getValueType(SmallVT)); 8880 unsigned NumVals = Op.getNode()->getNumValues(); 8881 if (NumVals == 1) 8882 return ZExt; 8883 8884 SmallVector<SDValue, 4> Ops; 8885 8886 Ops.push_back(ZExt); 8887 for (unsigned I = 1; I != NumVals; ++I) 8888 Ops.push_back(Op.getValue(I)); 8889 8890 return DAG.getMergeValues(Ops, SL); 8891 } 8892 8893 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8894 /// the call being lowered. 8895 /// 8896 /// This is a helper for lowering intrinsics that follow a target calling 8897 /// convention or require stack pointer adjustment. Only a subset of the 8898 /// intrinsic's operands need to participate in the calling convention. 8899 void SelectionDAGBuilder::populateCallLoweringInfo( 8900 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8901 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8902 bool IsPatchPoint) { 8903 TargetLowering::ArgListTy Args; 8904 Args.reserve(NumArgs); 8905 8906 // Populate the argument list. 8907 // Attributes for args start at offset 1, after the return attribute. 8908 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8909 ArgI != ArgE; ++ArgI) { 8910 const Value *V = Call->getOperand(ArgI); 8911 8912 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8913 8914 TargetLowering::ArgListEntry Entry; 8915 Entry.Node = getValue(V); 8916 Entry.Ty = V->getType(); 8917 Entry.setAttributes(Call, ArgI); 8918 Args.push_back(Entry); 8919 } 8920 8921 CLI.setDebugLoc(getCurSDLoc()) 8922 .setChain(getRoot()) 8923 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8924 .setDiscardResult(Call->use_empty()) 8925 .setIsPatchPoint(IsPatchPoint) 8926 .setIsPreallocated( 8927 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8928 } 8929 8930 /// Add a stack map intrinsic call's live variable operands to a stackmap 8931 /// or patchpoint target node's operand list. 8932 /// 8933 /// Constants are converted to TargetConstants purely as an optimization to 8934 /// avoid constant materialization and register allocation. 8935 /// 8936 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8937 /// generate addess computation nodes, and so FinalizeISel can convert the 8938 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8939 /// address materialization and register allocation, but may also be required 8940 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8941 /// alloca in the entry block, then the runtime may assume that the alloca's 8942 /// StackMap location can be read immediately after compilation and that the 8943 /// location is valid at any point during execution (this is similar to the 8944 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8945 /// only available in a register, then the runtime would need to trap when 8946 /// execution reaches the StackMap in order to read the alloca's location. 8947 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8948 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8949 SelectionDAGBuilder &Builder) { 8950 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8951 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8952 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8953 Ops.push_back( 8954 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8955 Ops.push_back( 8956 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8957 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8958 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8959 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8960 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8961 } else 8962 Ops.push_back(OpVal); 8963 } 8964 } 8965 8966 /// Lower llvm.experimental.stackmap directly to its target opcode. 8967 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8968 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8969 // [live variables...]) 8970 8971 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8972 8973 SDValue Chain, InFlag, Callee, NullPtr; 8974 SmallVector<SDValue, 32> Ops; 8975 8976 SDLoc DL = getCurSDLoc(); 8977 Callee = getValue(CI.getCalledOperand()); 8978 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8979 8980 // The stackmap intrinsic only records the live variables (the arguments 8981 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8982 // intrinsic, this won't be lowered to a function call. This means we don't 8983 // have to worry about calling conventions and target specific lowering code. 8984 // Instead we perform the call lowering right here. 8985 // 8986 // chain, flag = CALLSEQ_START(chain, 0, 0) 8987 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8988 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8989 // 8990 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8991 InFlag = Chain.getValue(1); 8992 8993 // Add the <id> and <numBytes> constants. 8994 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8995 Ops.push_back(DAG.getTargetConstant( 8996 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8997 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8998 Ops.push_back(DAG.getTargetConstant( 8999 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9000 MVT::i32)); 9001 9002 // Push live variables for the stack map. 9003 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9004 9005 // We are not pushing any register mask info here on the operands list, 9006 // because the stackmap doesn't clobber anything. 9007 9008 // Push the chain and the glue flag. 9009 Ops.push_back(Chain); 9010 Ops.push_back(InFlag); 9011 9012 // Create the STACKMAP node. 9013 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9014 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9015 Chain = SDValue(SM, 0); 9016 InFlag = Chain.getValue(1); 9017 9018 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9019 9020 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9021 9022 // Set the root to the target-lowered call chain. 9023 DAG.setRoot(Chain); 9024 9025 // Inform the Frame Information that we have a stackmap in this function. 9026 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9027 } 9028 9029 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9030 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9031 const BasicBlock *EHPadBB) { 9032 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9033 // i32 <numBytes>, 9034 // i8* <target>, 9035 // i32 <numArgs>, 9036 // [Args...], 9037 // [live variables...]) 9038 9039 CallingConv::ID CC = CB.getCallingConv(); 9040 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9041 bool HasDef = !CB.getType()->isVoidTy(); 9042 SDLoc dl = getCurSDLoc(); 9043 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9044 9045 // Handle immediate and symbolic callees. 9046 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9047 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9048 /*isTarget=*/true); 9049 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9050 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9051 SDLoc(SymbolicCallee), 9052 SymbolicCallee->getValueType(0)); 9053 9054 // Get the real number of arguments participating in the call <numArgs> 9055 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9056 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9057 9058 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9059 // Intrinsics include all meta-operands up to but not including CC. 9060 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9061 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9062 "Not enough arguments provided to the patchpoint intrinsic"); 9063 9064 // For AnyRegCC the arguments are lowered later on manually. 9065 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9066 Type *ReturnTy = 9067 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9068 9069 TargetLowering::CallLoweringInfo CLI(DAG); 9070 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9071 ReturnTy, true); 9072 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9073 9074 SDNode *CallEnd = Result.second.getNode(); 9075 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9076 CallEnd = CallEnd->getOperand(0).getNode(); 9077 9078 /// Get a call instruction from the call sequence chain. 9079 /// Tail calls are not allowed. 9080 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9081 "Expected a callseq node."); 9082 SDNode *Call = CallEnd->getOperand(0).getNode(); 9083 bool HasGlue = Call->getGluedNode(); 9084 9085 // Replace the target specific call node with the patchable intrinsic. 9086 SmallVector<SDValue, 8> Ops; 9087 9088 // Add the <id> and <numBytes> constants. 9089 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9090 Ops.push_back(DAG.getTargetConstant( 9091 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9092 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9093 Ops.push_back(DAG.getTargetConstant( 9094 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9095 MVT::i32)); 9096 9097 // Add the callee. 9098 Ops.push_back(Callee); 9099 9100 // Adjust <numArgs> to account for any arguments that have been passed on the 9101 // stack instead. 9102 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9103 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9104 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9105 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9106 9107 // Add the calling convention 9108 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9109 9110 // Add the arguments we omitted previously. The register allocator should 9111 // place these in any free register. 9112 if (IsAnyRegCC) 9113 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9114 Ops.push_back(getValue(CB.getArgOperand(i))); 9115 9116 // Push the arguments from the call instruction up to the register mask. 9117 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9118 Ops.append(Call->op_begin() + 2, e); 9119 9120 // Push live variables for the stack map. 9121 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9122 9123 // Push the register mask info. 9124 if (HasGlue) 9125 Ops.push_back(*(Call->op_end()-2)); 9126 else 9127 Ops.push_back(*(Call->op_end()-1)); 9128 9129 // Push the chain (this is originally the first operand of the call, but 9130 // becomes now the last or second to last operand). 9131 Ops.push_back(*(Call->op_begin())); 9132 9133 // Push the glue flag (last operand). 9134 if (HasGlue) 9135 Ops.push_back(*(Call->op_end()-1)); 9136 9137 SDVTList NodeTys; 9138 if (IsAnyRegCC && HasDef) { 9139 // Create the return types based on the intrinsic definition 9140 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9141 SmallVector<EVT, 3> ValueVTs; 9142 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9143 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9144 9145 // There is always a chain and a glue type at the end 9146 ValueVTs.push_back(MVT::Other); 9147 ValueVTs.push_back(MVT::Glue); 9148 NodeTys = DAG.getVTList(ValueVTs); 9149 } else 9150 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9151 9152 // Replace the target specific call node with a PATCHPOINT node. 9153 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9154 dl, NodeTys, Ops); 9155 9156 // Update the NodeMap. 9157 if (HasDef) { 9158 if (IsAnyRegCC) 9159 setValue(&CB, SDValue(MN, 0)); 9160 else 9161 setValue(&CB, Result.first); 9162 } 9163 9164 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9165 // call sequence. Furthermore the location of the chain and glue can change 9166 // when the AnyReg calling convention is used and the intrinsic returns a 9167 // value. 9168 if (IsAnyRegCC && HasDef) { 9169 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9170 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9171 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9172 } else 9173 DAG.ReplaceAllUsesWith(Call, MN); 9174 DAG.DeleteNode(Call); 9175 9176 // Inform the Frame Information that we have a patchpoint in this function. 9177 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9178 } 9179 9180 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9181 unsigned Intrinsic) { 9182 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9183 SDValue Op1 = getValue(I.getArgOperand(0)); 9184 SDValue Op2; 9185 if (I.getNumArgOperands() > 1) 9186 Op2 = getValue(I.getArgOperand(1)); 9187 SDLoc dl = getCurSDLoc(); 9188 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9189 SDValue Res; 9190 SDNodeFlags SDFlags; 9191 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9192 SDFlags.copyFMF(*FPMO); 9193 9194 switch (Intrinsic) { 9195 case Intrinsic::vector_reduce_fadd: 9196 if (SDFlags.hasAllowReassociation()) 9197 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9198 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9199 SDFlags); 9200 else 9201 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9202 break; 9203 case Intrinsic::vector_reduce_fmul: 9204 if (SDFlags.hasAllowReassociation()) 9205 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9206 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9207 SDFlags); 9208 else 9209 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9210 break; 9211 case Intrinsic::vector_reduce_add: 9212 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9213 break; 9214 case Intrinsic::vector_reduce_mul: 9215 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9216 break; 9217 case Intrinsic::vector_reduce_and: 9218 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9219 break; 9220 case Intrinsic::vector_reduce_or: 9221 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9222 break; 9223 case Intrinsic::vector_reduce_xor: 9224 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9225 break; 9226 case Intrinsic::vector_reduce_smax: 9227 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9228 break; 9229 case Intrinsic::vector_reduce_smin: 9230 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9231 break; 9232 case Intrinsic::vector_reduce_umax: 9233 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9234 break; 9235 case Intrinsic::vector_reduce_umin: 9236 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9237 break; 9238 case Intrinsic::vector_reduce_fmax: 9239 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9240 break; 9241 case Intrinsic::vector_reduce_fmin: 9242 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9243 break; 9244 default: 9245 llvm_unreachable("Unhandled vector reduce intrinsic"); 9246 } 9247 setValue(&I, Res); 9248 } 9249 9250 /// Returns an AttributeList representing the attributes applied to the return 9251 /// value of the given call. 9252 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9253 SmallVector<Attribute::AttrKind, 2> Attrs; 9254 if (CLI.RetSExt) 9255 Attrs.push_back(Attribute::SExt); 9256 if (CLI.RetZExt) 9257 Attrs.push_back(Attribute::ZExt); 9258 if (CLI.IsInReg) 9259 Attrs.push_back(Attribute::InReg); 9260 9261 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9262 Attrs); 9263 } 9264 9265 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9266 /// implementation, which just calls LowerCall. 9267 /// FIXME: When all targets are 9268 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9269 std::pair<SDValue, SDValue> 9270 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9271 // Handle the incoming return values from the call. 9272 CLI.Ins.clear(); 9273 Type *OrigRetTy = CLI.RetTy; 9274 SmallVector<EVT, 4> RetTys; 9275 SmallVector<uint64_t, 4> Offsets; 9276 auto &DL = CLI.DAG.getDataLayout(); 9277 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9278 9279 if (CLI.IsPostTypeLegalization) { 9280 // If we are lowering a libcall after legalization, split the return type. 9281 SmallVector<EVT, 4> OldRetTys; 9282 SmallVector<uint64_t, 4> OldOffsets; 9283 RetTys.swap(OldRetTys); 9284 Offsets.swap(OldOffsets); 9285 9286 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9287 EVT RetVT = OldRetTys[i]; 9288 uint64_t Offset = OldOffsets[i]; 9289 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9290 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9291 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9292 RetTys.append(NumRegs, RegisterVT); 9293 for (unsigned j = 0; j != NumRegs; ++j) 9294 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9295 } 9296 } 9297 9298 SmallVector<ISD::OutputArg, 4> Outs; 9299 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9300 9301 bool CanLowerReturn = 9302 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9303 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9304 9305 SDValue DemoteStackSlot; 9306 int DemoteStackIdx = -100; 9307 if (!CanLowerReturn) { 9308 // FIXME: equivalent assert? 9309 // assert(!CS.hasInAllocaArgument() && 9310 // "sret demotion is incompatible with inalloca"); 9311 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9312 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9313 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9314 DemoteStackIdx = 9315 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9316 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9317 DL.getAllocaAddrSpace()); 9318 9319 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9320 ArgListEntry Entry; 9321 Entry.Node = DemoteStackSlot; 9322 Entry.Ty = StackSlotPtrType; 9323 Entry.IsSExt = false; 9324 Entry.IsZExt = false; 9325 Entry.IsInReg = false; 9326 Entry.IsSRet = true; 9327 Entry.IsNest = false; 9328 Entry.IsByVal = false; 9329 Entry.IsByRef = false; 9330 Entry.IsReturned = false; 9331 Entry.IsSwiftSelf = false; 9332 Entry.IsSwiftError = false; 9333 Entry.IsCFGuardTarget = false; 9334 Entry.Alignment = Alignment; 9335 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9336 CLI.NumFixedArgs += 1; 9337 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9338 9339 // sret demotion isn't compatible with tail-calls, since the sret argument 9340 // points into the callers stack frame. 9341 CLI.IsTailCall = false; 9342 } else { 9343 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9344 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9345 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9346 ISD::ArgFlagsTy Flags; 9347 if (NeedsRegBlock) { 9348 Flags.setInConsecutiveRegs(); 9349 if (I == RetTys.size() - 1) 9350 Flags.setInConsecutiveRegsLast(); 9351 } 9352 EVT VT = RetTys[I]; 9353 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9354 CLI.CallConv, VT); 9355 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9356 CLI.CallConv, VT); 9357 for (unsigned i = 0; i != NumRegs; ++i) { 9358 ISD::InputArg MyFlags; 9359 MyFlags.Flags = Flags; 9360 MyFlags.VT = RegisterVT; 9361 MyFlags.ArgVT = VT; 9362 MyFlags.Used = CLI.IsReturnValueUsed; 9363 if (CLI.RetTy->isPointerTy()) { 9364 MyFlags.Flags.setPointer(); 9365 MyFlags.Flags.setPointerAddrSpace( 9366 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9367 } 9368 if (CLI.RetSExt) 9369 MyFlags.Flags.setSExt(); 9370 if (CLI.RetZExt) 9371 MyFlags.Flags.setZExt(); 9372 if (CLI.IsInReg) 9373 MyFlags.Flags.setInReg(); 9374 CLI.Ins.push_back(MyFlags); 9375 } 9376 } 9377 } 9378 9379 // We push in swifterror return as the last element of CLI.Ins. 9380 ArgListTy &Args = CLI.getArgs(); 9381 if (supportSwiftError()) { 9382 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9383 if (Args[i].IsSwiftError) { 9384 ISD::InputArg MyFlags; 9385 MyFlags.VT = getPointerTy(DL); 9386 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9387 MyFlags.Flags.setSwiftError(); 9388 CLI.Ins.push_back(MyFlags); 9389 } 9390 } 9391 } 9392 9393 // Handle all of the outgoing arguments. 9394 CLI.Outs.clear(); 9395 CLI.OutVals.clear(); 9396 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9397 SmallVector<EVT, 4> ValueVTs; 9398 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9399 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9400 Type *FinalType = Args[i].Ty; 9401 if (Args[i].IsByVal) 9402 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9403 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9404 FinalType, CLI.CallConv, CLI.IsVarArg); 9405 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9406 ++Value) { 9407 EVT VT = ValueVTs[Value]; 9408 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9409 SDValue Op = SDValue(Args[i].Node.getNode(), 9410 Args[i].Node.getResNo() + Value); 9411 ISD::ArgFlagsTy Flags; 9412 9413 // Certain targets (such as MIPS), may have a different ABI alignment 9414 // for a type depending on the context. Give the target a chance to 9415 // specify the alignment it wants. 9416 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9417 9418 if (Args[i].Ty->isPointerTy()) { 9419 Flags.setPointer(); 9420 Flags.setPointerAddrSpace( 9421 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9422 } 9423 if (Args[i].IsZExt) 9424 Flags.setZExt(); 9425 if (Args[i].IsSExt) 9426 Flags.setSExt(); 9427 if (Args[i].IsInReg) { 9428 // If we are using vectorcall calling convention, a structure that is 9429 // passed InReg - is surely an HVA 9430 if (CLI.CallConv == CallingConv::X86_VectorCall && 9431 isa<StructType>(FinalType)) { 9432 // The first value of a structure is marked 9433 if (0 == Value) 9434 Flags.setHvaStart(); 9435 Flags.setHva(); 9436 } 9437 // Set InReg Flag 9438 Flags.setInReg(); 9439 } 9440 if (Args[i].IsSRet) 9441 Flags.setSRet(); 9442 if (Args[i].IsSwiftSelf) 9443 Flags.setSwiftSelf(); 9444 if (Args[i].IsSwiftError) 9445 Flags.setSwiftError(); 9446 if (Args[i].IsCFGuardTarget) 9447 Flags.setCFGuardTarget(); 9448 if (Args[i].IsByVal) 9449 Flags.setByVal(); 9450 if (Args[i].IsByRef) 9451 Flags.setByRef(); 9452 if (Args[i].IsPreallocated) { 9453 Flags.setPreallocated(); 9454 // Set the byval flag for CCAssignFn callbacks that don't know about 9455 // preallocated. This way we can know how many bytes we should've 9456 // allocated and how many bytes a callee cleanup function will pop. If 9457 // we port preallocated to more targets, we'll have to add custom 9458 // preallocated handling in the various CC lowering callbacks. 9459 Flags.setByVal(); 9460 } 9461 if (Args[i].IsInAlloca) { 9462 Flags.setInAlloca(); 9463 // Set the byval flag for CCAssignFn callbacks that don't know about 9464 // inalloca. This way we can know how many bytes we should've allocated 9465 // and how many bytes a callee cleanup function will pop. If we port 9466 // inalloca to more targets, we'll have to add custom inalloca handling 9467 // in the various CC lowering callbacks. 9468 Flags.setByVal(); 9469 } 9470 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9471 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9472 Type *ElementTy = Ty->getElementType(); 9473 9474 unsigned FrameSize = DL.getTypeAllocSize( 9475 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9476 Flags.setByValSize(FrameSize); 9477 9478 // info is not there but there are cases it cannot get right. 9479 Align FrameAlign; 9480 if (auto MA = Args[i].Alignment) 9481 FrameAlign = *MA; 9482 else 9483 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9484 Flags.setByValAlign(FrameAlign); 9485 } 9486 if (Args[i].IsNest) 9487 Flags.setNest(); 9488 if (NeedsRegBlock) 9489 Flags.setInConsecutiveRegs(); 9490 Flags.setOrigAlign(OriginalAlignment); 9491 9492 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9493 CLI.CallConv, VT); 9494 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9495 CLI.CallConv, VT); 9496 SmallVector<SDValue, 4> Parts(NumParts); 9497 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9498 9499 if (Args[i].IsSExt) 9500 ExtendKind = ISD::SIGN_EXTEND; 9501 else if (Args[i].IsZExt) 9502 ExtendKind = ISD::ZERO_EXTEND; 9503 9504 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9505 // for now. 9506 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9507 CanLowerReturn) { 9508 assert((CLI.RetTy == Args[i].Ty || 9509 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9510 CLI.RetTy->getPointerAddressSpace() == 9511 Args[i].Ty->getPointerAddressSpace())) && 9512 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9513 // Before passing 'returned' to the target lowering code, ensure that 9514 // either the register MVT and the actual EVT are the same size or that 9515 // the return value and argument are extended in the same way; in these 9516 // cases it's safe to pass the argument register value unchanged as the 9517 // return register value (although it's at the target's option whether 9518 // to do so) 9519 // TODO: allow code generation to take advantage of partially preserved 9520 // registers rather than clobbering the entire register when the 9521 // parameter extension method is not compatible with the return 9522 // extension method 9523 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9524 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9525 CLI.RetZExt == Args[i].IsZExt)) 9526 Flags.setReturned(); 9527 } 9528 9529 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9530 CLI.CallConv, ExtendKind); 9531 9532 for (unsigned j = 0; j != NumParts; ++j) { 9533 // if it isn't first piece, alignment must be 1 9534 // For scalable vectors the scalable part is currently handled 9535 // by individual targets, so we just use the known minimum size here. 9536 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9537 i < CLI.NumFixedArgs, i, 9538 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9539 if (NumParts > 1 && j == 0) 9540 MyFlags.Flags.setSplit(); 9541 else if (j != 0) { 9542 MyFlags.Flags.setOrigAlign(Align(1)); 9543 if (j == NumParts - 1) 9544 MyFlags.Flags.setSplitEnd(); 9545 } 9546 9547 CLI.Outs.push_back(MyFlags); 9548 CLI.OutVals.push_back(Parts[j]); 9549 } 9550 9551 if (NeedsRegBlock && Value == NumValues - 1) 9552 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9553 } 9554 } 9555 9556 SmallVector<SDValue, 4> InVals; 9557 CLI.Chain = LowerCall(CLI, InVals); 9558 9559 // Update CLI.InVals to use outside of this function. 9560 CLI.InVals = InVals; 9561 9562 // Verify that the target's LowerCall behaved as expected. 9563 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9564 "LowerCall didn't return a valid chain!"); 9565 assert((!CLI.IsTailCall || InVals.empty()) && 9566 "LowerCall emitted a return value for a tail call!"); 9567 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9568 "LowerCall didn't emit the correct number of values!"); 9569 9570 // For a tail call, the return value is merely live-out and there aren't 9571 // any nodes in the DAG representing it. Return a special value to 9572 // indicate that a tail call has been emitted and no more Instructions 9573 // should be processed in the current block. 9574 if (CLI.IsTailCall) { 9575 CLI.DAG.setRoot(CLI.Chain); 9576 return std::make_pair(SDValue(), SDValue()); 9577 } 9578 9579 #ifndef NDEBUG 9580 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9581 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9582 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9583 "LowerCall emitted a value with the wrong type!"); 9584 } 9585 #endif 9586 9587 SmallVector<SDValue, 4> ReturnValues; 9588 if (!CanLowerReturn) { 9589 // The instruction result is the result of loading from the 9590 // hidden sret parameter. 9591 SmallVector<EVT, 1> PVTs; 9592 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9593 9594 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9595 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9596 EVT PtrVT = PVTs[0]; 9597 9598 unsigned NumValues = RetTys.size(); 9599 ReturnValues.resize(NumValues); 9600 SmallVector<SDValue, 4> Chains(NumValues); 9601 9602 // An aggregate return value cannot wrap around the address space, so 9603 // offsets to its parts don't wrap either. 9604 SDNodeFlags Flags; 9605 Flags.setNoUnsignedWrap(true); 9606 9607 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9608 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9609 for (unsigned i = 0; i < NumValues; ++i) { 9610 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9611 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9612 PtrVT), Flags); 9613 SDValue L = CLI.DAG.getLoad( 9614 RetTys[i], CLI.DL, CLI.Chain, Add, 9615 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9616 DemoteStackIdx, Offsets[i]), 9617 HiddenSRetAlign); 9618 ReturnValues[i] = L; 9619 Chains[i] = L.getValue(1); 9620 } 9621 9622 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9623 } else { 9624 // Collect the legal value parts into potentially illegal values 9625 // that correspond to the original function's return values. 9626 Optional<ISD::NodeType> AssertOp; 9627 if (CLI.RetSExt) 9628 AssertOp = ISD::AssertSext; 9629 else if (CLI.RetZExt) 9630 AssertOp = ISD::AssertZext; 9631 unsigned CurReg = 0; 9632 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9633 EVT VT = RetTys[I]; 9634 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9635 CLI.CallConv, VT); 9636 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9637 CLI.CallConv, VT); 9638 9639 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9640 NumRegs, RegisterVT, VT, nullptr, 9641 CLI.CallConv, AssertOp)); 9642 CurReg += NumRegs; 9643 } 9644 9645 // For a function returning void, there is no return value. We can't create 9646 // such a node, so we just return a null return value in that case. In 9647 // that case, nothing will actually look at the value. 9648 if (ReturnValues.empty()) 9649 return std::make_pair(SDValue(), CLI.Chain); 9650 } 9651 9652 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9653 CLI.DAG.getVTList(RetTys), ReturnValues); 9654 return std::make_pair(Res, CLI.Chain); 9655 } 9656 9657 /// Places new result values for the node in Results (their number 9658 /// and types must exactly match those of the original return values of 9659 /// the node), or leaves Results empty, which indicates that the node is not 9660 /// to be custom lowered after all. 9661 void TargetLowering::LowerOperationWrapper(SDNode *N, 9662 SmallVectorImpl<SDValue> &Results, 9663 SelectionDAG &DAG) const { 9664 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9665 9666 if (!Res.getNode()) 9667 return; 9668 9669 // If the original node has one result, take the return value from 9670 // LowerOperation as is. It might not be result number 0. 9671 if (N->getNumValues() == 1) { 9672 Results.push_back(Res); 9673 return; 9674 } 9675 9676 // If the original node has multiple results, then the return node should 9677 // have the same number of results. 9678 assert((N->getNumValues() == Res->getNumValues()) && 9679 "Lowering returned the wrong number of results!"); 9680 9681 // Places new result values base on N result number. 9682 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9683 Results.push_back(Res.getValue(I)); 9684 } 9685 9686 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9687 llvm_unreachable("LowerOperation not implemented for this target!"); 9688 } 9689 9690 void 9691 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9692 SDValue Op = getNonRegisterValue(V); 9693 assert((Op.getOpcode() != ISD::CopyFromReg || 9694 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9695 "Copy from a reg to the same reg!"); 9696 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9697 9698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9699 // If this is an InlineAsm we have to match the registers required, not the 9700 // notional registers required by the type. 9701 9702 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9703 None); // This is not an ABI copy. 9704 SDValue Chain = DAG.getEntryNode(); 9705 9706 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9707 FuncInfo.PreferredExtendType.end()) 9708 ? ISD::ANY_EXTEND 9709 : FuncInfo.PreferredExtendType[V]; 9710 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9711 PendingExports.push_back(Chain); 9712 } 9713 9714 #include "llvm/CodeGen/SelectionDAGISel.h" 9715 9716 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9717 /// entry block, return true. This includes arguments used by switches, since 9718 /// the switch may expand into multiple basic blocks. 9719 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9720 // With FastISel active, we may be splitting blocks, so force creation 9721 // of virtual registers for all non-dead arguments. 9722 if (FastISel) 9723 return A->use_empty(); 9724 9725 const BasicBlock &Entry = A->getParent()->front(); 9726 for (const User *U : A->users()) 9727 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9728 return false; // Use not in entry block. 9729 9730 return true; 9731 } 9732 9733 using ArgCopyElisionMapTy = 9734 DenseMap<const Argument *, 9735 std::pair<const AllocaInst *, const StoreInst *>>; 9736 9737 /// Scan the entry block of the function in FuncInfo for arguments that look 9738 /// like copies into a local alloca. Record any copied arguments in 9739 /// ArgCopyElisionCandidates. 9740 static void 9741 findArgumentCopyElisionCandidates(const DataLayout &DL, 9742 FunctionLoweringInfo *FuncInfo, 9743 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9744 // Record the state of every static alloca used in the entry block. Argument 9745 // allocas are all used in the entry block, so we need approximately as many 9746 // entries as we have arguments. 9747 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9748 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9749 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9750 StaticAllocas.reserve(NumArgs * 2); 9751 9752 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9753 if (!V) 9754 return nullptr; 9755 V = V->stripPointerCasts(); 9756 const auto *AI = dyn_cast<AllocaInst>(V); 9757 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9758 return nullptr; 9759 auto Iter = StaticAllocas.insert({AI, Unknown}); 9760 return &Iter.first->second; 9761 }; 9762 9763 // Look for stores of arguments to static allocas. Look through bitcasts and 9764 // GEPs to handle type coercions, as long as the alloca is fully initialized 9765 // by the store. Any non-store use of an alloca escapes it and any subsequent 9766 // unanalyzed store might write it. 9767 // FIXME: Handle structs initialized with multiple stores. 9768 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9769 // Look for stores, and handle non-store uses conservatively. 9770 const auto *SI = dyn_cast<StoreInst>(&I); 9771 if (!SI) { 9772 // We will look through cast uses, so ignore them completely. 9773 if (I.isCast()) 9774 continue; 9775 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9776 // to allocas. 9777 if (I.isDebugOrPseudoInst()) 9778 continue; 9779 // This is an unknown instruction. Assume it escapes or writes to all 9780 // static alloca operands. 9781 for (const Use &U : I.operands()) { 9782 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9783 *Info = StaticAllocaInfo::Clobbered; 9784 } 9785 continue; 9786 } 9787 9788 // If the stored value is a static alloca, mark it as escaped. 9789 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9790 *Info = StaticAllocaInfo::Clobbered; 9791 9792 // Check if the destination is a static alloca. 9793 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9794 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9795 if (!Info) 9796 continue; 9797 const AllocaInst *AI = cast<AllocaInst>(Dst); 9798 9799 // Skip allocas that have been initialized or clobbered. 9800 if (*Info != StaticAllocaInfo::Unknown) 9801 continue; 9802 9803 // Check if the stored value is an argument, and that this store fully 9804 // initializes the alloca. Don't elide copies from the same argument twice. 9805 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9806 const auto *Arg = dyn_cast<Argument>(Val); 9807 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9808 Arg->getType()->isEmptyTy() || 9809 DL.getTypeStoreSize(Arg->getType()) != 9810 DL.getTypeAllocSize(AI->getAllocatedType()) || 9811 ArgCopyElisionCandidates.count(Arg)) { 9812 *Info = StaticAllocaInfo::Clobbered; 9813 continue; 9814 } 9815 9816 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9817 << '\n'); 9818 9819 // Mark this alloca and store for argument copy elision. 9820 *Info = StaticAllocaInfo::Elidable; 9821 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9822 9823 // Stop scanning if we've seen all arguments. This will happen early in -O0 9824 // builds, which is useful, because -O0 builds have large entry blocks and 9825 // many allocas. 9826 if (ArgCopyElisionCandidates.size() == NumArgs) 9827 break; 9828 } 9829 } 9830 9831 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9832 /// ArgVal is a load from a suitable fixed stack object. 9833 static void tryToElideArgumentCopy( 9834 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9835 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9836 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9837 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9838 SDValue ArgVal, bool &ArgHasUses) { 9839 // Check if this is a load from a fixed stack object. 9840 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9841 if (!LNode) 9842 return; 9843 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9844 if (!FINode) 9845 return; 9846 9847 // Check that the fixed stack object is the right size and alignment. 9848 // Look at the alignment that the user wrote on the alloca instead of looking 9849 // at the stack object. 9850 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9851 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9852 const AllocaInst *AI = ArgCopyIter->second.first; 9853 int FixedIndex = FINode->getIndex(); 9854 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9855 int OldIndex = AllocaIndex; 9856 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9857 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9858 LLVM_DEBUG( 9859 dbgs() << " argument copy elision failed due to bad fixed stack " 9860 "object size\n"); 9861 return; 9862 } 9863 Align RequiredAlignment = AI->getAlign(); 9864 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9865 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9866 "greater than stack argument alignment (" 9867 << DebugStr(RequiredAlignment) << " vs " 9868 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9869 return; 9870 } 9871 9872 // Perform the elision. Delete the old stack object and replace its only use 9873 // in the variable info map. Mark the stack object as mutable. 9874 LLVM_DEBUG({ 9875 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9876 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9877 << '\n'; 9878 }); 9879 MFI.RemoveStackObject(OldIndex); 9880 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9881 AllocaIndex = FixedIndex; 9882 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9883 Chains.push_back(ArgVal.getValue(1)); 9884 9885 // Avoid emitting code for the store implementing the copy. 9886 const StoreInst *SI = ArgCopyIter->second.second; 9887 ElidedArgCopyInstrs.insert(SI); 9888 9889 // Check for uses of the argument again so that we can avoid exporting ArgVal 9890 // if it is't used by anything other than the store. 9891 for (const Value *U : Arg.users()) { 9892 if (U != SI) { 9893 ArgHasUses = true; 9894 break; 9895 } 9896 } 9897 } 9898 9899 void SelectionDAGISel::LowerArguments(const Function &F) { 9900 SelectionDAG &DAG = SDB->DAG; 9901 SDLoc dl = SDB->getCurSDLoc(); 9902 const DataLayout &DL = DAG.getDataLayout(); 9903 SmallVector<ISD::InputArg, 16> Ins; 9904 9905 // In Naked functions we aren't going to save any registers. 9906 if (F.hasFnAttribute(Attribute::Naked)) 9907 return; 9908 9909 if (!FuncInfo->CanLowerReturn) { 9910 // Put in an sret pointer parameter before all the other parameters. 9911 SmallVector<EVT, 1> ValueVTs; 9912 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9913 F.getReturnType()->getPointerTo( 9914 DAG.getDataLayout().getAllocaAddrSpace()), 9915 ValueVTs); 9916 9917 // NOTE: Assuming that a pointer will never break down to more than one VT 9918 // or one register. 9919 ISD::ArgFlagsTy Flags; 9920 Flags.setSRet(); 9921 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9922 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9923 ISD::InputArg::NoArgIndex, 0); 9924 Ins.push_back(RetArg); 9925 } 9926 9927 // Look for stores of arguments to static allocas. Mark such arguments with a 9928 // flag to ask the target to give us the memory location of that argument if 9929 // available. 9930 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9931 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9932 ArgCopyElisionCandidates); 9933 9934 // Set up the incoming argument description vector. 9935 for (const Argument &Arg : F.args()) { 9936 unsigned ArgNo = Arg.getArgNo(); 9937 SmallVector<EVT, 4> ValueVTs; 9938 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9939 bool isArgValueUsed = !Arg.use_empty(); 9940 unsigned PartBase = 0; 9941 Type *FinalType = Arg.getType(); 9942 if (Arg.hasAttribute(Attribute::ByVal)) 9943 FinalType = Arg.getParamByValType(); 9944 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9945 FinalType, F.getCallingConv(), F.isVarArg()); 9946 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9947 Value != NumValues; ++Value) { 9948 EVT VT = ValueVTs[Value]; 9949 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9950 ISD::ArgFlagsTy Flags; 9951 9952 // Certain targets (such as MIPS), may have a different ABI alignment 9953 // for a type depending on the context. Give the target a chance to 9954 // specify the alignment it wants. 9955 const Align OriginalAlignment( 9956 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9957 9958 if (Arg.getType()->isPointerTy()) { 9959 Flags.setPointer(); 9960 Flags.setPointerAddrSpace( 9961 cast<PointerType>(Arg.getType())->getAddressSpace()); 9962 } 9963 if (Arg.hasAttribute(Attribute::ZExt)) 9964 Flags.setZExt(); 9965 if (Arg.hasAttribute(Attribute::SExt)) 9966 Flags.setSExt(); 9967 if (Arg.hasAttribute(Attribute::InReg)) { 9968 // If we are using vectorcall calling convention, a structure that is 9969 // passed InReg - is surely an HVA 9970 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9971 isa<StructType>(Arg.getType())) { 9972 // The first value of a structure is marked 9973 if (0 == Value) 9974 Flags.setHvaStart(); 9975 Flags.setHva(); 9976 } 9977 // Set InReg Flag 9978 Flags.setInReg(); 9979 } 9980 if (Arg.hasAttribute(Attribute::StructRet)) 9981 Flags.setSRet(); 9982 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9983 Flags.setSwiftSelf(); 9984 if (Arg.hasAttribute(Attribute::SwiftError)) 9985 Flags.setSwiftError(); 9986 if (Arg.hasAttribute(Attribute::ByVal)) 9987 Flags.setByVal(); 9988 if (Arg.hasAttribute(Attribute::ByRef)) 9989 Flags.setByRef(); 9990 if (Arg.hasAttribute(Attribute::InAlloca)) { 9991 Flags.setInAlloca(); 9992 // Set the byval flag for CCAssignFn callbacks that don't know about 9993 // inalloca. This way we can know how many bytes we should've allocated 9994 // and how many bytes a callee cleanup function will pop. If we port 9995 // inalloca to more targets, we'll have to add custom inalloca handling 9996 // in the various CC lowering callbacks. 9997 Flags.setByVal(); 9998 } 9999 if (Arg.hasAttribute(Attribute::Preallocated)) { 10000 Flags.setPreallocated(); 10001 // Set the byval flag for CCAssignFn callbacks that don't know about 10002 // preallocated. This way we can know how many bytes we should've 10003 // allocated and how many bytes a callee cleanup function will pop. If 10004 // we port preallocated to more targets, we'll have to add custom 10005 // preallocated handling in the various CC lowering callbacks. 10006 Flags.setByVal(); 10007 } 10008 10009 Type *ArgMemTy = nullptr; 10010 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10011 Flags.isByRef()) { 10012 if (!ArgMemTy) 10013 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10014 10015 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10016 10017 // For in-memory arguments, size and alignment should be passed from FE. 10018 // BE will guess if this info is not there but there are cases it cannot 10019 // get right. 10020 MaybeAlign MemAlign = Arg.getParamAlign(); 10021 if (!MemAlign) 10022 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10023 10024 if (Flags.isByRef()) { 10025 Flags.setByRefSize(MemSize); 10026 Flags.setByRefAlign(*MemAlign); 10027 } else { 10028 Flags.setByValSize(MemSize); 10029 Flags.setByValAlign(*MemAlign); 10030 } 10031 } 10032 10033 if (Arg.hasAttribute(Attribute::Nest)) 10034 Flags.setNest(); 10035 if (NeedsRegBlock) 10036 Flags.setInConsecutiveRegs(); 10037 Flags.setOrigAlign(OriginalAlignment); 10038 if (ArgCopyElisionCandidates.count(&Arg)) 10039 Flags.setCopyElisionCandidate(); 10040 if (Arg.hasAttribute(Attribute::Returned)) 10041 Flags.setReturned(); 10042 10043 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10044 *CurDAG->getContext(), F.getCallingConv(), VT); 10045 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10046 *CurDAG->getContext(), F.getCallingConv(), VT); 10047 for (unsigned i = 0; i != NumRegs; ++i) { 10048 // For scalable vectors, use the minimum size; individual targets 10049 // are responsible for handling scalable vector arguments and 10050 // return values. 10051 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10052 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10053 if (NumRegs > 1 && i == 0) 10054 MyFlags.Flags.setSplit(); 10055 // if it isn't first piece, alignment must be 1 10056 else if (i > 0) { 10057 MyFlags.Flags.setOrigAlign(Align(1)); 10058 if (i == NumRegs - 1) 10059 MyFlags.Flags.setSplitEnd(); 10060 } 10061 Ins.push_back(MyFlags); 10062 } 10063 if (NeedsRegBlock && Value == NumValues - 1) 10064 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10065 PartBase += VT.getStoreSize().getKnownMinSize(); 10066 } 10067 } 10068 10069 // Call the target to set up the argument values. 10070 SmallVector<SDValue, 8> InVals; 10071 SDValue NewRoot = TLI->LowerFormalArguments( 10072 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10073 10074 // Verify that the target's LowerFormalArguments behaved as expected. 10075 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10076 "LowerFormalArguments didn't return a valid chain!"); 10077 assert(InVals.size() == Ins.size() && 10078 "LowerFormalArguments didn't emit the correct number of values!"); 10079 LLVM_DEBUG({ 10080 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10081 assert(InVals[i].getNode() && 10082 "LowerFormalArguments emitted a null value!"); 10083 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10084 "LowerFormalArguments emitted a value with the wrong type!"); 10085 } 10086 }); 10087 10088 // Update the DAG with the new chain value resulting from argument lowering. 10089 DAG.setRoot(NewRoot); 10090 10091 // Set up the argument values. 10092 unsigned i = 0; 10093 if (!FuncInfo->CanLowerReturn) { 10094 // Create a virtual register for the sret pointer, and put in a copy 10095 // from the sret argument into it. 10096 SmallVector<EVT, 1> ValueVTs; 10097 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10098 F.getReturnType()->getPointerTo( 10099 DAG.getDataLayout().getAllocaAddrSpace()), 10100 ValueVTs); 10101 MVT VT = ValueVTs[0].getSimpleVT(); 10102 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10103 Optional<ISD::NodeType> AssertOp = None; 10104 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10105 nullptr, F.getCallingConv(), AssertOp); 10106 10107 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10108 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10109 Register SRetReg = 10110 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10111 FuncInfo->DemoteRegister = SRetReg; 10112 NewRoot = 10113 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10114 DAG.setRoot(NewRoot); 10115 10116 // i indexes lowered arguments. Bump it past the hidden sret argument. 10117 ++i; 10118 } 10119 10120 SmallVector<SDValue, 4> Chains; 10121 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10122 for (const Argument &Arg : F.args()) { 10123 SmallVector<SDValue, 4> ArgValues; 10124 SmallVector<EVT, 4> ValueVTs; 10125 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10126 unsigned NumValues = ValueVTs.size(); 10127 if (NumValues == 0) 10128 continue; 10129 10130 bool ArgHasUses = !Arg.use_empty(); 10131 10132 // Elide the copying store if the target loaded this argument from a 10133 // suitable fixed stack object. 10134 if (Ins[i].Flags.isCopyElisionCandidate()) { 10135 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10136 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10137 InVals[i], ArgHasUses); 10138 } 10139 10140 // If this argument is unused then remember its value. It is used to generate 10141 // debugging information. 10142 bool isSwiftErrorArg = 10143 TLI->supportSwiftError() && 10144 Arg.hasAttribute(Attribute::SwiftError); 10145 if (!ArgHasUses && !isSwiftErrorArg) { 10146 SDB->setUnusedArgValue(&Arg, InVals[i]); 10147 10148 // Also remember any frame index for use in FastISel. 10149 if (FrameIndexSDNode *FI = 10150 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10151 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10152 } 10153 10154 for (unsigned Val = 0; Val != NumValues; ++Val) { 10155 EVT VT = ValueVTs[Val]; 10156 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10157 F.getCallingConv(), VT); 10158 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10159 *CurDAG->getContext(), F.getCallingConv(), VT); 10160 10161 // Even an apparent 'unused' swifterror argument needs to be returned. So 10162 // we do generate a copy for it that can be used on return from the 10163 // function. 10164 if (ArgHasUses || isSwiftErrorArg) { 10165 Optional<ISD::NodeType> AssertOp; 10166 if (Arg.hasAttribute(Attribute::SExt)) 10167 AssertOp = ISD::AssertSext; 10168 else if (Arg.hasAttribute(Attribute::ZExt)) 10169 AssertOp = ISD::AssertZext; 10170 10171 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10172 PartVT, VT, nullptr, 10173 F.getCallingConv(), AssertOp)); 10174 } 10175 10176 i += NumParts; 10177 } 10178 10179 // We don't need to do anything else for unused arguments. 10180 if (ArgValues.empty()) 10181 continue; 10182 10183 // Note down frame index. 10184 if (FrameIndexSDNode *FI = 10185 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10186 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10187 10188 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10189 SDB->getCurSDLoc()); 10190 10191 SDB->setValue(&Arg, Res); 10192 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10193 // We want to associate the argument with the frame index, among 10194 // involved operands, that correspond to the lowest address. The 10195 // getCopyFromParts function, called earlier, is swapping the order of 10196 // the operands to BUILD_PAIR depending on endianness. The result of 10197 // that swapping is that the least significant bits of the argument will 10198 // be in the first operand of the BUILD_PAIR node, and the most 10199 // significant bits will be in the second operand. 10200 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10201 if (LoadSDNode *LNode = 10202 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10203 if (FrameIndexSDNode *FI = 10204 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10205 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10206 } 10207 10208 // Analyses past this point are naive and don't expect an assertion. 10209 if (Res.getOpcode() == ISD::AssertZext) 10210 Res = Res.getOperand(0); 10211 10212 // Update the SwiftErrorVRegDefMap. 10213 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10214 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10215 if (Register::isVirtualRegister(Reg)) 10216 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10217 Reg); 10218 } 10219 10220 // If this argument is live outside of the entry block, insert a copy from 10221 // wherever we got it to the vreg that other BB's will reference it as. 10222 if (Res.getOpcode() == ISD::CopyFromReg) { 10223 // If we can, though, try to skip creating an unnecessary vreg. 10224 // FIXME: This isn't very clean... it would be nice to make this more 10225 // general. 10226 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10227 if (Register::isVirtualRegister(Reg)) { 10228 FuncInfo->ValueMap[&Arg] = Reg; 10229 continue; 10230 } 10231 } 10232 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10233 FuncInfo->InitializeRegForValue(&Arg); 10234 SDB->CopyToExportRegsIfNeeded(&Arg); 10235 } 10236 } 10237 10238 if (!Chains.empty()) { 10239 Chains.push_back(NewRoot); 10240 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10241 } 10242 10243 DAG.setRoot(NewRoot); 10244 10245 assert(i == InVals.size() && "Argument register count mismatch!"); 10246 10247 // If any argument copy elisions occurred and we have debug info, update the 10248 // stale frame indices used in the dbg.declare variable info table. 10249 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10250 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10251 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10252 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10253 if (I != ArgCopyElisionFrameIndexMap.end()) 10254 VI.Slot = I->second; 10255 } 10256 } 10257 10258 // Finally, if the target has anything special to do, allow it to do so. 10259 emitFunctionEntryCode(); 10260 } 10261 10262 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10263 /// ensure constants are generated when needed. Remember the virtual registers 10264 /// that need to be added to the Machine PHI nodes as input. We cannot just 10265 /// directly add them, because expansion might result in multiple MBB's for one 10266 /// BB. As such, the start of the BB might correspond to a different MBB than 10267 /// the end. 10268 void 10269 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10270 const Instruction *TI = LLVMBB->getTerminator(); 10271 10272 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10273 10274 // Check PHI nodes in successors that expect a value to be available from this 10275 // block. 10276 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10277 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10278 if (!isa<PHINode>(SuccBB->begin())) continue; 10279 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10280 10281 // If this terminator has multiple identical successors (common for 10282 // switches), only handle each succ once. 10283 if (!SuccsHandled.insert(SuccMBB).second) 10284 continue; 10285 10286 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10287 10288 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10289 // nodes and Machine PHI nodes, but the incoming operands have not been 10290 // emitted yet. 10291 for (const PHINode &PN : SuccBB->phis()) { 10292 // Ignore dead phi's. 10293 if (PN.use_empty()) 10294 continue; 10295 10296 // Skip empty types 10297 if (PN.getType()->isEmptyTy()) 10298 continue; 10299 10300 unsigned Reg; 10301 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10302 10303 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10304 unsigned &RegOut = ConstantsOut[C]; 10305 if (RegOut == 0) { 10306 RegOut = FuncInfo.CreateRegs(C); 10307 CopyValueToVirtualRegister(C, RegOut); 10308 } 10309 Reg = RegOut; 10310 } else { 10311 DenseMap<const Value *, Register>::iterator I = 10312 FuncInfo.ValueMap.find(PHIOp); 10313 if (I != FuncInfo.ValueMap.end()) 10314 Reg = I->second; 10315 else { 10316 assert(isa<AllocaInst>(PHIOp) && 10317 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10318 "Didn't codegen value into a register!??"); 10319 Reg = FuncInfo.CreateRegs(PHIOp); 10320 CopyValueToVirtualRegister(PHIOp, Reg); 10321 } 10322 } 10323 10324 // Remember that this register needs to added to the machine PHI node as 10325 // the input for this MBB. 10326 SmallVector<EVT, 4> ValueVTs; 10327 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10328 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10329 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10330 EVT VT = ValueVTs[vti]; 10331 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10332 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10333 FuncInfo.PHINodesToUpdate.push_back( 10334 std::make_pair(&*MBBI++, Reg + i)); 10335 Reg += NumRegisters; 10336 } 10337 } 10338 } 10339 10340 ConstantsOut.clear(); 10341 } 10342 10343 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10344 /// is 0. 10345 MachineBasicBlock * 10346 SelectionDAGBuilder::StackProtectorDescriptor:: 10347 AddSuccessorMBB(const BasicBlock *BB, 10348 MachineBasicBlock *ParentMBB, 10349 bool IsLikely, 10350 MachineBasicBlock *SuccMBB) { 10351 // If SuccBB has not been created yet, create it. 10352 if (!SuccMBB) { 10353 MachineFunction *MF = ParentMBB->getParent(); 10354 MachineFunction::iterator BBI(ParentMBB); 10355 SuccMBB = MF->CreateMachineBasicBlock(BB); 10356 MF->insert(++BBI, SuccMBB); 10357 } 10358 // Add it as a successor of ParentMBB. 10359 ParentMBB->addSuccessor( 10360 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10361 return SuccMBB; 10362 } 10363 10364 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10365 MachineFunction::iterator I(MBB); 10366 if (++I == FuncInfo.MF->end()) 10367 return nullptr; 10368 return &*I; 10369 } 10370 10371 /// During lowering new call nodes can be created (such as memset, etc.). 10372 /// Those will become new roots of the current DAG, but complications arise 10373 /// when they are tail calls. In such cases, the call lowering will update 10374 /// the root, but the builder still needs to know that a tail call has been 10375 /// lowered in order to avoid generating an additional return. 10376 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10377 // If the node is null, we do have a tail call. 10378 if (MaybeTC.getNode() != nullptr) 10379 DAG.setRoot(MaybeTC); 10380 else 10381 HasTailCall = true; 10382 } 10383 10384 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10385 MachineBasicBlock *SwitchMBB, 10386 MachineBasicBlock *DefaultMBB) { 10387 MachineFunction *CurMF = FuncInfo.MF; 10388 MachineBasicBlock *NextMBB = nullptr; 10389 MachineFunction::iterator BBI(W.MBB); 10390 if (++BBI != FuncInfo.MF->end()) 10391 NextMBB = &*BBI; 10392 10393 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10394 10395 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10396 10397 if (Size == 2 && W.MBB == SwitchMBB) { 10398 // If any two of the cases has the same destination, and if one value 10399 // is the same as the other, but has one bit unset that the other has set, 10400 // use bit manipulation to do two compares at once. For example: 10401 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10402 // TODO: This could be extended to merge any 2 cases in switches with 3 10403 // cases. 10404 // TODO: Handle cases where W.CaseBB != SwitchBB. 10405 CaseCluster &Small = *W.FirstCluster; 10406 CaseCluster &Big = *W.LastCluster; 10407 10408 if (Small.Low == Small.High && Big.Low == Big.High && 10409 Small.MBB == Big.MBB) { 10410 const APInt &SmallValue = Small.Low->getValue(); 10411 const APInt &BigValue = Big.Low->getValue(); 10412 10413 // Check that there is only one bit different. 10414 APInt CommonBit = BigValue ^ SmallValue; 10415 if (CommonBit.isPowerOf2()) { 10416 SDValue CondLHS = getValue(Cond); 10417 EVT VT = CondLHS.getValueType(); 10418 SDLoc DL = getCurSDLoc(); 10419 10420 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10421 DAG.getConstant(CommonBit, DL, VT)); 10422 SDValue Cond = DAG.getSetCC( 10423 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10424 ISD::SETEQ); 10425 10426 // Update successor info. 10427 // Both Small and Big will jump to Small.BB, so we sum up the 10428 // probabilities. 10429 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10430 if (BPI) 10431 addSuccessorWithProb( 10432 SwitchMBB, DefaultMBB, 10433 // The default destination is the first successor in IR. 10434 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10435 else 10436 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10437 10438 // Insert the true branch. 10439 SDValue BrCond = 10440 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10441 DAG.getBasicBlock(Small.MBB)); 10442 // Insert the false branch. 10443 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10444 DAG.getBasicBlock(DefaultMBB)); 10445 10446 DAG.setRoot(BrCond); 10447 return; 10448 } 10449 } 10450 } 10451 10452 if (TM.getOptLevel() != CodeGenOpt::None) { 10453 // Here, we order cases by probability so the most likely case will be 10454 // checked first. However, two clusters can have the same probability in 10455 // which case their relative ordering is non-deterministic. So we use Low 10456 // as a tie-breaker as clusters are guaranteed to never overlap. 10457 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10458 [](const CaseCluster &a, const CaseCluster &b) { 10459 return a.Prob != b.Prob ? 10460 a.Prob > b.Prob : 10461 a.Low->getValue().slt(b.Low->getValue()); 10462 }); 10463 10464 // Rearrange the case blocks so that the last one falls through if possible 10465 // without changing the order of probabilities. 10466 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10467 --I; 10468 if (I->Prob > W.LastCluster->Prob) 10469 break; 10470 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10471 std::swap(*I, *W.LastCluster); 10472 break; 10473 } 10474 } 10475 } 10476 10477 // Compute total probability. 10478 BranchProbability DefaultProb = W.DefaultProb; 10479 BranchProbability UnhandledProbs = DefaultProb; 10480 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10481 UnhandledProbs += I->Prob; 10482 10483 MachineBasicBlock *CurMBB = W.MBB; 10484 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10485 bool FallthroughUnreachable = false; 10486 MachineBasicBlock *Fallthrough; 10487 if (I == W.LastCluster) { 10488 // For the last cluster, fall through to the default destination. 10489 Fallthrough = DefaultMBB; 10490 FallthroughUnreachable = isa<UnreachableInst>( 10491 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10492 } else { 10493 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10494 CurMF->insert(BBI, Fallthrough); 10495 // Put Cond in a virtual register to make it available from the new blocks. 10496 ExportFromCurrentBlock(Cond); 10497 } 10498 UnhandledProbs -= I->Prob; 10499 10500 switch (I->Kind) { 10501 case CC_JumpTable: { 10502 // FIXME: Optimize away range check based on pivot comparisons. 10503 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10504 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10505 10506 // The jump block hasn't been inserted yet; insert it here. 10507 MachineBasicBlock *JumpMBB = JT->MBB; 10508 CurMF->insert(BBI, JumpMBB); 10509 10510 auto JumpProb = I->Prob; 10511 auto FallthroughProb = UnhandledProbs; 10512 10513 // If the default statement is a target of the jump table, we evenly 10514 // distribute the default probability to successors of CurMBB. Also 10515 // update the probability on the edge from JumpMBB to Fallthrough. 10516 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10517 SE = JumpMBB->succ_end(); 10518 SI != SE; ++SI) { 10519 if (*SI == DefaultMBB) { 10520 JumpProb += DefaultProb / 2; 10521 FallthroughProb -= DefaultProb / 2; 10522 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10523 JumpMBB->normalizeSuccProbs(); 10524 break; 10525 } 10526 } 10527 10528 if (FallthroughUnreachable) { 10529 // Skip the range check if the fallthrough block is unreachable. 10530 JTH->OmitRangeCheck = true; 10531 } 10532 10533 if (!JTH->OmitRangeCheck) 10534 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10535 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10536 CurMBB->normalizeSuccProbs(); 10537 10538 // The jump table header will be inserted in our current block, do the 10539 // range check, and fall through to our fallthrough block. 10540 JTH->HeaderBB = CurMBB; 10541 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10542 10543 // If we're in the right place, emit the jump table header right now. 10544 if (CurMBB == SwitchMBB) { 10545 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10546 JTH->Emitted = true; 10547 } 10548 break; 10549 } 10550 case CC_BitTests: { 10551 // FIXME: Optimize away range check based on pivot comparisons. 10552 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10553 10554 // The bit test blocks haven't been inserted yet; insert them here. 10555 for (BitTestCase &BTC : BTB->Cases) 10556 CurMF->insert(BBI, BTC.ThisBB); 10557 10558 // Fill in fields of the BitTestBlock. 10559 BTB->Parent = CurMBB; 10560 BTB->Default = Fallthrough; 10561 10562 BTB->DefaultProb = UnhandledProbs; 10563 // If the cases in bit test don't form a contiguous range, we evenly 10564 // distribute the probability on the edge to Fallthrough to two 10565 // successors of CurMBB. 10566 if (!BTB->ContiguousRange) { 10567 BTB->Prob += DefaultProb / 2; 10568 BTB->DefaultProb -= DefaultProb / 2; 10569 } 10570 10571 if (FallthroughUnreachable) { 10572 // Skip the range check if the fallthrough block is unreachable. 10573 BTB->OmitRangeCheck = true; 10574 } 10575 10576 // If we're in the right place, emit the bit test header right now. 10577 if (CurMBB == SwitchMBB) { 10578 visitBitTestHeader(*BTB, SwitchMBB); 10579 BTB->Emitted = true; 10580 } 10581 break; 10582 } 10583 case CC_Range: { 10584 const Value *RHS, *LHS, *MHS; 10585 ISD::CondCode CC; 10586 if (I->Low == I->High) { 10587 // Check Cond == I->Low. 10588 CC = ISD::SETEQ; 10589 LHS = Cond; 10590 RHS=I->Low; 10591 MHS = nullptr; 10592 } else { 10593 // Check I->Low <= Cond <= I->High. 10594 CC = ISD::SETLE; 10595 LHS = I->Low; 10596 MHS = Cond; 10597 RHS = I->High; 10598 } 10599 10600 // If Fallthrough is unreachable, fold away the comparison. 10601 if (FallthroughUnreachable) 10602 CC = ISD::SETTRUE; 10603 10604 // The false probability is the sum of all unhandled cases. 10605 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10606 getCurSDLoc(), I->Prob, UnhandledProbs); 10607 10608 if (CurMBB == SwitchMBB) 10609 visitSwitchCase(CB, SwitchMBB); 10610 else 10611 SL->SwitchCases.push_back(CB); 10612 10613 break; 10614 } 10615 } 10616 CurMBB = Fallthrough; 10617 } 10618 } 10619 10620 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10621 CaseClusterIt First, 10622 CaseClusterIt Last) { 10623 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10624 if (X.Prob != CC.Prob) 10625 return X.Prob > CC.Prob; 10626 10627 // Ties are broken by comparing the case value. 10628 return X.Low->getValue().slt(CC.Low->getValue()); 10629 }); 10630 } 10631 10632 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10633 const SwitchWorkListItem &W, 10634 Value *Cond, 10635 MachineBasicBlock *SwitchMBB) { 10636 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10637 "Clusters not sorted?"); 10638 10639 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10640 10641 // Balance the tree based on branch probabilities to create a near-optimal (in 10642 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10643 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10644 CaseClusterIt LastLeft = W.FirstCluster; 10645 CaseClusterIt FirstRight = W.LastCluster; 10646 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10647 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10648 10649 // Move LastLeft and FirstRight towards each other from opposite directions to 10650 // find a partitioning of the clusters which balances the probability on both 10651 // sides. If LeftProb and RightProb are equal, alternate which side is 10652 // taken to ensure 0-probability nodes are distributed evenly. 10653 unsigned I = 0; 10654 while (LastLeft + 1 < FirstRight) { 10655 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10656 LeftProb += (++LastLeft)->Prob; 10657 else 10658 RightProb += (--FirstRight)->Prob; 10659 I++; 10660 } 10661 10662 while (true) { 10663 // Our binary search tree differs from a typical BST in that ours can have up 10664 // to three values in each leaf. The pivot selection above doesn't take that 10665 // into account, which means the tree might require more nodes and be less 10666 // efficient. We compensate for this here. 10667 10668 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10669 unsigned NumRight = W.LastCluster - FirstRight + 1; 10670 10671 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10672 // If one side has less than 3 clusters, and the other has more than 3, 10673 // consider taking a cluster from the other side. 10674 10675 if (NumLeft < NumRight) { 10676 // Consider moving the first cluster on the right to the left side. 10677 CaseCluster &CC = *FirstRight; 10678 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10679 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10680 if (LeftSideRank <= RightSideRank) { 10681 // Moving the cluster to the left does not demote it. 10682 ++LastLeft; 10683 ++FirstRight; 10684 continue; 10685 } 10686 } else { 10687 assert(NumRight < NumLeft); 10688 // Consider moving the last element on the left to the right side. 10689 CaseCluster &CC = *LastLeft; 10690 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10691 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10692 if (RightSideRank <= LeftSideRank) { 10693 // Moving the cluster to the right does not demot it. 10694 --LastLeft; 10695 --FirstRight; 10696 continue; 10697 } 10698 } 10699 } 10700 break; 10701 } 10702 10703 assert(LastLeft + 1 == FirstRight); 10704 assert(LastLeft >= W.FirstCluster); 10705 assert(FirstRight <= W.LastCluster); 10706 10707 // Use the first element on the right as pivot since we will make less-than 10708 // comparisons against it. 10709 CaseClusterIt PivotCluster = FirstRight; 10710 assert(PivotCluster > W.FirstCluster); 10711 assert(PivotCluster <= W.LastCluster); 10712 10713 CaseClusterIt FirstLeft = W.FirstCluster; 10714 CaseClusterIt LastRight = W.LastCluster; 10715 10716 const ConstantInt *Pivot = PivotCluster->Low; 10717 10718 // New blocks will be inserted immediately after the current one. 10719 MachineFunction::iterator BBI(W.MBB); 10720 ++BBI; 10721 10722 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10723 // we can branch to its destination directly if it's squeezed exactly in 10724 // between the known lower bound and Pivot - 1. 10725 MachineBasicBlock *LeftMBB; 10726 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10727 FirstLeft->Low == W.GE && 10728 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10729 LeftMBB = FirstLeft->MBB; 10730 } else { 10731 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10732 FuncInfo.MF->insert(BBI, LeftMBB); 10733 WorkList.push_back( 10734 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10735 // Put Cond in a virtual register to make it available from the new blocks. 10736 ExportFromCurrentBlock(Cond); 10737 } 10738 10739 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10740 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10741 // directly if RHS.High equals the current upper bound. 10742 MachineBasicBlock *RightMBB; 10743 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10744 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10745 RightMBB = FirstRight->MBB; 10746 } else { 10747 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10748 FuncInfo.MF->insert(BBI, RightMBB); 10749 WorkList.push_back( 10750 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10751 // Put Cond in a virtual register to make it available from the new blocks. 10752 ExportFromCurrentBlock(Cond); 10753 } 10754 10755 // Create the CaseBlock record that will be used to lower the branch. 10756 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10757 getCurSDLoc(), LeftProb, RightProb); 10758 10759 if (W.MBB == SwitchMBB) 10760 visitSwitchCase(CB, SwitchMBB); 10761 else 10762 SL->SwitchCases.push_back(CB); 10763 } 10764 10765 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10766 // from the swith statement. 10767 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10768 BranchProbability PeeledCaseProb) { 10769 if (PeeledCaseProb == BranchProbability::getOne()) 10770 return BranchProbability::getZero(); 10771 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10772 10773 uint32_t Numerator = CaseProb.getNumerator(); 10774 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10775 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10776 } 10777 10778 // Try to peel the top probability case if it exceeds the threshold. 10779 // Return current MachineBasicBlock for the switch statement if the peeling 10780 // does not occur. 10781 // If the peeling is performed, return the newly created MachineBasicBlock 10782 // for the peeled switch statement. Also update Clusters to remove the peeled 10783 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10784 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10785 const SwitchInst &SI, CaseClusterVector &Clusters, 10786 BranchProbability &PeeledCaseProb) { 10787 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10788 // Don't perform if there is only one cluster or optimizing for size. 10789 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10790 TM.getOptLevel() == CodeGenOpt::None || 10791 SwitchMBB->getParent()->getFunction().hasMinSize()) 10792 return SwitchMBB; 10793 10794 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10795 unsigned PeeledCaseIndex = 0; 10796 bool SwitchPeeled = false; 10797 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10798 CaseCluster &CC = Clusters[Index]; 10799 if (CC.Prob < TopCaseProb) 10800 continue; 10801 TopCaseProb = CC.Prob; 10802 PeeledCaseIndex = Index; 10803 SwitchPeeled = true; 10804 } 10805 if (!SwitchPeeled) 10806 return SwitchMBB; 10807 10808 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10809 << TopCaseProb << "\n"); 10810 10811 // Record the MBB for the peeled switch statement. 10812 MachineFunction::iterator BBI(SwitchMBB); 10813 ++BBI; 10814 MachineBasicBlock *PeeledSwitchMBB = 10815 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10816 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10817 10818 ExportFromCurrentBlock(SI.getCondition()); 10819 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10820 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10821 nullptr, nullptr, TopCaseProb.getCompl()}; 10822 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10823 10824 Clusters.erase(PeeledCaseIt); 10825 for (CaseCluster &CC : Clusters) { 10826 LLVM_DEBUG( 10827 dbgs() << "Scale the probablity for one cluster, before scaling: " 10828 << CC.Prob << "\n"); 10829 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10830 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10831 } 10832 PeeledCaseProb = TopCaseProb; 10833 return PeeledSwitchMBB; 10834 } 10835 10836 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10837 // Extract cases from the switch. 10838 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10839 CaseClusterVector Clusters; 10840 Clusters.reserve(SI.getNumCases()); 10841 for (auto I : SI.cases()) { 10842 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10843 const ConstantInt *CaseVal = I.getCaseValue(); 10844 BranchProbability Prob = 10845 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10846 : BranchProbability(1, SI.getNumCases() + 1); 10847 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10848 } 10849 10850 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10851 10852 // Cluster adjacent cases with the same destination. We do this at all 10853 // optimization levels because it's cheap to do and will make codegen faster 10854 // if there are many clusters. 10855 sortAndRangeify(Clusters); 10856 10857 // The branch probablity of the peeled case. 10858 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10859 MachineBasicBlock *PeeledSwitchMBB = 10860 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10861 10862 // If there is only the default destination, jump there directly. 10863 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10864 if (Clusters.empty()) { 10865 assert(PeeledSwitchMBB == SwitchMBB); 10866 SwitchMBB->addSuccessor(DefaultMBB); 10867 if (DefaultMBB != NextBlock(SwitchMBB)) { 10868 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10869 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10870 } 10871 return; 10872 } 10873 10874 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10875 SL->findBitTestClusters(Clusters, &SI); 10876 10877 LLVM_DEBUG({ 10878 dbgs() << "Case clusters: "; 10879 for (const CaseCluster &C : Clusters) { 10880 if (C.Kind == CC_JumpTable) 10881 dbgs() << "JT:"; 10882 if (C.Kind == CC_BitTests) 10883 dbgs() << "BT:"; 10884 10885 C.Low->getValue().print(dbgs(), true); 10886 if (C.Low != C.High) { 10887 dbgs() << '-'; 10888 C.High->getValue().print(dbgs(), true); 10889 } 10890 dbgs() << ' '; 10891 } 10892 dbgs() << '\n'; 10893 }); 10894 10895 assert(!Clusters.empty()); 10896 SwitchWorkList WorkList; 10897 CaseClusterIt First = Clusters.begin(); 10898 CaseClusterIt Last = Clusters.end() - 1; 10899 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10900 // Scale the branchprobability for DefaultMBB if the peel occurs and 10901 // DefaultMBB is not replaced. 10902 if (PeeledCaseProb != BranchProbability::getZero() && 10903 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10904 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10905 WorkList.push_back( 10906 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10907 10908 while (!WorkList.empty()) { 10909 SwitchWorkListItem W = WorkList.pop_back_val(); 10910 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10911 10912 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10913 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10914 // For optimized builds, lower large range as a balanced binary tree. 10915 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10916 continue; 10917 } 10918 10919 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10920 } 10921 } 10922 10923 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 10924 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10925 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10926 10927 SDLoc DL = getCurSDLoc(); 10928 SDValue V = getValue(I.getOperand(0)); 10929 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 10930 10931 if (VT.isScalableVector()) { 10932 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 10933 return; 10934 } 10935 10936 // Use VECTOR_SHUFFLE for the fixed-length vector 10937 // to maintain existing behavior. 10938 SmallVector<int, 8> Mask; 10939 unsigned NumElts = VT.getVectorMinNumElements(); 10940 for (unsigned i = 0; i != NumElts; ++i) 10941 Mask.push_back(NumElts - 1 - i); 10942 10943 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 10944 } 10945 10946 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10947 SmallVector<EVT, 4> ValueVTs; 10948 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10949 ValueVTs); 10950 unsigned NumValues = ValueVTs.size(); 10951 if (NumValues == 0) return; 10952 10953 SmallVector<SDValue, 4> Values(NumValues); 10954 SDValue Op = getValue(I.getOperand(0)); 10955 10956 for (unsigned i = 0; i != NumValues; ++i) 10957 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10958 SDValue(Op.getNode(), Op.getResNo() + i)); 10959 10960 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10961 DAG.getVTList(ValueVTs), Values)); 10962 } 10963 10964 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 10965 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10966 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10967 10968 SDLoc DL = getCurSDLoc(); 10969 SDValue V1 = getValue(I.getOperand(0)); 10970 SDValue V2 = getValue(I.getOperand(1)); 10971 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 10972 10973 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 10974 if (VT.isScalableVector()) { 10975 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 10976 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 10977 DAG.getConstant(Imm, DL, IdxVT))); 10978 return; 10979 } 10980 10981 unsigned NumElts = VT.getVectorNumElements(); 10982 10983 if ((-Imm > NumElts) || (Imm >= NumElts)) { 10984 // Result is undefined if immediate is out-of-bounds. 10985 setValue(&I, DAG.getUNDEF(VT)); 10986 return; 10987 } 10988 10989 uint64_t Idx = (NumElts + Imm) % NumElts; 10990 10991 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 10992 SmallVector<int, 8> Mask; 10993 for (unsigned i = 0; i < NumElts; ++i) 10994 Mask.push_back(Idx + i); 10995 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 10996 } 10997