1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements routines for translating from LLVM IR into SelectionDAG IR. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SelectionDAGBuilder.h" 15 #include "SDNodeDbgValue.h" 16 #include "llvm/ADT/BitVector.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/BranchProbabilityInfo.h" 22 #include "llvm/Analysis/ConstantFolding.h" 23 #include "llvm/Analysis/Loads.h" 24 #include "llvm/Analysis/TargetLibraryInfo.h" 25 #include "llvm/Analysis/ValueTracking.h" 26 #include "llvm/Analysis/VectorUtils.h" 27 #include "llvm/CodeGen/Analysis.h" 28 #include "llvm/CodeGen/FastISel.h" 29 #include "llvm/CodeGen/FunctionLoweringInfo.h" 30 #include "llvm/CodeGen/GCMetadata.h" 31 #include "llvm/CodeGen/GCStrategy.h" 32 #include "llvm/CodeGen/MachineFrameInfo.h" 33 #include "llvm/CodeGen/MachineFunction.h" 34 #include "llvm/CodeGen/MachineInstrBuilder.h" 35 #include "llvm/CodeGen/MachineJumpTableInfo.h" 36 #include "llvm/CodeGen/MachineModuleInfo.h" 37 #include "llvm/CodeGen/MachineRegisterInfo.h" 38 #include "llvm/CodeGen/SelectionDAG.h" 39 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 40 #include "llvm/CodeGen/StackMaps.h" 41 #include "llvm/CodeGen/WinEHFuncInfo.h" 42 #include "llvm/IR/CallingConv.h" 43 #include "llvm/IR/Constants.h" 44 #include "llvm/IR/DataLayout.h" 45 #include "llvm/IR/DebugInfo.h" 46 #include "llvm/IR/DerivedTypes.h" 47 #include "llvm/IR/Function.h" 48 #include "llvm/IR/GetElementPtrTypeIterator.h" 49 #include "llvm/IR/GlobalVariable.h" 50 #include "llvm/IR/InlineAsm.h" 51 #include "llvm/IR/Instructions.h" 52 #include "llvm/IR/IntrinsicInst.h" 53 #include "llvm/IR/Intrinsics.h" 54 #include "llvm/IR/LLVMContext.h" 55 #include "llvm/IR/Module.h" 56 #include "llvm/IR/Statepoint.h" 57 #include "llvm/MC/MCSymbol.h" 58 #include "llvm/Support/CommandLine.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/MathExtras.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include "llvm/Target/TargetFrameLowering.h" 64 #include "llvm/Target/TargetInstrInfo.h" 65 #include "llvm/Target/TargetIntrinsicInfo.h" 66 #include "llvm/Target/TargetLowering.h" 67 #include "llvm/Target/TargetOptions.h" 68 #include "llvm/Target/TargetSubtargetInfo.h" 69 #include <algorithm> 70 #include <utility> 71 using namespace llvm; 72 73 #define DEBUG_TYPE "isel" 74 75 /// LimitFloatPrecision - Generate low-precision inline sequences for 76 /// some float libcalls (6, 8 or 12 bits). 77 static unsigned LimitFloatPrecision; 78 79 static cl::opt<unsigned, true> 80 LimitFPPrecision("limit-float-precision", 81 cl::desc("Generate low-precision inline sequences " 82 "for some float libcalls"), 83 cl::location(LimitFloatPrecision), 84 cl::init(0)); 85 86 static cl::opt<bool> 87 EnableFMFInDAG("enable-fmf-dag", cl::init(true), cl::Hidden, 88 cl::desc("Enable fast-math-flags for DAG nodes")); 89 90 /// Minimum jump table density for normal functions. 91 static cl::opt<unsigned> 92 JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden, 93 cl::desc("Minimum density for building a jump table in " 94 "a normal function")); 95 96 /// Minimum jump table density for -Os or -Oz functions. 97 static cl::opt<unsigned> 98 OptsizeJumpTableDensity("optsize-jump-table-density", cl::init(40), cl::Hidden, 99 cl::desc("Minimum density for building a jump table in " 100 "an optsize function")); 101 102 103 // Limit the width of DAG chains. This is important in general to prevent 104 // DAG-based analysis from blowing up. For example, alias analysis and 105 // load clustering may not complete in reasonable time. It is difficult to 106 // recognize and avoid this situation within each individual analysis, and 107 // future analyses are likely to have the same behavior. Limiting DAG width is 108 // the safe approach and will be especially important with global DAGs. 109 // 110 // MaxParallelChains default is arbitrarily high to avoid affecting 111 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 112 // sequence over this should have been converted to llvm.memcpy by the 113 // frontend. It is easy to induce this behavior with .ll code such as: 114 // %buffer = alloca [4096 x i8] 115 // %data = load [4096 x i8]* %argPtr 116 // store [4096 x i8] %data, [4096 x i8]* %buffer 117 static const unsigned MaxParallelChains = 64; 118 119 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 120 const SDValue *Parts, unsigned NumParts, 121 MVT PartVT, EVT ValueVT, const Value *V); 122 123 /// getCopyFromParts - Create a value that contains the specified legal parts 124 /// combined into the value they represent. If the parts combine to a type 125 /// larger than ValueVT then AssertOp can be used to specify whether the extra 126 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 127 /// (ISD::AssertSext). 128 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 129 const SDValue *Parts, unsigned NumParts, 130 MVT PartVT, EVT ValueVT, const Value *V, 131 Optional<ISD::NodeType> AssertOp = None) { 132 if (ValueVT.isVector()) 133 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, 134 PartVT, ValueVT, V); 135 136 assert(NumParts > 0 && "No parts to assemble!"); 137 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 138 SDValue Val = Parts[0]; 139 140 if (NumParts > 1) { 141 // Assemble the value from multiple parts. 142 if (ValueVT.isInteger()) { 143 unsigned PartBits = PartVT.getSizeInBits(); 144 unsigned ValueBits = ValueVT.getSizeInBits(); 145 146 // Assemble the power of 2 part. 147 unsigned RoundParts = NumParts & (NumParts - 1) ? 148 1 << Log2_32(NumParts) : NumParts; 149 unsigned RoundBits = PartBits * RoundParts; 150 EVT RoundVT = RoundBits == ValueBits ? 151 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 152 SDValue Lo, Hi; 153 154 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 155 156 if (RoundParts > 2) { 157 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 158 PartVT, HalfVT, V); 159 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 160 RoundParts / 2, PartVT, HalfVT, V); 161 } else { 162 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 163 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 164 } 165 166 if (DAG.getDataLayout().isBigEndian()) 167 std::swap(Lo, Hi); 168 169 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 170 171 if (RoundParts < NumParts) { 172 // Assemble the trailing non-power-of-2 part. 173 unsigned OddParts = NumParts - RoundParts; 174 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 175 Hi = getCopyFromParts(DAG, DL, 176 Parts + RoundParts, OddParts, PartVT, OddVT, V); 177 178 // Combine the round and odd parts. 179 Lo = Val; 180 if (DAG.getDataLayout().isBigEndian()) 181 std::swap(Lo, Hi); 182 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 183 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 184 Hi = 185 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 186 DAG.getConstant(Lo.getValueType().getSizeInBits(), DL, 187 TLI.getPointerTy(DAG.getDataLayout()))); 188 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 189 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 190 } 191 } else if (PartVT.isFloatingPoint()) { 192 // FP split into multiple FP parts (for ppcf128) 193 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 194 "Unexpected split"); 195 SDValue Lo, Hi; 196 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 197 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 198 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 199 std::swap(Lo, Hi); 200 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 201 } else { 202 // FP split into integer parts (soft fp) 203 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 204 !PartVT.isVector() && "Unexpected split"); 205 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 206 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V); 207 } 208 } 209 210 // There is now one part, held in Val. Correct it to match ValueVT. 211 // PartEVT is the type of the register class that holds the value. 212 // ValueVT is the type of the inline asm operation. 213 EVT PartEVT = Val.getValueType(); 214 215 if (PartEVT == ValueVT) 216 return Val; 217 218 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 219 ValueVT.bitsLT(PartEVT)) { 220 // For an FP value in an integer part, we need to truncate to the right 221 // width first. 222 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 223 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 224 } 225 226 // Handle types that have the same size. 227 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 228 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 229 230 // Handle types with different sizes. 231 if (PartEVT.isInteger() && ValueVT.isInteger()) { 232 if (ValueVT.bitsLT(PartEVT)) { 233 // For a truncate, see if we have any information to 234 // indicate whether the truncated bits will always be 235 // zero or sign-extension. 236 if (AssertOp.hasValue()) 237 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 238 DAG.getValueType(ValueVT)); 239 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 240 } 241 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 242 } 243 244 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 245 // FP_ROUND's are always exact here. 246 if (ValueVT.bitsLT(Val.getValueType())) 247 return DAG.getNode( 248 ISD::FP_ROUND, DL, ValueVT, Val, 249 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 250 251 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 252 } 253 254 llvm_unreachable("Unknown mismatch!"); 255 } 256 257 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 258 const Twine &ErrMsg) { 259 const Instruction *I = dyn_cast_or_null<Instruction>(V); 260 if (!V) 261 return Ctx.emitError(ErrMsg); 262 263 const char *AsmError = ", possible invalid constraint for vector type"; 264 if (const CallInst *CI = dyn_cast<CallInst>(I)) 265 if (isa<InlineAsm>(CI->getCalledValue())) 266 return Ctx.emitError(I, ErrMsg + AsmError); 267 268 return Ctx.emitError(I, ErrMsg); 269 } 270 271 /// getCopyFromPartsVector - Create a value that contains the specified legal 272 /// parts combined into the value they represent. If the parts combine to a 273 /// type larger than ValueVT then AssertOp can be used to specify whether the 274 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 275 /// ValueVT (ISD::AssertSext). 276 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 277 const SDValue *Parts, unsigned NumParts, 278 MVT PartVT, EVT ValueVT, const Value *V) { 279 assert(ValueVT.isVector() && "Not a vector value"); 280 assert(NumParts > 0 && "No parts to assemble!"); 281 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 282 SDValue Val = Parts[0]; 283 284 // Handle a multi-element vector. 285 if (NumParts > 1) { 286 EVT IntermediateVT; 287 MVT RegisterVT; 288 unsigned NumIntermediates; 289 unsigned NumRegs = 290 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 291 NumIntermediates, RegisterVT); 292 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 293 NumParts = NumRegs; // Silence a compiler warning. 294 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 295 assert(RegisterVT.getSizeInBits() == 296 Parts[0].getSimpleValueType().getSizeInBits() && 297 "Part type sizes don't match!"); 298 299 // Assemble the parts into intermediate operands. 300 SmallVector<SDValue, 8> Ops(NumIntermediates); 301 if (NumIntermediates == NumParts) { 302 // If the register was not expanded, truncate or copy the value, 303 // as appropriate. 304 for (unsigned i = 0; i != NumParts; ++i) 305 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 306 PartVT, IntermediateVT, V); 307 } else if (NumParts > 0) { 308 // If the intermediate type was expanded, build the intermediate 309 // operands from the parts. 310 assert(NumParts % NumIntermediates == 0 && 311 "Must expand into a divisible number of parts!"); 312 unsigned Factor = NumParts / NumIntermediates; 313 for (unsigned i = 0; i != NumIntermediates; ++i) 314 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 315 PartVT, IntermediateVT, V); 316 } 317 318 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 319 // intermediate operands. 320 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 321 : ISD::BUILD_VECTOR, 322 DL, ValueVT, Ops); 323 } 324 325 // There is now one part, held in Val. Correct it to match ValueVT. 326 EVT PartEVT = Val.getValueType(); 327 328 if (PartEVT == ValueVT) 329 return Val; 330 331 if (PartEVT.isVector()) { 332 // If the element type of the source/dest vectors are the same, but the 333 // parts vector has more elements than the value vector, then we have a 334 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 335 // elements we want. 336 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 337 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 338 "Cannot narrow, it would be a lossy transformation"); 339 return DAG.getNode( 340 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 341 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 342 } 343 344 // Vector/Vector bitcast. 345 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 346 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 347 348 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 349 "Cannot handle this kind of promotion"); 350 // Promoted vector extract 351 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 352 353 } 354 355 // Trivial bitcast if the types are the same size and the destination 356 // vector type is legal. 357 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 358 TLI.isTypeLegal(ValueVT)) 359 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 360 361 // Handle cases such as i8 -> <1 x i1> 362 if (ValueVT.getVectorNumElements() != 1) { 363 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 364 "non-trivial scalar-to-vector conversion"); 365 return DAG.getUNDEF(ValueVT); 366 } 367 368 if (ValueVT.getVectorNumElements() == 1 && 369 ValueVT.getVectorElementType() != PartEVT) 370 Val = DAG.getAnyExtOrTrunc(Val, DL, ValueVT.getScalarType()); 371 372 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val); 373 } 374 375 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 376 SDValue Val, SDValue *Parts, unsigned NumParts, 377 MVT PartVT, const Value *V); 378 379 /// getCopyToParts - Create a series of nodes that contain the specified value 380 /// split into legal parts. If the parts contain more bits than Val, then, for 381 /// integers, ExtendKind can be used to specify how to generate the extra bits. 382 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 383 SDValue *Parts, unsigned NumParts, MVT PartVT, 384 const Value *V, 385 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 386 EVT ValueVT = Val.getValueType(); 387 388 // Handle the vector case separately. 389 if (ValueVT.isVector()) 390 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V); 391 392 unsigned PartBits = PartVT.getSizeInBits(); 393 unsigned OrigNumParts = NumParts; 394 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 395 "Copying to an illegal type!"); 396 397 if (NumParts == 0) 398 return; 399 400 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 401 EVT PartEVT = PartVT; 402 if (PartEVT == ValueVT) { 403 assert(NumParts == 1 && "No-op copy with multiple parts!"); 404 Parts[0] = Val; 405 return; 406 } 407 408 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 409 // If the parts cover more bits than the value has, promote the value. 410 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 411 assert(NumParts == 1 && "Do not know what to promote to!"); 412 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 413 } else { 414 if (ValueVT.isFloatingPoint()) { 415 // FP values need to be bitcast, then extended if they are being put 416 // into a larger container. 417 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 418 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 } 420 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 421 ValueVT.isInteger() && 422 "Unknown mismatch!"); 423 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 424 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 425 if (PartVT == MVT::x86mmx) 426 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 427 } 428 } else if (PartBits == ValueVT.getSizeInBits()) { 429 // Different types of the same size. 430 assert(NumParts == 1 && PartEVT != ValueVT); 431 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 432 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 433 // If the parts cover less bits than value has, truncate the value. 434 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 435 ValueVT.isInteger() && 436 "Unknown mismatch!"); 437 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 438 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 439 if (PartVT == MVT::x86mmx) 440 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 441 } 442 443 // The value may have changed - recompute ValueVT. 444 ValueVT = Val.getValueType(); 445 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 446 "Failed to tile the value with PartVT!"); 447 448 if (NumParts == 1) { 449 if (PartEVT != ValueVT) { 450 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 451 "scalar-to-vector conversion failed"); 452 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 453 } 454 455 Parts[0] = Val; 456 return; 457 } 458 459 // Expand the value into multiple parts. 460 if (NumParts & (NumParts - 1)) { 461 // The number of parts is not a power of 2. Split off and copy the tail. 462 assert(PartVT.isInteger() && ValueVT.isInteger() && 463 "Do not know what to expand to!"); 464 unsigned RoundParts = 1 << Log2_32(NumParts); 465 unsigned RoundBits = RoundParts * PartBits; 466 unsigned OddParts = NumParts - RoundParts; 467 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 468 DAG.getIntPtrConstant(RoundBits, DL)); 469 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V); 470 471 if (DAG.getDataLayout().isBigEndian()) 472 // The odd parts were reversed by getCopyToParts - unreverse them. 473 std::reverse(Parts + RoundParts, Parts + NumParts); 474 475 NumParts = RoundParts; 476 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 477 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 478 } 479 480 // The number of parts is a power of 2. Repeatedly bisect the value using 481 // EXTRACT_ELEMENT. 482 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 483 EVT::getIntegerVT(*DAG.getContext(), 484 ValueVT.getSizeInBits()), 485 Val); 486 487 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 488 for (unsigned i = 0; i < NumParts; i += StepSize) { 489 unsigned ThisBits = StepSize * PartBits / 2; 490 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 491 SDValue &Part0 = Parts[i]; 492 SDValue &Part1 = Parts[i+StepSize/2]; 493 494 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 495 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 496 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 497 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 498 499 if (ThisBits == PartBits && ThisVT != PartVT) { 500 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 501 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 502 } 503 } 504 } 505 506 if (DAG.getDataLayout().isBigEndian()) 507 std::reverse(Parts, Parts + OrigNumParts); 508 } 509 510 511 /// getCopyToPartsVector - Create a series of nodes that contain the specified 512 /// value split into legal parts. 513 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 514 SDValue Val, SDValue *Parts, unsigned NumParts, 515 MVT PartVT, const Value *V) { 516 EVT ValueVT = Val.getValueType(); 517 assert(ValueVT.isVector() && "Not a vector"); 518 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 519 520 if (NumParts == 1) { 521 EVT PartEVT = PartVT; 522 if (PartEVT == ValueVT) { 523 // Nothing to do. 524 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 525 // Bitconvert vector->vector case. 526 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 527 } else if (PartVT.isVector() && 528 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() && 529 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { 530 EVT ElementVT = PartVT.getVectorElementType(); 531 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 532 // undef elements. 533 SmallVector<SDValue, 16> Ops; 534 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) 535 Ops.push_back(DAG.getNode( 536 ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val, 537 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())))); 538 539 for (unsigned i = ValueVT.getVectorNumElements(), 540 e = PartVT.getVectorNumElements(); i != e; ++i) 541 Ops.push_back(DAG.getUNDEF(ElementVT)); 542 543 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops); 544 545 // FIXME: Use CONCAT for 2x -> 4x. 546 547 //SDValue UndefElts = DAG.getUNDEF(VectorTy); 548 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); 549 } else if (PartVT.isVector() && 550 PartEVT.getVectorElementType().bitsGE( 551 ValueVT.getVectorElementType()) && 552 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 553 554 // Promoted vector extract 555 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 556 } else{ 557 // Vector -> scalar conversion. 558 assert(ValueVT.getVectorNumElements() == 1 && 559 "Only trivial vector-to-scalar conversions should get here!"); 560 Val = DAG.getNode( 561 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 562 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 563 564 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 565 } 566 567 Parts[0] = Val; 568 return; 569 } 570 571 // Handle a multi-element vector. 572 EVT IntermediateVT; 573 MVT RegisterVT; 574 unsigned NumIntermediates; 575 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, 576 IntermediateVT, 577 NumIntermediates, RegisterVT); 578 unsigned NumElements = ValueVT.getVectorNumElements(); 579 580 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 581 NumParts = NumRegs; // Silence a compiler warning. 582 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 583 584 // Split the vector into intermediate operands. 585 SmallVector<SDValue, 8> Ops(NumIntermediates); 586 for (unsigned i = 0; i != NumIntermediates; ++i) { 587 if (IntermediateVT.isVector()) 588 Ops[i] = 589 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 590 DAG.getConstant(i * (NumElements / NumIntermediates), DL, 591 TLI.getVectorIdxTy(DAG.getDataLayout()))); 592 else 593 Ops[i] = DAG.getNode( 594 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 595 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 596 } 597 598 // Split the intermediate operands into legal parts. 599 if (NumParts == NumIntermediates) { 600 // If the register was not expanded, promote or copy the value, 601 // as appropriate. 602 for (unsigned i = 0; i != NumParts; ++i) 603 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V); 604 } else if (NumParts > 0) { 605 // If the intermediate type was expanded, split each the value into 606 // legal parts. 607 assert(NumIntermediates != 0 && "division by zero"); 608 assert(NumParts % NumIntermediates == 0 && 609 "Must expand into a divisible number of parts!"); 610 unsigned Factor = NumParts / NumIntermediates; 611 for (unsigned i = 0; i != NumIntermediates; ++i) 612 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V); 613 } 614 } 615 616 RegsForValue::RegsForValue() {} 617 618 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 619 EVT valuevt) 620 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {} 621 622 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 623 const DataLayout &DL, unsigned Reg, Type *Ty) { 624 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 625 626 for (EVT ValueVT : ValueVTs) { 627 unsigned NumRegs = TLI.getNumRegisters(Context, ValueVT); 628 MVT RegisterVT = TLI.getRegisterType(Context, ValueVT); 629 for (unsigned i = 0; i != NumRegs; ++i) 630 Regs.push_back(Reg + i); 631 RegVTs.push_back(RegisterVT); 632 Reg += NumRegs; 633 } 634 } 635 636 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 637 /// this value and returns the result as a ValueVT value. This uses 638 /// Chain/Flag as the input and updates them for the output Chain/Flag. 639 /// If the Flag pointer is NULL, no flag is used. 640 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 641 FunctionLoweringInfo &FuncInfo, 642 const SDLoc &dl, SDValue &Chain, 643 SDValue *Flag, const Value *V) const { 644 // A Value with type {} or [0 x %t] needs no registers. 645 if (ValueVTs.empty()) 646 return SDValue(); 647 648 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 649 650 // Assemble the legal parts into the final values. 651 SmallVector<SDValue, 4> Values(ValueVTs.size()); 652 SmallVector<SDValue, 8> Parts; 653 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 654 // Copy the legal parts from the registers. 655 EVT ValueVT = ValueVTs[Value]; 656 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 657 MVT RegisterVT = RegVTs[Value]; 658 659 Parts.resize(NumRegs); 660 for (unsigned i = 0; i != NumRegs; ++i) { 661 SDValue P; 662 if (!Flag) { 663 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 664 } else { 665 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 666 *Flag = P.getValue(2); 667 } 668 669 Chain = P.getValue(1); 670 Parts[i] = P; 671 672 // If the source register was virtual and if we know something about it, 673 // add an assert node. 674 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 675 !RegisterVT.isInteger() || RegisterVT.isVector()) 676 continue; 677 678 const FunctionLoweringInfo::LiveOutInfo *LOI = 679 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 680 if (!LOI) 681 continue; 682 683 unsigned RegSize = RegisterVT.getSizeInBits(); 684 unsigned NumSignBits = LOI->NumSignBits; 685 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes(); 686 687 if (NumZeroBits == RegSize) { 688 // The current value is a zero. 689 // Explicitly express that as it would be easier for 690 // optimizations to kick in. 691 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 692 continue; 693 } 694 695 // FIXME: We capture more information than the dag can represent. For 696 // now, just use the tightest assertzext/assertsext possible. 697 bool isSExt = true; 698 EVT FromVT(MVT::Other); 699 if (NumSignBits == RegSize) { 700 isSExt = true; // ASSERT SEXT 1 701 FromVT = MVT::i1; 702 } else if (NumZeroBits >= RegSize - 1) { 703 isSExt = false; // ASSERT ZEXT 1 704 FromVT = MVT::i1; 705 } else if (NumSignBits > RegSize - 8) { 706 isSExt = true; // ASSERT SEXT 8 707 FromVT = MVT::i8; 708 } else if (NumZeroBits >= RegSize - 8) { 709 isSExt = false; // ASSERT ZEXT 8 710 FromVT = MVT::i8; 711 } else if (NumSignBits > RegSize - 16) { 712 isSExt = true; // ASSERT SEXT 16 713 FromVT = MVT::i16; 714 } else if (NumZeroBits >= RegSize - 16) { 715 isSExt = false; // ASSERT ZEXT 16 716 FromVT = MVT::i16; 717 } else if (NumSignBits > RegSize - 32) { 718 isSExt = true; // ASSERT SEXT 32 719 FromVT = MVT::i32; 720 } else if (NumZeroBits >= RegSize - 32) { 721 isSExt = false; // ASSERT ZEXT 32 722 FromVT = MVT::i32; 723 } else { 724 continue; 725 } 726 // Add an assertion node. 727 assert(FromVT != MVT::Other); 728 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 729 RegisterVT, P, DAG.getValueType(FromVT)); 730 } 731 732 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 733 NumRegs, RegisterVT, ValueVT, V); 734 Part += NumRegs; 735 Parts.clear(); 736 } 737 738 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 739 } 740 741 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 742 /// specified value into the registers specified by this object. This uses 743 /// Chain/Flag as the input and updates them for the output Chain/Flag. 744 /// If the Flag pointer is NULL, no flag is used. 745 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 746 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 747 const Value *V, 748 ISD::NodeType PreferredExtendType) const { 749 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 750 ISD::NodeType ExtendKind = PreferredExtendType; 751 752 // Get the list of the values's legal parts. 753 unsigned NumRegs = Regs.size(); 754 SmallVector<SDValue, 8> Parts(NumRegs); 755 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 756 EVT ValueVT = ValueVTs[Value]; 757 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 758 MVT RegisterVT = RegVTs[Value]; 759 760 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 761 ExtendKind = ISD::ZERO_EXTEND; 762 763 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), 764 &Parts[Part], NumParts, RegisterVT, V, ExtendKind); 765 Part += NumParts; 766 } 767 768 // Copy the parts into the registers. 769 SmallVector<SDValue, 8> Chains(NumRegs); 770 for (unsigned i = 0; i != NumRegs; ++i) { 771 SDValue Part; 772 if (!Flag) { 773 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 774 } else { 775 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 776 *Flag = Part.getValue(1); 777 } 778 779 Chains[i] = Part.getValue(0); 780 } 781 782 if (NumRegs == 1 || Flag) 783 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 784 // flagged to it. That is the CopyToReg nodes and the user are considered 785 // a single scheduling unit. If we create a TokenFactor and return it as 786 // chain, then the TokenFactor is both a predecessor (operand) of the 787 // user as well as a successor (the TF operands are flagged to the user). 788 // c1, f1 = CopyToReg 789 // c2, f2 = CopyToReg 790 // c3 = TokenFactor c1, c2 791 // ... 792 // = op c3, ..., f2 793 Chain = Chains[NumRegs-1]; 794 else 795 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 796 } 797 798 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 799 /// operand list. This adds the code marker and includes the number of 800 /// values added into it. 801 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 802 unsigned MatchingIdx, const SDLoc &dl, 803 SelectionDAG &DAG, 804 std::vector<SDValue> &Ops) const { 805 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 806 807 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 808 if (HasMatching) 809 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 810 else if (!Regs.empty() && 811 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 812 // Put the register class of the virtual registers in the flag word. That 813 // way, later passes can recompute register class constraints for inline 814 // assembly as well as normal instructions. 815 // Don't do this for tied operands that can use the regclass information 816 // from the def. 817 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 818 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 819 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 820 } 821 822 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 823 Ops.push_back(Res); 824 825 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 826 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 827 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 828 MVT RegisterVT = RegVTs[Value]; 829 for (unsigned i = 0; i != NumRegs; ++i) { 830 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 831 unsigned TheReg = Regs[Reg++]; 832 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 833 834 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) { 835 // If we clobbered the stack pointer, MFI should know about it. 836 assert(DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()); 837 } 838 } 839 } 840 } 841 842 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa, 843 const TargetLibraryInfo *li) { 844 AA = &aa; 845 GFI = gfi; 846 LibInfo = li; 847 DL = &DAG.getDataLayout(); 848 Context = DAG.getContext(); 849 LPadToCallSiteMap.clear(); 850 } 851 852 /// clear - Clear out the current SelectionDAG and the associated 853 /// state and prepare this SelectionDAGBuilder object to be used 854 /// for a new block. This doesn't clear out information about 855 /// additional blocks that are needed to complete switch lowering 856 /// or PHI node updating; that information is cleared out as it is 857 /// consumed. 858 void SelectionDAGBuilder::clear() { 859 NodeMap.clear(); 860 UnusedArgNodeMap.clear(); 861 PendingLoads.clear(); 862 PendingExports.clear(); 863 CurInst = nullptr; 864 HasTailCall = false; 865 SDNodeOrder = LowestSDNodeOrder; 866 StatepointLowering.clear(); 867 } 868 869 /// clearDanglingDebugInfo - Clear the dangling debug information 870 /// map. This function is separated from the clear so that debug 871 /// information that is dangling in a basic block can be properly 872 /// resolved in a different basic block. This allows the 873 /// SelectionDAG to resolve dangling debug information attached 874 /// to PHI nodes. 875 void SelectionDAGBuilder::clearDanglingDebugInfo() { 876 DanglingDebugInfoMap.clear(); 877 } 878 879 /// getRoot - Return the current virtual root of the Selection DAG, 880 /// flushing any PendingLoad items. This must be done before emitting 881 /// a store or any other node that may need to be ordered after any 882 /// prior load instructions. 883 /// 884 SDValue SelectionDAGBuilder::getRoot() { 885 if (PendingLoads.empty()) 886 return DAG.getRoot(); 887 888 if (PendingLoads.size() == 1) { 889 SDValue Root = PendingLoads[0]; 890 DAG.setRoot(Root); 891 PendingLoads.clear(); 892 return Root; 893 } 894 895 // Otherwise, we have to make a token factor node. 896 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 897 PendingLoads); 898 PendingLoads.clear(); 899 DAG.setRoot(Root); 900 return Root; 901 } 902 903 /// getControlRoot - Similar to getRoot, but instead of flushing all the 904 /// PendingLoad items, flush all the PendingExports items. It is necessary 905 /// to do this before emitting a terminator instruction. 906 /// 907 SDValue SelectionDAGBuilder::getControlRoot() { 908 SDValue Root = DAG.getRoot(); 909 910 if (PendingExports.empty()) 911 return Root; 912 913 // Turn all of the CopyToReg chains into one factored node. 914 if (Root.getOpcode() != ISD::EntryToken) { 915 unsigned i = 0, e = PendingExports.size(); 916 for (; i != e; ++i) { 917 assert(PendingExports[i].getNode()->getNumOperands() > 1); 918 if (PendingExports[i].getNode()->getOperand(0) == Root) 919 break; // Don't add the root if we already indirectly depend on it. 920 } 921 922 if (i == e) 923 PendingExports.push_back(Root); 924 } 925 926 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 927 PendingExports); 928 PendingExports.clear(); 929 DAG.setRoot(Root); 930 return Root; 931 } 932 933 /// Copy swift error to the final virtual register at end of a basic block, as 934 /// specified by SwiftErrorWorklist, if necessary. 935 static void copySwiftErrorsToFinalVRegs(SelectionDAGBuilder &SDB) { 936 const TargetLowering &TLI = SDB.DAG.getTargetLoweringInfo(); 937 if (!TLI.supportSwiftError()) 938 return; 939 940 if (!SDB.FuncInfo.SwiftErrorWorklist.count(SDB.FuncInfo.MBB)) 941 return; 942 943 // Go through entries in SwiftErrorWorklist, and create copy as necessary. 944 FunctionLoweringInfo::SwiftErrorVRegs &WorklistEntry = 945 SDB.FuncInfo.SwiftErrorWorklist[SDB.FuncInfo.MBB]; 946 FunctionLoweringInfo::SwiftErrorVRegs &MapEntry = 947 SDB.FuncInfo.SwiftErrorMap[SDB.FuncInfo.MBB]; 948 for (unsigned I = 0, E = WorklistEntry.size(); I < E; I++) { 949 unsigned WorkReg = WorklistEntry[I]; 950 951 // Find the swifterror virtual register for the value in SwiftErrorMap. 952 unsigned MapReg = MapEntry[I]; 953 assert(TargetRegisterInfo::isVirtualRegister(MapReg) && 954 "Entries in SwiftErrorMap should be virtual registers"); 955 956 if (WorkReg == MapReg) 957 continue; 958 959 // Create copy from SwiftErrorMap to SwiftWorklist. 960 auto &DL = SDB.DAG.getDataLayout(); 961 SDValue CopyNode = SDB.DAG.getCopyToReg( 962 SDB.getRoot(), SDB.getCurSDLoc(), WorkReg, 963 SDB.DAG.getRegister(MapReg, EVT(TLI.getPointerTy(DL)))); 964 MapEntry[I] = WorkReg; 965 SDB.DAG.setRoot(CopyNode); 966 } 967 } 968 969 void SelectionDAGBuilder::visit(const Instruction &I) { 970 // Set up outgoing PHI node register values before emitting the terminator. 971 if (isa<TerminatorInst>(&I)) { 972 copySwiftErrorsToFinalVRegs(*this); 973 HandlePHINodesInSuccessorBlocks(I.getParent()); 974 } 975 976 ++SDNodeOrder; 977 978 CurInst = &I; 979 980 visit(I.getOpcode(), I); 981 982 if (!isa<TerminatorInst>(&I) && !HasTailCall && 983 !isStatepoint(&I)) // statepoints handle their exports internally 984 CopyToExportRegsIfNeeded(&I); 985 986 CurInst = nullptr; 987 } 988 989 void SelectionDAGBuilder::visitPHI(const PHINode &) { 990 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 991 } 992 993 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 994 // Note: this doesn't use InstVisitor, because it has to work with 995 // ConstantExpr's in addition to instructions. 996 switch (Opcode) { 997 default: llvm_unreachable("Unknown instruction type encountered!"); 998 // Build the switch statement using the Instruction.def file. 999 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1000 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1001 #include "llvm/IR/Instruction.def" 1002 } 1003 } 1004 1005 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1006 // generate the debug data structures now that we've seen its definition. 1007 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1008 SDValue Val) { 1009 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V]; 1010 if (DDI.getDI()) { 1011 const DbgValueInst *DI = DDI.getDI(); 1012 DebugLoc dl = DDI.getdl(); 1013 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1014 DILocalVariable *Variable = DI->getVariable(); 1015 DIExpression *Expr = DI->getExpression(); 1016 assert(Variable->isValidLocationForIntrinsic(dl) && 1017 "Expected inlined-at fields to agree"); 1018 uint64_t Offset = DI->getOffset(); 1019 SDDbgValue *SDV; 1020 if (Val.getNode()) { 1021 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, false, 1022 Val)) { 1023 SDV = getDbgValue(Val, Variable, Expr, Offset, dl, DbgSDNodeOrder); 1024 DAG.AddDbgValue(SDV, Val.getNode(), false); 1025 } 1026 } else 1027 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1028 DanglingDebugInfoMap[V] = DanglingDebugInfo(); 1029 } 1030 } 1031 1032 /// getCopyFromRegs - If there was virtual register allocated for the value V 1033 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1034 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1035 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1036 SDValue Result; 1037 1038 if (It != FuncInfo.ValueMap.end()) { 1039 unsigned InReg = It->second; 1040 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1041 DAG.getDataLayout(), InReg, Ty); 1042 SDValue Chain = DAG.getEntryNode(); 1043 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1044 resolveDanglingDebugInfo(V, Result); 1045 } 1046 1047 return Result; 1048 } 1049 1050 /// getValue - Return an SDValue for the given Value. 1051 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1052 // If we already have an SDValue for this value, use it. It's important 1053 // to do this first, so that we don't create a CopyFromReg if we already 1054 // have a regular SDValue. 1055 SDValue &N = NodeMap[V]; 1056 if (N.getNode()) return N; 1057 1058 // If there's a virtual register allocated and initialized for this 1059 // value, use it. 1060 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1061 return copyFromReg; 1062 1063 // Otherwise create a new SDValue and remember it. 1064 SDValue Val = getValueImpl(V); 1065 NodeMap[V] = Val; 1066 resolveDanglingDebugInfo(V, Val); 1067 return Val; 1068 } 1069 1070 // Return true if SDValue exists for the given Value 1071 bool SelectionDAGBuilder::findValue(const Value *V) const { 1072 return (NodeMap.find(V) != NodeMap.end()) || 1073 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1074 } 1075 1076 /// getNonRegisterValue - Return an SDValue for the given Value, but 1077 /// don't look in FuncInfo.ValueMap for a virtual register. 1078 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1079 // If we already have an SDValue for this value, use it. 1080 SDValue &N = NodeMap[V]; 1081 if (N.getNode()) { 1082 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1083 // Remove the debug location from the node as the node is about to be used 1084 // in a location which may differ from the original debug location. This 1085 // is relevant to Constant and ConstantFP nodes because they can appear 1086 // as constant expressions inside PHI nodes. 1087 N->setDebugLoc(DebugLoc()); 1088 } 1089 return N; 1090 } 1091 1092 // Otherwise create a new SDValue and remember it. 1093 SDValue Val = getValueImpl(V); 1094 NodeMap[V] = Val; 1095 resolveDanglingDebugInfo(V, Val); 1096 return Val; 1097 } 1098 1099 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1100 /// Create an SDValue for the given value. 1101 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1102 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1103 1104 if (const Constant *C = dyn_cast<Constant>(V)) { 1105 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1106 1107 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1108 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1109 1110 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1111 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1112 1113 if (isa<ConstantPointerNull>(C)) { 1114 unsigned AS = V->getType()->getPointerAddressSpace(); 1115 return DAG.getConstant(0, getCurSDLoc(), 1116 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1117 } 1118 1119 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1120 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1121 1122 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1123 return DAG.getUNDEF(VT); 1124 1125 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1126 visit(CE->getOpcode(), *CE); 1127 SDValue N1 = NodeMap[V]; 1128 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1129 return N1; 1130 } 1131 1132 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1133 SmallVector<SDValue, 4> Constants; 1134 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1135 OI != OE; ++OI) { 1136 SDNode *Val = getValue(*OI).getNode(); 1137 // If the operand is an empty aggregate, there are no values. 1138 if (!Val) continue; 1139 // Add each leaf value from the operand to the Constants list 1140 // to form a flattened list of all the values. 1141 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1142 Constants.push_back(SDValue(Val, i)); 1143 } 1144 1145 return DAG.getMergeValues(Constants, getCurSDLoc()); 1146 } 1147 1148 if (const ConstantDataSequential *CDS = 1149 dyn_cast<ConstantDataSequential>(C)) { 1150 SmallVector<SDValue, 4> Ops; 1151 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1152 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1153 // Add each leaf value from the operand to the Constants list 1154 // to form a flattened list of all the values. 1155 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1156 Ops.push_back(SDValue(Val, i)); 1157 } 1158 1159 if (isa<ArrayType>(CDS->getType())) 1160 return DAG.getMergeValues(Ops, getCurSDLoc()); 1161 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), 1162 VT, Ops); 1163 } 1164 1165 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1166 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1167 "Unknown struct or array constant!"); 1168 1169 SmallVector<EVT, 4> ValueVTs; 1170 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1171 unsigned NumElts = ValueVTs.size(); 1172 if (NumElts == 0) 1173 return SDValue(); // empty struct 1174 SmallVector<SDValue, 4> Constants(NumElts); 1175 for (unsigned i = 0; i != NumElts; ++i) { 1176 EVT EltVT = ValueVTs[i]; 1177 if (isa<UndefValue>(C)) 1178 Constants[i] = DAG.getUNDEF(EltVT); 1179 else if (EltVT.isFloatingPoint()) 1180 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1181 else 1182 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1183 } 1184 1185 return DAG.getMergeValues(Constants, getCurSDLoc()); 1186 } 1187 1188 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1189 return DAG.getBlockAddress(BA, VT); 1190 1191 VectorType *VecTy = cast<VectorType>(V->getType()); 1192 unsigned NumElements = VecTy->getNumElements(); 1193 1194 // Now that we know the number and type of the elements, get that number of 1195 // elements into the Ops array based on what kind of constant it is. 1196 SmallVector<SDValue, 16> Ops; 1197 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1198 for (unsigned i = 0; i != NumElements; ++i) 1199 Ops.push_back(getValue(CV->getOperand(i))); 1200 } else { 1201 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1202 EVT EltVT = 1203 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1204 1205 SDValue Op; 1206 if (EltVT.isFloatingPoint()) 1207 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1208 else 1209 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1210 Ops.assign(NumElements, Op); 1211 } 1212 1213 // Create a BUILD_VECTOR node. 1214 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops); 1215 } 1216 1217 // If this is a static alloca, generate it as the frameindex instead of 1218 // computation. 1219 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1220 DenseMap<const AllocaInst*, int>::iterator SI = 1221 FuncInfo.StaticAllocaMap.find(AI); 1222 if (SI != FuncInfo.StaticAllocaMap.end()) 1223 return DAG.getFrameIndex(SI->second, 1224 TLI.getPointerTy(DAG.getDataLayout())); 1225 } 1226 1227 // If this is an instruction which fast-isel has deferred, select it now. 1228 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1229 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1230 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1231 Inst->getType()); 1232 SDValue Chain = DAG.getEntryNode(); 1233 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1234 } 1235 1236 llvm_unreachable("Can't get register for value!"); 1237 } 1238 1239 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1240 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1241 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1242 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1243 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1244 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1245 if (IsMSVCCXX || IsCoreCLR) 1246 CatchPadMBB->setIsEHFuncletEntry(); 1247 1248 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot())); 1249 } 1250 1251 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1252 // Update machine-CFG edge. 1253 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1254 FuncInfo.MBB->addSuccessor(TargetMBB); 1255 1256 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1257 bool IsSEH = isAsynchronousEHPersonality(Pers); 1258 if (IsSEH) { 1259 // If this is not a fall-through branch or optimizations are switched off, 1260 // emit the branch. 1261 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1262 TM.getOptLevel() == CodeGenOpt::None) 1263 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1264 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1265 return; 1266 } 1267 1268 // Figure out the funclet membership for the catchret's successor. 1269 // This will be used by the FuncletLayout pass to determine how to order the 1270 // BB's. 1271 // A 'catchret' returns to the outer scope's color. 1272 Value *ParentPad = I.getCatchSwitchParentPad(); 1273 const BasicBlock *SuccessorColor; 1274 if (isa<ConstantTokenNone>(ParentPad)) 1275 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1276 else 1277 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1278 assert(SuccessorColor && "No parent funclet for catchret!"); 1279 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1280 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1281 1282 // Create the terminator node. 1283 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1284 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1285 DAG.getBasicBlock(SuccessorColorMBB)); 1286 DAG.setRoot(Ret); 1287 } 1288 1289 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1290 // Don't emit any special code for the cleanuppad instruction. It just marks 1291 // the start of a funclet. 1292 FuncInfo.MBB->setIsEHFuncletEntry(); 1293 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1294 } 1295 1296 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1297 /// many places it could ultimately go. In the IR, we have a single unwind 1298 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1299 /// This function skips over imaginary basic blocks that hold catchswitch 1300 /// instructions, and finds all the "real" machine 1301 /// basic block destinations. As those destinations may not be successors of 1302 /// EHPadBB, here we also calculate the edge probability to those destinations. 1303 /// The passed-in Prob is the edge probability to EHPadBB. 1304 static void findUnwindDestinations( 1305 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1306 BranchProbability Prob, 1307 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1308 &UnwindDests) { 1309 EHPersonality Personality = 1310 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1311 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1312 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1313 1314 while (EHPadBB) { 1315 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1316 BasicBlock *NewEHPadBB = nullptr; 1317 if (isa<LandingPadInst>(Pad)) { 1318 // Stop on landingpads. They are not funclets. 1319 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1320 break; 1321 } else if (isa<CleanupPadInst>(Pad)) { 1322 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1323 // personalities. 1324 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1325 UnwindDests.back().first->setIsEHFuncletEntry(); 1326 break; 1327 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1328 // Add the catchpad handlers to the possible destinations. 1329 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1330 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1331 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1332 if (IsMSVCCXX || IsCoreCLR) 1333 UnwindDests.back().first->setIsEHFuncletEntry(); 1334 } 1335 NewEHPadBB = CatchSwitch->getUnwindDest(); 1336 } else { 1337 continue; 1338 } 1339 1340 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1341 if (BPI && NewEHPadBB) 1342 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1343 EHPadBB = NewEHPadBB; 1344 } 1345 } 1346 1347 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1348 // Update successor info. 1349 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1350 auto UnwindDest = I.getUnwindDest(); 1351 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1352 BranchProbability UnwindDestProb = 1353 (BPI && UnwindDest) 1354 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1355 : BranchProbability::getZero(); 1356 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1357 for (auto &UnwindDest : UnwindDests) { 1358 UnwindDest.first->setIsEHPad(); 1359 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1360 } 1361 FuncInfo.MBB->normalizeSuccProbs(); 1362 1363 // Create the terminator node. 1364 SDValue Ret = 1365 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1366 DAG.setRoot(Ret); 1367 } 1368 1369 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1370 report_fatal_error("visitCatchSwitch not yet implemented!"); 1371 } 1372 1373 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1374 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1375 auto &DL = DAG.getDataLayout(); 1376 SDValue Chain = getControlRoot(); 1377 SmallVector<ISD::OutputArg, 8> Outs; 1378 SmallVector<SDValue, 8> OutVals; 1379 1380 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1381 // lower 1382 // 1383 // %val = call <ty> @llvm.experimental.deoptimize() 1384 // ret <ty> %val 1385 // 1386 // differently. 1387 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1388 LowerDeoptimizingReturn(); 1389 return; 1390 } 1391 1392 if (!FuncInfo.CanLowerReturn) { 1393 unsigned DemoteReg = FuncInfo.DemoteRegister; 1394 const Function *F = I.getParent()->getParent(); 1395 1396 // Emit a store of the return value through the virtual register. 1397 // Leave Outs empty so that LowerReturn won't try to load return 1398 // registers the usual way. 1399 SmallVector<EVT, 1> PtrValueVTs; 1400 ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()), 1401 PtrValueVTs); 1402 1403 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1404 DemoteReg, PtrValueVTs[0]); 1405 SDValue RetOp = getValue(I.getOperand(0)); 1406 1407 SmallVector<EVT, 4> ValueVTs; 1408 SmallVector<uint64_t, 4> Offsets; 1409 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1410 unsigned NumValues = ValueVTs.size(); 1411 1412 // An aggregate return value cannot wrap around the address space, so 1413 // offsets to its parts don't wrap either. 1414 SDNodeFlags Flags; 1415 Flags.setNoUnsignedWrap(true); 1416 1417 SmallVector<SDValue, 4> Chains(NumValues); 1418 for (unsigned i = 0; i != NumValues; ++i) { 1419 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), 1420 RetPtr.getValueType(), RetPtr, 1421 DAG.getIntPtrConstant(Offsets[i], 1422 getCurSDLoc()), 1423 &Flags); 1424 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), 1425 SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1426 // FIXME: better loc info would be nice. 1427 Add, MachinePointerInfo()); 1428 } 1429 1430 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1431 MVT::Other, Chains); 1432 } else if (I.getNumOperands() != 0) { 1433 SmallVector<EVT, 4> ValueVTs; 1434 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1435 unsigned NumValues = ValueVTs.size(); 1436 if (NumValues) { 1437 SDValue RetOp = getValue(I.getOperand(0)); 1438 1439 const Function *F = I.getParent()->getParent(); 1440 1441 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1442 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1443 Attribute::SExt)) 1444 ExtendKind = ISD::SIGN_EXTEND; 1445 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1446 Attribute::ZExt)) 1447 ExtendKind = ISD::ZERO_EXTEND; 1448 1449 LLVMContext &Context = F->getContext(); 1450 bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1451 Attribute::InReg); 1452 1453 for (unsigned j = 0; j != NumValues; ++j) { 1454 EVT VT = ValueVTs[j]; 1455 1456 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1457 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1458 1459 unsigned NumParts = TLI.getNumRegisters(Context, VT); 1460 MVT PartVT = TLI.getRegisterType(Context, VT); 1461 SmallVector<SDValue, 4> Parts(NumParts); 1462 getCopyToParts(DAG, getCurSDLoc(), 1463 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1464 &Parts[0], NumParts, PartVT, &I, ExtendKind); 1465 1466 // 'inreg' on function refers to return value 1467 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1468 if (RetInReg) 1469 Flags.setInReg(); 1470 1471 // Propagate extension type if any 1472 if (ExtendKind == ISD::SIGN_EXTEND) 1473 Flags.setSExt(); 1474 else if (ExtendKind == ISD::ZERO_EXTEND) 1475 Flags.setZExt(); 1476 1477 for (unsigned i = 0; i < NumParts; ++i) { 1478 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1479 VT, /*isfixed=*/true, 0, 0)); 1480 OutVals.push_back(Parts[i]); 1481 } 1482 } 1483 } 1484 } 1485 1486 // Push in swifterror virtual register as the last element of Outs. This makes 1487 // sure swifterror virtual register will be returned in the swifterror 1488 // physical register. 1489 const Function *F = I.getParent()->getParent(); 1490 if (TLI.supportSwiftError() && 1491 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1492 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1493 Flags.setSwiftError(); 1494 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1495 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1496 true /*isfixed*/, 1 /*origidx*/, 1497 0 /*partOffs*/)); 1498 // Create SDNode for the swifterror virtual register. 1499 OutVals.push_back(DAG.getRegister(FuncInfo.SwiftErrorMap[FuncInfo.MBB][0], 1500 EVT(TLI.getPointerTy(DL)))); 1501 } 1502 1503 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); 1504 CallingConv::ID CallConv = 1505 DAG.getMachineFunction().getFunction()->getCallingConv(); 1506 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1507 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1508 1509 // Verify that the target's LowerReturn behaved as expected. 1510 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1511 "LowerReturn didn't return a valid chain!"); 1512 1513 // Update the DAG with the new chain value resulting from return lowering. 1514 DAG.setRoot(Chain); 1515 } 1516 1517 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1518 /// created for it, emit nodes to copy the value into the virtual 1519 /// registers. 1520 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1521 // Skip empty types 1522 if (V->getType()->isEmptyTy()) 1523 return; 1524 1525 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1526 if (VMI != FuncInfo.ValueMap.end()) { 1527 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1528 CopyValueToVirtualRegister(V, VMI->second); 1529 } 1530 } 1531 1532 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1533 /// the current basic block, add it to ValueMap now so that we'll get a 1534 /// CopyTo/FromReg. 1535 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1536 // No need to export constants. 1537 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1538 1539 // Already exported? 1540 if (FuncInfo.isExportedInst(V)) return; 1541 1542 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1543 CopyValueToVirtualRegister(V, Reg); 1544 } 1545 1546 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1547 const BasicBlock *FromBB) { 1548 // The operands of the setcc have to be in this block. We don't know 1549 // how to export them from some other block. 1550 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1551 // Can export from current BB. 1552 if (VI->getParent() == FromBB) 1553 return true; 1554 1555 // Is already exported, noop. 1556 return FuncInfo.isExportedInst(V); 1557 } 1558 1559 // If this is an argument, we can export it if the BB is the entry block or 1560 // if it is already exported. 1561 if (isa<Argument>(V)) { 1562 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1563 return true; 1564 1565 // Otherwise, can only export this if it is already exported. 1566 return FuncInfo.isExportedInst(V); 1567 } 1568 1569 // Otherwise, constants can always be exported. 1570 return true; 1571 } 1572 1573 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1574 BranchProbability 1575 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1576 const MachineBasicBlock *Dst) const { 1577 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1578 const BasicBlock *SrcBB = Src->getBasicBlock(); 1579 const BasicBlock *DstBB = Dst->getBasicBlock(); 1580 if (!BPI) { 1581 // If BPI is not available, set the default probability as 1 / N, where N is 1582 // the number of successors. 1583 auto SuccSize = std::max<uint32_t>( 1584 std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1); 1585 return BranchProbability(1, SuccSize); 1586 } 1587 return BPI->getEdgeProbability(SrcBB, DstBB); 1588 } 1589 1590 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1591 MachineBasicBlock *Dst, 1592 BranchProbability Prob) { 1593 if (!FuncInfo.BPI) 1594 Src->addSuccessorWithoutProb(Dst); 1595 else { 1596 if (Prob.isUnknown()) 1597 Prob = getEdgeProbability(Src, Dst); 1598 Src->addSuccessor(Dst, Prob); 1599 } 1600 } 1601 1602 static bool InBlock(const Value *V, const BasicBlock *BB) { 1603 if (const Instruction *I = dyn_cast<Instruction>(V)) 1604 return I->getParent() == BB; 1605 return true; 1606 } 1607 1608 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1609 /// This function emits a branch and is used at the leaves of an OR or an 1610 /// AND operator tree. 1611 /// 1612 void 1613 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1614 MachineBasicBlock *TBB, 1615 MachineBasicBlock *FBB, 1616 MachineBasicBlock *CurBB, 1617 MachineBasicBlock *SwitchBB, 1618 BranchProbability TProb, 1619 BranchProbability FProb) { 1620 const BasicBlock *BB = CurBB->getBasicBlock(); 1621 1622 // If the leaf of the tree is a comparison, merge the condition into 1623 // the caseblock. 1624 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1625 // The operands of the cmp have to be in this block. We don't know 1626 // how to export them from some other block. If this is the first block 1627 // of the sequence, no exporting is needed. 1628 if (CurBB == SwitchBB || 1629 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1630 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1631 ISD::CondCode Condition; 1632 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1633 Condition = getICmpCondCode(IC->getPredicate()); 1634 } else { 1635 const FCmpInst *FC = cast<FCmpInst>(Cond); 1636 Condition = getFCmpCondCode(FC->getPredicate()); 1637 if (TM.Options.NoNaNsFPMath) 1638 Condition = getFCmpCodeWithoutNaN(Condition); 1639 } 1640 1641 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1642 TBB, FBB, CurBB, TProb, FProb); 1643 SwitchCases.push_back(CB); 1644 return; 1645 } 1646 } 1647 1648 // Create a CaseBlock record representing this branch. 1649 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()), 1650 nullptr, TBB, FBB, CurBB, TProb, FProb); 1651 SwitchCases.push_back(CB); 1652 } 1653 1654 /// FindMergedConditions - If Cond is an expression like 1655 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1656 MachineBasicBlock *TBB, 1657 MachineBasicBlock *FBB, 1658 MachineBasicBlock *CurBB, 1659 MachineBasicBlock *SwitchBB, 1660 Instruction::BinaryOps Opc, 1661 BranchProbability TProb, 1662 BranchProbability FProb) { 1663 // If this node is not part of the or/and tree, emit it as a branch. 1664 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1665 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1666 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || 1667 BOp->getParent() != CurBB->getBasicBlock() || 1668 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1669 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1670 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1671 TProb, FProb); 1672 return; 1673 } 1674 1675 // Create TmpBB after CurBB. 1676 MachineFunction::iterator BBI(CurBB); 1677 MachineFunction &MF = DAG.getMachineFunction(); 1678 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1679 CurBB->getParent()->insert(++BBI, TmpBB); 1680 1681 if (Opc == Instruction::Or) { 1682 // Codegen X | Y as: 1683 // BB1: 1684 // jmp_if_X TBB 1685 // jmp TmpBB 1686 // TmpBB: 1687 // jmp_if_Y TBB 1688 // jmp FBB 1689 // 1690 1691 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1692 // The requirement is that 1693 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1694 // = TrueProb for original BB. 1695 // Assuming the original probabilities are A and B, one choice is to set 1696 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1697 // A/(1+B) and 2B/(1+B). This choice assumes that 1698 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1699 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1700 // TmpBB, but the math is more complicated. 1701 1702 auto NewTrueProb = TProb / 2; 1703 auto NewFalseProb = TProb / 2 + FProb; 1704 // Emit the LHS condition. 1705 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1706 NewTrueProb, NewFalseProb); 1707 1708 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1709 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 1710 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1711 // Emit the RHS condition into TmpBB. 1712 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1713 Probs[0], Probs[1]); 1714 } else { 1715 assert(Opc == Instruction::And && "Unknown merge op!"); 1716 // Codegen X & Y as: 1717 // BB1: 1718 // jmp_if_X TmpBB 1719 // jmp FBB 1720 // TmpBB: 1721 // jmp_if_Y TBB 1722 // jmp FBB 1723 // 1724 // This requires creation of TmpBB after CurBB. 1725 1726 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1727 // The requirement is that 1728 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1729 // = FalseProb for original BB. 1730 // Assuming the original probabilities are A and B, one choice is to set 1731 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1732 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1733 // TrueProb for BB1 * FalseProb for TmpBB. 1734 1735 auto NewTrueProb = TProb + FProb / 2; 1736 auto NewFalseProb = FProb / 2; 1737 // Emit the LHS condition. 1738 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1739 NewTrueProb, NewFalseProb); 1740 1741 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1742 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 1743 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1744 // Emit the RHS condition into TmpBB. 1745 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1746 Probs[0], Probs[1]); 1747 } 1748 } 1749 1750 /// If the set of cases should be emitted as a series of branches, return true. 1751 /// If we should emit this as a bunch of and/or'd together conditions, return 1752 /// false. 1753 bool 1754 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1755 if (Cases.size() != 2) return true; 1756 1757 // If this is two comparisons of the same values or'd or and'd together, they 1758 // will get folded into a single comparison, so don't emit two blocks. 1759 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1760 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1761 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1762 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1763 return false; 1764 } 1765 1766 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1767 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1768 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1769 Cases[0].CC == Cases[1].CC && 1770 isa<Constant>(Cases[0].CmpRHS) && 1771 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1772 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1773 return false; 1774 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1775 return false; 1776 } 1777 1778 return true; 1779 } 1780 1781 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1782 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1783 1784 // Update machine-CFG edges. 1785 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1786 1787 if (I.isUnconditional()) { 1788 // Update machine-CFG edges. 1789 BrMBB->addSuccessor(Succ0MBB); 1790 1791 // If this is not a fall-through branch or optimizations are switched off, 1792 // emit the branch. 1793 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1794 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1795 MVT::Other, getControlRoot(), 1796 DAG.getBasicBlock(Succ0MBB))); 1797 1798 return; 1799 } 1800 1801 // If this condition is one of the special cases we handle, do special stuff 1802 // now. 1803 const Value *CondVal = I.getCondition(); 1804 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1805 1806 // If this is a series of conditions that are or'd or and'd together, emit 1807 // this as a sequence of branches instead of setcc's with and/or operations. 1808 // As long as jumps are not expensive, this should improve performance. 1809 // For example, instead of something like: 1810 // cmp A, B 1811 // C = seteq 1812 // cmp D, E 1813 // F = setle 1814 // or C, F 1815 // jnz foo 1816 // Emit: 1817 // cmp A, B 1818 // je foo 1819 // cmp D, E 1820 // jle foo 1821 // 1822 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1823 Instruction::BinaryOps Opcode = BOp->getOpcode(); 1824 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 1825 !I.getMetadata(LLVMContext::MD_unpredictable) && 1826 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 1827 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 1828 Opcode, 1829 getEdgeProbability(BrMBB, Succ0MBB), 1830 getEdgeProbability(BrMBB, Succ1MBB)); 1831 // If the compares in later blocks need to use values not currently 1832 // exported from this block, export them now. This block should always 1833 // be the first entry. 1834 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 1835 1836 // Allow some cases to be rejected. 1837 if (ShouldEmitAsBranches(SwitchCases)) { 1838 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1839 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1840 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1841 } 1842 1843 // Emit the branch for this block. 1844 visitSwitchCase(SwitchCases[0], BrMBB); 1845 SwitchCases.erase(SwitchCases.begin()); 1846 return; 1847 } 1848 1849 // Okay, we decided not to do this, remove any inserted MBB's and clear 1850 // SwitchCases. 1851 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1852 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 1853 1854 SwitchCases.clear(); 1855 } 1856 } 1857 1858 // Create a CaseBlock record representing this branch. 1859 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 1860 nullptr, Succ0MBB, Succ1MBB, BrMBB); 1861 1862 // Use visitSwitchCase to actually insert the fast branch sequence for this 1863 // cond branch. 1864 visitSwitchCase(CB, BrMBB); 1865 } 1866 1867 /// visitSwitchCase - Emits the necessary code to represent a single node in 1868 /// the binary search tree resulting from lowering a switch instruction. 1869 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 1870 MachineBasicBlock *SwitchBB) { 1871 SDValue Cond; 1872 SDValue CondLHS = getValue(CB.CmpLHS); 1873 SDLoc dl = getCurSDLoc(); 1874 1875 // Build the setcc now. 1876 if (!CB.CmpMHS) { 1877 // Fold "(X == true)" to X and "(X == false)" to !X to 1878 // handle common cases produced by branch lowering. 1879 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 1880 CB.CC == ISD::SETEQ) 1881 Cond = CondLHS; 1882 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 1883 CB.CC == ISD::SETEQ) { 1884 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 1885 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 1886 } else 1887 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1888 } else { 1889 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 1890 1891 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 1892 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 1893 1894 SDValue CmpOp = getValue(CB.CmpMHS); 1895 EVT VT = CmpOp.getValueType(); 1896 1897 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 1898 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 1899 ISD::SETLE); 1900 } else { 1901 SDValue SUB = DAG.getNode(ISD::SUB, dl, 1902 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 1903 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 1904 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 1905 } 1906 } 1907 1908 // Update successor info 1909 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 1910 // TrueBB and FalseBB are always different unless the incoming IR is 1911 // degenerate. This only happens when running llc on weird IR. 1912 if (CB.TrueBB != CB.FalseBB) 1913 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 1914 SwitchBB->normalizeSuccProbs(); 1915 1916 // If the lhs block is the next block, invert the condition so that we can 1917 // fall through to the lhs instead of the rhs block. 1918 if (CB.TrueBB == NextBlock(SwitchBB)) { 1919 std::swap(CB.TrueBB, CB.FalseBB); 1920 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 1921 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 1922 } 1923 1924 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1925 MVT::Other, getControlRoot(), Cond, 1926 DAG.getBasicBlock(CB.TrueBB)); 1927 1928 // Insert the false branch. Do this even if it's a fall through branch, 1929 // this makes it easier to do DAG optimizations which require inverting 1930 // the branch condition. 1931 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1932 DAG.getBasicBlock(CB.FalseBB)); 1933 1934 DAG.setRoot(BrCond); 1935 } 1936 1937 /// visitJumpTable - Emit JumpTable node in the current MBB 1938 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 1939 // Emit the code for the jump table 1940 assert(JT.Reg != -1U && "Should lower JT Header first!"); 1941 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1942 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 1943 JT.Reg, PTy); 1944 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 1945 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 1946 MVT::Other, Index.getValue(1), 1947 Table, Index); 1948 DAG.setRoot(BrJumpTable); 1949 } 1950 1951 /// visitJumpTableHeader - This function emits necessary code to produce index 1952 /// in the JumpTable from switch case. 1953 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 1954 JumpTableHeader &JTH, 1955 MachineBasicBlock *SwitchBB) { 1956 SDLoc dl = getCurSDLoc(); 1957 1958 // Subtract the lowest switch case value from the value being switched on and 1959 // conditional branch to default mbb if the result is greater than the 1960 // difference between smallest and largest cases. 1961 SDValue SwitchOp = getValue(JTH.SValue); 1962 EVT VT = SwitchOp.getValueType(); 1963 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 1964 DAG.getConstant(JTH.First, dl, VT)); 1965 1966 // The SDNode we just created, which holds the value being switched on minus 1967 // the smallest case value, needs to be copied to a virtual register so it 1968 // can be used as an index into the jump table in a subsequent basic block. 1969 // This value may be smaller or larger than the target's pointer type, and 1970 // therefore require extension or truncating. 1971 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1972 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 1973 1974 unsigned JumpTableReg = 1975 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 1976 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 1977 JumpTableReg, SwitchOp); 1978 JT.Reg = JumpTableReg; 1979 1980 // Emit the range check for the jump table, and branch to the default block 1981 // for the switch statement if the value being switched on exceeds the largest 1982 // case in the switch. 1983 SDValue CMP = DAG.getSetCC( 1984 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 1985 Sub.getValueType()), 1986 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 1987 1988 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1989 MVT::Other, CopyTo, CMP, 1990 DAG.getBasicBlock(JT.Default)); 1991 1992 // Avoid emitting unnecessary branches to the next block. 1993 if (JT.MBB != NextBlock(SwitchBB)) 1994 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1995 DAG.getBasicBlock(JT.MBB)); 1996 1997 DAG.setRoot(BrCond); 1998 } 1999 2000 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2001 /// variable if there exists one. 2002 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2003 SDValue &Chain) { 2004 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2005 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2006 MachineFunction &MF = DAG.getMachineFunction(); 2007 Value *Global = TLI.getSDagStackGuard(*MF.getFunction()->getParent()); 2008 MachineSDNode *Node = 2009 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2010 if (Global) { 2011 MachinePointerInfo MPInfo(Global); 2012 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1); 2013 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant; 2014 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8, 2015 DAG.getEVTAlignment(PtrTy)); 2016 Node->setMemRefs(MemRefs, MemRefs + 1); 2017 } 2018 return SDValue(Node, 0); 2019 } 2020 2021 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2022 /// tail spliced into a stack protector check success bb. 2023 /// 2024 /// For a high level explanation of how this fits into the stack protector 2025 /// generation see the comment on the declaration of class 2026 /// StackProtectorDescriptor. 2027 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2028 MachineBasicBlock *ParentBB) { 2029 2030 // First create the loads to the guard/stack slot for the comparison. 2031 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2032 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2033 2034 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2035 int FI = MFI.getStackProtectorIndex(); 2036 2037 SDValue Guard; 2038 SDLoc dl = getCurSDLoc(); 2039 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2040 const Module &M = *ParentBB->getParent()->getFunction()->getParent(); 2041 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2042 2043 // Generate code to load the content of the guard slot. 2044 SDValue StackSlot = DAG.getLoad( 2045 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2046 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2047 MachineMemOperand::MOVolatile); 2048 2049 // Retrieve guard check function, nullptr if instrumentation is inlined. 2050 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2051 // The target provides a guard check function to validate the guard value. 2052 // Generate a call to that function with the content of the guard slot as 2053 // argument. 2054 auto *Fn = cast<Function>(GuardCheck); 2055 FunctionType *FnTy = Fn->getFunctionType(); 2056 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2057 2058 TargetLowering::ArgListTy Args; 2059 TargetLowering::ArgListEntry Entry; 2060 Entry.Node = StackSlot; 2061 Entry.Ty = FnTy->getParamType(0); 2062 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2063 Entry.isInReg = true; 2064 Args.push_back(Entry); 2065 2066 TargetLowering::CallLoweringInfo CLI(DAG); 2067 CLI.setDebugLoc(getCurSDLoc()) 2068 .setChain(DAG.getEntryNode()) 2069 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2070 getValue(GuardCheck), std::move(Args)); 2071 2072 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2073 DAG.setRoot(Result.second); 2074 return; 2075 } 2076 2077 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2078 // Otherwise, emit a volatile load to retrieve the stack guard value. 2079 SDValue Chain = DAG.getEntryNode(); 2080 if (TLI.useLoadStackGuardNode()) { 2081 Guard = getLoadStackGuard(DAG, dl, Chain); 2082 } else { 2083 const Value *IRGuard = TLI.getSDagStackGuard(M); 2084 SDValue GuardPtr = getValue(IRGuard); 2085 2086 Guard = 2087 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2088 Align, MachineMemOperand::MOVolatile); 2089 } 2090 2091 // Perform the comparison via a subtract/getsetcc. 2092 EVT VT = Guard.getValueType(); 2093 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot); 2094 2095 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2096 *DAG.getContext(), 2097 Sub.getValueType()), 2098 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2099 2100 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2101 // branch to failure MBB. 2102 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2103 MVT::Other, StackSlot.getOperand(0), 2104 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2105 // Otherwise branch to success MBB. 2106 SDValue Br = DAG.getNode(ISD::BR, dl, 2107 MVT::Other, BrCond, 2108 DAG.getBasicBlock(SPD.getSuccessMBB())); 2109 2110 DAG.setRoot(Br); 2111 } 2112 2113 /// Codegen the failure basic block for a stack protector check. 2114 /// 2115 /// A failure stack protector machine basic block consists simply of a call to 2116 /// __stack_chk_fail(). 2117 /// 2118 /// For a high level explanation of how this fits into the stack protector 2119 /// generation see the comment on the declaration of class 2120 /// StackProtectorDescriptor. 2121 void 2122 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2123 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2124 SDValue Chain = 2125 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2126 None, false, getCurSDLoc(), false, false).second; 2127 DAG.setRoot(Chain); 2128 } 2129 2130 /// visitBitTestHeader - This function emits necessary code to produce value 2131 /// suitable for "bit tests" 2132 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2133 MachineBasicBlock *SwitchBB) { 2134 SDLoc dl = getCurSDLoc(); 2135 2136 // Subtract the minimum value 2137 SDValue SwitchOp = getValue(B.SValue); 2138 EVT VT = SwitchOp.getValueType(); 2139 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2140 DAG.getConstant(B.First, dl, VT)); 2141 2142 // Check range 2143 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2144 SDValue RangeCmp = DAG.getSetCC( 2145 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2146 Sub.getValueType()), 2147 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2148 2149 // Determine the type of the test operands. 2150 bool UsePtrType = false; 2151 if (!TLI.isTypeLegal(VT)) 2152 UsePtrType = true; 2153 else { 2154 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2155 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2156 // Switch table case range are encoded into series of masks. 2157 // Just use pointer type, it's guaranteed to fit. 2158 UsePtrType = true; 2159 break; 2160 } 2161 } 2162 if (UsePtrType) { 2163 VT = TLI.getPointerTy(DAG.getDataLayout()); 2164 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2165 } 2166 2167 B.RegVT = VT.getSimpleVT(); 2168 B.Reg = FuncInfo.CreateReg(B.RegVT); 2169 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2170 2171 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2172 2173 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2174 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2175 SwitchBB->normalizeSuccProbs(); 2176 2177 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2178 MVT::Other, CopyTo, RangeCmp, 2179 DAG.getBasicBlock(B.Default)); 2180 2181 // Avoid emitting unnecessary branches to the next block. 2182 if (MBB != NextBlock(SwitchBB)) 2183 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2184 DAG.getBasicBlock(MBB)); 2185 2186 DAG.setRoot(BrRange); 2187 } 2188 2189 /// visitBitTestCase - this function produces one "bit test" 2190 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2191 MachineBasicBlock* NextMBB, 2192 BranchProbability BranchProbToNext, 2193 unsigned Reg, 2194 BitTestCase &B, 2195 MachineBasicBlock *SwitchBB) { 2196 SDLoc dl = getCurSDLoc(); 2197 MVT VT = BB.RegVT; 2198 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2199 SDValue Cmp; 2200 unsigned PopCount = countPopulation(B.Mask); 2201 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2202 if (PopCount == 1) { 2203 // Testing for a single bit; just compare the shift count with what it 2204 // would need to be to shift a 1 bit in that position. 2205 Cmp = DAG.getSetCC( 2206 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2207 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2208 ISD::SETEQ); 2209 } else if (PopCount == BB.Range) { 2210 // There is only one zero bit in the range, test for it directly. 2211 Cmp = DAG.getSetCC( 2212 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2213 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2214 ISD::SETNE); 2215 } else { 2216 // Make desired shift 2217 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2218 DAG.getConstant(1, dl, VT), ShiftOp); 2219 2220 // Emit bit tests and jumps 2221 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2222 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2223 Cmp = DAG.getSetCC( 2224 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2225 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2226 } 2227 2228 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2229 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2230 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2231 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2232 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2233 // one as they are relative probabilities (and thus work more like weights), 2234 // and hence we need to normalize them to let the sum of them become one. 2235 SwitchBB->normalizeSuccProbs(); 2236 2237 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2238 MVT::Other, getControlRoot(), 2239 Cmp, DAG.getBasicBlock(B.TargetBB)); 2240 2241 // Avoid emitting unnecessary branches to the next block. 2242 if (NextMBB != NextBlock(SwitchBB)) 2243 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2244 DAG.getBasicBlock(NextMBB)); 2245 2246 DAG.setRoot(BrAnd); 2247 } 2248 2249 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2250 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2251 2252 // Retrieve successors. Look through artificial IR level blocks like 2253 // catchswitch for successors. 2254 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2255 const BasicBlock *EHPadBB = I.getSuccessor(1); 2256 2257 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2258 // have to do anything here to lower funclet bundles. 2259 assert(!I.hasOperandBundlesOtherThan( 2260 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2261 "Cannot lower invokes with arbitrary operand bundles yet!"); 2262 2263 const Value *Callee(I.getCalledValue()); 2264 const Function *Fn = dyn_cast<Function>(Callee); 2265 if (isa<InlineAsm>(Callee)) 2266 visitInlineAsm(&I); 2267 else if (Fn && Fn->isIntrinsic()) { 2268 switch (Fn->getIntrinsicID()) { 2269 default: 2270 llvm_unreachable("Cannot invoke this intrinsic"); 2271 case Intrinsic::donothing: 2272 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2273 break; 2274 case Intrinsic::experimental_patchpoint_void: 2275 case Intrinsic::experimental_patchpoint_i64: 2276 visitPatchpoint(&I, EHPadBB); 2277 break; 2278 case Intrinsic::experimental_gc_statepoint: 2279 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2280 break; 2281 } 2282 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2283 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2284 // Eventually we will support lowering the @llvm.experimental.deoptimize 2285 // intrinsic, and right now there are no plans to support other intrinsics 2286 // with deopt state. 2287 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2288 } else { 2289 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2290 } 2291 2292 // If the value of the invoke is used outside of its defining block, make it 2293 // available as a virtual register. 2294 // We already took care of the exported value for the statepoint instruction 2295 // during call to the LowerStatepoint. 2296 if (!isStatepoint(I)) { 2297 CopyToExportRegsIfNeeded(&I); 2298 } 2299 2300 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2301 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2302 BranchProbability EHPadBBProb = 2303 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2304 : BranchProbability::getZero(); 2305 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2306 2307 // Update successor info. 2308 addSuccessorWithProb(InvokeMBB, Return); 2309 for (auto &UnwindDest : UnwindDests) { 2310 UnwindDest.first->setIsEHPad(); 2311 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2312 } 2313 InvokeMBB->normalizeSuccProbs(); 2314 2315 // Drop into normal successor. 2316 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2317 MVT::Other, getControlRoot(), 2318 DAG.getBasicBlock(Return))); 2319 } 2320 2321 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2322 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2323 } 2324 2325 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2326 assert(FuncInfo.MBB->isEHPad() && 2327 "Call to landingpad not in landing pad!"); 2328 2329 MachineBasicBlock *MBB = FuncInfo.MBB; 2330 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 2331 AddLandingPadInfo(LP, MMI, MBB); 2332 2333 // If there aren't registers to copy the values into (e.g., during SjLj 2334 // exceptions), then don't bother to create these DAG nodes. 2335 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2336 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2337 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2338 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2339 return; 2340 2341 // If landingpad's return type is token type, we don't create DAG nodes 2342 // for its exception pointer and selector value. The extraction of exception 2343 // pointer or selector value from token type landingpads is not currently 2344 // supported. 2345 if (LP.getType()->isTokenTy()) 2346 return; 2347 2348 SmallVector<EVT, 2> ValueVTs; 2349 SDLoc dl = getCurSDLoc(); 2350 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2351 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2352 2353 // Get the two live-in registers as SDValues. The physregs have already been 2354 // copied into virtual registers. 2355 SDValue Ops[2]; 2356 if (FuncInfo.ExceptionPointerVirtReg) { 2357 Ops[0] = DAG.getZExtOrTrunc( 2358 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2359 FuncInfo.ExceptionPointerVirtReg, 2360 TLI.getPointerTy(DAG.getDataLayout())), 2361 dl, ValueVTs[0]); 2362 } else { 2363 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2364 } 2365 Ops[1] = DAG.getZExtOrTrunc( 2366 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2367 FuncInfo.ExceptionSelectorVirtReg, 2368 TLI.getPointerTy(DAG.getDataLayout())), 2369 dl, ValueVTs[1]); 2370 2371 // Merge into one. 2372 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2373 DAG.getVTList(ValueVTs), Ops); 2374 setValue(&LP, Res); 2375 } 2376 2377 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2378 #ifndef NDEBUG 2379 for (const CaseCluster &CC : Clusters) 2380 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2381 #endif 2382 2383 std::sort(Clusters.begin(), Clusters.end(), 2384 [](const CaseCluster &a, const CaseCluster &b) { 2385 return a.Low->getValue().slt(b.Low->getValue()); 2386 }); 2387 2388 // Merge adjacent clusters with the same destination. 2389 const unsigned N = Clusters.size(); 2390 unsigned DstIndex = 0; 2391 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2392 CaseCluster &CC = Clusters[SrcIndex]; 2393 const ConstantInt *CaseVal = CC.Low; 2394 MachineBasicBlock *Succ = CC.MBB; 2395 2396 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2397 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2398 // If this case has the same successor and is a neighbour, merge it into 2399 // the previous cluster. 2400 Clusters[DstIndex - 1].High = CaseVal; 2401 Clusters[DstIndex - 1].Prob += CC.Prob; 2402 } else { 2403 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2404 sizeof(Clusters[SrcIndex])); 2405 } 2406 } 2407 Clusters.resize(DstIndex); 2408 } 2409 2410 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2411 MachineBasicBlock *Last) { 2412 // Update JTCases. 2413 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2414 if (JTCases[i].first.HeaderBB == First) 2415 JTCases[i].first.HeaderBB = Last; 2416 2417 // Update BitTestCases. 2418 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2419 if (BitTestCases[i].Parent == First) 2420 BitTestCases[i].Parent = Last; 2421 } 2422 2423 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2424 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2425 2426 // Update machine-CFG edges with unique successors. 2427 SmallSet<BasicBlock*, 32> Done; 2428 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2429 BasicBlock *BB = I.getSuccessor(i); 2430 bool Inserted = Done.insert(BB).second; 2431 if (!Inserted) 2432 continue; 2433 2434 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2435 addSuccessorWithProb(IndirectBrMBB, Succ); 2436 } 2437 IndirectBrMBB->normalizeSuccProbs(); 2438 2439 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2440 MVT::Other, getControlRoot(), 2441 getValue(I.getAddress()))); 2442 } 2443 2444 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2445 if (DAG.getTarget().Options.TrapUnreachable) 2446 DAG.setRoot( 2447 DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2448 } 2449 2450 void SelectionDAGBuilder::visitFSub(const User &I) { 2451 // -0.0 - X --> fneg 2452 Type *Ty = I.getType(); 2453 if (isa<Constant>(I.getOperand(0)) && 2454 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2455 SDValue Op2 = getValue(I.getOperand(1)); 2456 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2457 Op2.getValueType(), Op2)); 2458 return; 2459 } 2460 2461 visitBinary(I, ISD::FSUB); 2462 } 2463 2464 /// Checks if the given instruction performs a vector reduction, in which case 2465 /// we have the freedom to alter the elements in the result as long as the 2466 /// reduction of them stays unchanged. 2467 static bool isVectorReductionOp(const User *I) { 2468 const Instruction *Inst = dyn_cast<Instruction>(I); 2469 if (!Inst || !Inst->getType()->isVectorTy()) 2470 return false; 2471 2472 auto OpCode = Inst->getOpcode(); 2473 switch (OpCode) { 2474 case Instruction::Add: 2475 case Instruction::Mul: 2476 case Instruction::And: 2477 case Instruction::Or: 2478 case Instruction::Xor: 2479 break; 2480 case Instruction::FAdd: 2481 case Instruction::FMul: 2482 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2483 if (FPOp->getFastMathFlags().unsafeAlgebra()) 2484 break; 2485 LLVM_FALLTHROUGH; 2486 default: 2487 return false; 2488 } 2489 2490 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2491 unsigned ElemNumToReduce = ElemNum; 2492 2493 // Do DFS search on the def-use chain from the given instruction. We only 2494 // allow four kinds of operations during the search until we reach the 2495 // instruction that extracts the first element from the vector: 2496 // 2497 // 1. The reduction operation of the same opcode as the given instruction. 2498 // 2499 // 2. PHI node. 2500 // 2501 // 3. ShuffleVector instruction together with a reduction operation that 2502 // does a partial reduction. 2503 // 2504 // 4. ExtractElement that extracts the first element from the vector, and we 2505 // stop searching the def-use chain here. 2506 // 2507 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2508 // from 1-3 to the stack to continue the DFS. The given instruction is not 2509 // a reduction operation if we meet any other instructions other than those 2510 // listed above. 2511 2512 SmallVector<const User *, 16> UsersToVisit{Inst}; 2513 SmallPtrSet<const User *, 16> Visited; 2514 bool ReduxExtracted = false; 2515 2516 while (!UsersToVisit.empty()) { 2517 auto User = UsersToVisit.back(); 2518 UsersToVisit.pop_back(); 2519 if (!Visited.insert(User).second) 2520 continue; 2521 2522 for (const auto &U : User->users()) { 2523 auto Inst = dyn_cast<Instruction>(U); 2524 if (!Inst) 2525 return false; 2526 2527 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2528 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2529 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().unsafeAlgebra()) 2530 return false; 2531 UsersToVisit.push_back(U); 2532 } else if (const ShuffleVectorInst *ShufInst = 2533 dyn_cast<ShuffleVectorInst>(U)) { 2534 // Detect the following pattern: A ShuffleVector instruction together 2535 // with a reduction that do partial reduction on the first and second 2536 // ElemNumToReduce / 2 elements, and store the result in 2537 // ElemNumToReduce / 2 elements in another vector. 2538 2539 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2540 if (ResultElements < ElemNum) 2541 return false; 2542 2543 if (ElemNumToReduce == 1) 2544 return false; 2545 if (!isa<UndefValue>(U->getOperand(1))) 2546 return false; 2547 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2548 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2549 return false; 2550 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2551 if (ShufInst->getMaskValue(i) != -1) 2552 return false; 2553 2554 // There is only one user of this ShuffleVector instruction, which 2555 // must be a reduction operation. 2556 if (!U->hasOneUse()) 2557 return false; 2558 2559 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2560 if (!U2 || U2->getOpcode() != OpCode) 2561 return false; 2562 2563 // Check operands of the reduction operation. 2564 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2565 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2566 UsersToVisit.push_back(U2); 2567 ElemNumToReduce /= 2; 2568 } else 2569 return false; 2570 } else if (isa<ExtractElementInst>(U)) { 2571 // At this moment we should have reduced all elements in the vector. 2572 if (ElemNumToReduce != 1) 2573 return false; 2574 2575 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2576 if (!Val || Val->getZExtValue() != 0) 2577 return false; 2578 2579 ReduxExtracted = true; 2580 } else 2581 return false; 2582 } 2583 } 2584 return ReduxExtracted; 2585 } 2586 2587 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) { 2588 SDValue Op1 = getValue(I.getOperand(0)); 2589 SDValue Op2 = getValue(I.getOperand(1)); 2590 2591 bool nuw = false; 2592 bool nsw = false; 2593 bool exact = false; 2594 bool vec_redux = false; 2595 FastMathFlags FMF; 2596 2597 if (const OverflowingBinaryOperator *OFBinOp = 2598 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2599 nuw = OFBinOp->hasNoUnsignedWrap(); 2600 nsw = OFBinOp->hasNoSignedWrap(); 2601 } 2602 if (const PossiblyExactOperator *ExactOp = 2603 dyn_cast<const PossiblyExactOperator>(&I)) 2604 exact = ExactOp->isExact(); 2605 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I)) 2606 FMF = FPOp->getFastMathFlags(); 2607 2608 if (isVectorReductionOp(&I)) { 2609 vec_redux = true; 2610 DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2611 } 2612 2613 SDNodeFlags Flags; 2614 Flags.setExact(exact); 2615 Flags.setNoSignedWrap(nsw); 2616 Flags.setNoUnsignedWrap(nuw); 2617 Flags.setVectorReduction(vec_redux); 2618 if (EnableFMFInDAG) { 2619 Flags.setAllowReciprocal(FMF.allowReciprocal()); 2620 Flags.setNoInfs(FMF.noInfs()); 2621 Flags.setNoNaNs(FMF.noNaNs()); 2622 Flags.setNoSignedZeros(FMF.noSignedZeros()); 2623 Flags.setUnsafeAlgebra(FMF.unsafeAlgebra()); 2624 } 2625 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(), 2626 Op1, Op2, &Flags); 2627 setValue(&I, BinNodeValue); 2628 } 2629 2630 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2631 SDValue Op1 = getValue(I.getOperand(0)); 2632 SDValue Op2 = getValue(I.getOperand(1)); 2633 2634 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2635 Op2.getValueType(), DAG.getDataLayout()); 2636 2637 // Coerce the shift amount to the right type if we can. 2638 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2639 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2640 unsigned Op2Size = Op2.getValueType().getSizeInBits(); 2641 SDLoc DL = getCurSDLoc(); 2642 2643 // If the operand is smaller than the shift count type, promote it. 2644 if (ShiftSize > Op2Size) 2645 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2646 2647 // If the operand is larger than the shift count type but the shift 2648 // count type has enough bits to represent any shift value, truncate 2649 // it now. This is a common case and it exposes the truncate to 2650 // optimization early. 2651 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits())) 2652 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2653 // Otherwise we'll need to temporarily settle for some other convenient 2654 // type. Type legalization will make adjustments once the shiftee is split. 2655 else 2656 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2657 } 2658 2659 bool nuw = false; 2660 bool nsw = false; 2661 bool exact = false; 2662 2663 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2664 2665 if (const OverflowingBinaryOperator *OFBinOp = 2666 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2667 nuw = OFBinOp->hasNoUnsignedWrap(); 2668 nsw = OFBinOp->hasNoSignedWrap(); 2669 } 2670 if (const PossiblyExactOperator *ExactOp = 2671 dyn_cast<const PossiblyExactOperator>(&I)) 2672 exact = ExactOp->isExact(); 2673 } 2674 SDNodeFlags Flags; 2675 Flags.setExact(exact); 2676 Flags.setNoSignedWrap(nsw); 2677 Flags.setNoUnsignedWrap(nuw); 2678 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2679 &Flags); 2680 setValue(&I, Res); 2681 } 2682 2683 void SelectionDAGBuilder::visitSDiv(const User &I) { 2684 SDValue Op1 = getValue(I.getOperand(0)); 2685 SDValue Op2 = getValue(I.getOperand(1)); 2686 2687 SDNodeFlags Flags; 2688 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2689 cast<PossiblyExactOperator>(&I)->isExact()); 2690 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2691 Op2, &Flags)); 2692 } 2693 2694 void SelectionDAGBuilder::visitICmp(const User &I) { 2695 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2696 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2697 predicate = IC->getPredicate(); 2698 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2699 predicate = ICmpInst::Predicate(IC->getPredicate()); 2700 SDValue Op1 = getValue(I.getOperand(0)); 2701 SDValue Op2 = getValue(I.getOperand(1)); 2702 ISD::CondCode Opcode = getICmpCondCode(predicate); 2703 2704 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2705 I.getType()); 2706 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2707 } 2708 2709 void SelectionDAGBuilder::visitFCmp(const User &I) { 2710 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2711 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2712 predicate = FC->getPredicate(); 2713 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2714 predicate = FCmpInst::Predicate(FC->getPredicate()); 2715 SDValue Op1 = getValue(I.getOperand(0)); 2716 SDValue Op2 = getValue(I.getOperand(1)); 2717 ISD::CondCode Condition = getFCmpCondCode(predicate); 2718 2719 // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them. 2720 // FIXME: We should propagate the fast-math-flags to the DAG node itself for 2721 // further optimization, but currently FMF is only applicable to binary nodes. 2722 if (TM.Options.NoNaNsFPMath) 2723 Condition = getFCmpCodeWithoutNaN(Condition); 2724 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2725 I.getType()); 2726 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2727 } 2728 2729 // Check if the condition of the select has one use or two users that are both 2730 // selects with the same condition. 2731 static bool hasOnlySelectUsers(const Value *Cond) { 2732 return all_of(Cond->users(), [](const Value *V) { 2733 return isa<SelectInst>(V); 2734 }); 2735 } 2736 2737 void SelectionDAGBuilder::visitSelect(const User &I) { 2738 SmallVector<EVT, 4> ValueVTs; 2739 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2740 ValueVTs); 2741 unsigned NumValues = ValueVTs.size(); 2742 if (NumValues == 0) return; 2743 2744 SmallVector<SDValue, 4> Values(NumValues); 2745 SDValue Cond = getValue(I.getOperand(0)); 2746 SDValue LHSVal = getValue(I.getOperand(1)); 2747 SDValue RHSVal = getValue(I.getOperand(2)); 2748 auto BaseOps = {Cond}; 2749 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2750 ISD::VSELECT : ISD::SELECT; 2751 2752 // Min/max matching is only viable if all output VTs are the same. 2753 if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) { 2754 EVT VT = ValueVTs[0]; 2755 LLVMContext &Ctx = *DAG.getContext(); 2756 auto &TLI = DAG.getTargetLoweringInfo(); 2757 2758 // We care about the legality of the operation after it has been type 2759 // legalized. 2760 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2761 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2762 VT = TLI.getTypeToTransformTo(Ctx, VT); 2763 2764 // If the vselect is legal, assume we want to leave this as a vector setcc + 2765 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2766 // min/max is legal on the scalar type. 2767 bool UseScalarMinMax = VT.isVector() && 2768 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2769 2770 Value *LHS, *RHS; 2771 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2772 ISD::NodeType Opc = ISD::DELETED_NODE; 2773 switch (SPR.Flavor) { 2774 case SPF_UMAX: Opc = ISD::UMAX; break; 2775 case SPF_UMIN: Opc = ISD::UMIN; break; 2776 case SPF_SMAX: Opc = ISD::SMAX; break; 2777 case SPF_SMIN: Opc = ISD::SMIN; break; 2778 case SPF_FMINNUM: 2779 switch (SPR.NaNBehavior) { 2780 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2781 case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break; 2782 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2783 case SPNB_RETURNS_ANY: { 2784 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2785 Opc = ISD::FMINNUM; 2786 else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)) 2787 Opc = ISD::FMINNAN; 2788 else if (UseScalarMinMax) 2789 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2790 ISD::FMINNUM : ISD::FMINNAN; 2791 break; 2792 } 2793 } 2794 break; 2795 case SPF_FMAXNUM: 2796 switch (SPR.NaNBehavior) { 2797 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2798 case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break; 2799 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 2800 case SPNB_RETURNS_ANY: 2801 2802 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 2803 Opc = ISD::FMAXNUM; 2804 else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)) 2805 Opc = ISD::FMAXNAN; 2806 else if (UseScalarMinMax) 2807 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 2808 ISD::FMAXNUM : ISD::FMAXNAN; 2809 break; 2810 } 2811 break; 2812 default: break; 2813 } 2814 2815 if (Opc != ISD::DELETED_NODE && 2816 (TLI.isOperationLegalOrCustom(Opc, VT) || 2817 (UseScalarMinMax && 2818 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 2819 // If the underlying comparison instruction is used by any other 2820 // instruction, the consumed instructions won't be destroyed, so it is 2821 // not profitable to convert to a min/max. 2822 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 2823 OpCode = Opc; 2824 LHSVal = getValue(LHS); 2825 RHSVal = getValue(RHS); 2826 BaseOps = {}; 2827 } 2828 } 2829 2830 for (unsigned i = 0; i != NumValues; ++i) { 2831 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 2832 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 2833 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 2834 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 2835 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 2836 Ops); 2837 } 2838 2839 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2840 DAG.getVTList(ValueVTs), Values)); 2841 } 2842 2843 void SelectionDAGBuilder::visitTrunc(const User &I) { 2844 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2845 SDValue N = getValue(I.getOperand(0)); 2846 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2847 I.getType()); 2848 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 2849 } 2850 2851 void SelectionDAGBuilder::visitZExt(const User &I) { 2852 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2853 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2854 SDValue N = getValue(I.getOperand(0)); 2855 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2856 I.getType()); 2857 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 2858 } 2859 2860 void SelectionDAGBuilder::visitSExt(const User &I) { 2861 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2862 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2863 SDValue N = getValue(I.getOperand(0)); 2864 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2865 I.getType()); 2866 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 2867 } 2868 2869 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 2870 // FPTrunc is never a no-op cast, no need to check 2871 SDValue N = getValue(I.getOperand(0)); 2872 SDLoc dl = getCurSDLoc(); 2873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2874 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 2875 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 2876 DAG.getTargetConstant( 2877 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 2878 } 2879 2880 void SelectionDAGBuilder::visitFPExt(const User &I) { 2881 // FPExt is never a no-op cast, no need to check 2882 SDValue N = getValue(I.getOperand(0)); 2883 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2884 I.getType()); 2885 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 2886 } 2887 2888 void SelectionDAGBuilder::visitFPToUI(const User &I) { 2889 // FPToUI is never a no-op cast, no need to check 2890 SDValue N = getValue(I.getOperand(0)); 2891 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2892 I.getType()); 2893 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 2894 } 2895 2896 void SelectionDAGBuilder::visitFPToSI(const User &I) { 2897 // FPToSI is never a no-op cast, no need to check 2898 SDValue N = getValue(I.getOperand(0)); 2899 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2900 I.getType()); 2901 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 2902 } 2903 2904 void SelectionDAGBuilder::visitUIToFP(const User &I) { 2905 // UIToFP is never a no-op cast, no need to check 2906 SDValue N = getValue(I.getOperand(0)); 2907 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2908 I.getType()); 2909 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 2910 } 2911 2912 void SelectionDAGBuilder::visitSIToFP(const User &I) { 2913 // SIToFP is never a no-op cast, no need to check 2914 SDValue N = getValue(I.getOperand(0)); 2915 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2916 I.getType()); 2917 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 2918 } 2919 2920 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 2921 // What to do depends on the size of the integer and the size of the pointer. 2922 // We can either truncate, zero extend, or no-op, accordingly. 2923 SDValue N = getValue(I.getOperand(0)); 2924 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2925 I.getType()); 2926 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 2927 } 2928 2929 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 2930 // What to do depends on the size of the integer and the size of the pointer. 2931 // We can either truncate, zero extend, or no-op, accordingly. 2932 SDValue N = getValue(I.getOperand(0)); 2933 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2934 I.getType()); 2935 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 2936 } 2937 2938 void SelectionDAGBuilder::visitBitCast(const User &I) { 2939 SDValue N = getValue(I.getOperand(0)); 2940 SDLoc dl = getCurSDLoc(); 2941 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2942 I.getType()); 2943 2944 // BitCast assures us that source and destination are the same size so this is 2945 // either a BITCAST or a no-op. 2946 if (DestVT != N.getValueType()) 2947 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 2948 DestVT, N)); // convert types. 2949 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 2950 // might fold any kind of constant expression to an integer constant and that 2951 // is not what we are looking for. Only regcognize a bitcast of a genuine 2952 // constant integer as an opaque constant. 2953 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 2954 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 2955 /*isOpaque*/true)); 2956 else 2957 setValue(&I, N); // noop cast. 2958 } 2959 2960 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 2961 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2962 const Value *SV = I.getOperand(0); 2963 SDValue N = getValue(SV); 2964 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 2965 2966 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 2967 unsigned DestAS = I.getType()->getPointerAddressSpace(); 2968 2969 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 2970 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 2971 2972 setValue(&I, N); 2973 } 2974 2975 void SelectionDAGBuilder::visitInsertElement(const User &I) { 2976 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2977 SDValue InVec = getValue(I.getOperand(0)); 2978 SDValue InVal = getValue(I.getOperand(1)); 2979 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 2980 TLI.getVectorIdxTy(DAG.getDataLayout())); 2981 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 2982 TLI.getValueType(DAG.getDataLayout(), I.getType()), 2983 InVec, InVal, InIdx)); 2984 } 2985 2986 void SelectionDAGBuilder::visitExtractElement(const User &I) { 2987 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2988 SDValue InVec = getValue(I.getOperand(0)); 2989 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 2990 TLI.getVectorIdxTy(DAG.getDataLayout())); 2991 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 2992 TLI.getValueType(DAG.getDataLayout(), I.getType()), 2993 InVec, InIdx)); 2994 } 2995 2996 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 2997 SDValue Src1 = getValue(I.getOperand(0)); 2998 SDValue Src2 = getValue(I.getOperand(1)); 2999 SDLoc DL = getCurSDLoc(); 3000 3001 SmallVector<int, 8> Mask; 3002 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3003 unsigned MaskNumElts = Mask.size(); 3004 3005 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3006 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3007 EVT SrcVT = Src1.getValueType(); 3008 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3009 3010 if (SrcNumElts == MaskNumElts) { 3011 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3012 return; 3013 } 3014 3015 // Normalize the shuffle vector since mask and vector length don't match. 3016 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) { 3017 // Mask is longer than the source vectors and is a multiple of the source 3018 // vectors. We can use concatenate vector to make the mask and vectors 3019 // lengths match. 3020 3021 unsigned NumConcat = MaskNumElts / SrcNumElts; 3022 3023 // Check if the shuffle is some kind of concatenation of the input vectors. 3024 bool IsConcat = true; 3025 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3026 for (unsigned i = 0; i != MaskNumElts; ++i) { 3027 int Idx = Mask[i]; 3028 if (Idx < 0) 3029 continue; 3030 // Ensure the indices in each SrcVT sized piece are sequential and that 3031 // the same source is used for the whole piece. 3032 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3033 (ConcatSrcs[i / SrcNumElts] >= 0 && 3034 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3035 IsConcat = false; 3036 break; 3037 } 3038 // Remember which source this index came from. 3039 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3040 } 3041 3042 // The shuffle is concatenating multiple vectors together. Just emit 3043 // a CONCAT_VECTORS operation. 3044 if (IsConcat) { 3045 SmallVector<SDValue, 8> ConcatOps; 3046 for (auto Src : ConcatSrcs) { 3047 if (Src < 0) 3048 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3049 else if (Src == 0) 3050 ConcatOps.push_back(Src1); 3051 else 3052 ConcatOps.push_back(Src2); 3053 } 3054 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3055 return; 3056 } 3057 3058 // Pad both vectors with undefs to make them the same length as the mask. 3059 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3060 3061 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3062 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3063 MOps1[0] = Src1; 3064 MOps2[0] = Src2; 3065 3066 Src1 = Src1.isUndef() ? DAG.getUNDEF(VT) 3067 : DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, MOps1); 3068 Src2 = Src2.isUndef() ? DAG.getUNDEF(VT) 3069 : DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, MOps2); 3070 3071 // Readjust mask for new input vector length. 3072 SmallVector<int, 8> MappedOps; 3073 for (unsigned i = 0; i != MaskNumElts; ++i) { 3074 int Idx = Mask[i]; 3075 if (Idx >= (int)SrcNumElts) 3076 Idx -= SrcNumElts - MaskNumElts; 3077 MappedOps.push_back(Idx); 3078 } 3079 3080 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3081 return; 3082 } 3083 3084 if (SrcNumElts > MaskNumElts) { 3085 // Analyze the access pattern of the vector to see if we can extract 3086 // two subvectors and do the shuffle. The analysis is done by calculating 3087 // the range of elements the mask access on both vectors. 3088 int MinRange[2] = { static_cast<int>(SrcNumElts), 3089 static_cast<int>(SrcNumElts)}; 3090 int MaxRange[2] = {-1, -1}; 3091 3092 for (unsigned i = 0; i != MaskNumElts; ++i) { 3093 int Idx = Mask[i]; 3094 unsigned Input = 0; 3095 if (Idx < 0) 3096 continue; 3097 3098 if (Idx >= (int)SrcNumElts) { 3099 Input = 1; 3100 Idx -= SrcNumElts; 3101 } 3102 if (Idx > MaxRange[Input]) 3103 MaxRange[Input] = Idx; 3104 if (Idx < MinRange[Input]) 3105 MinRange[Input] = Idx; 3106 } 3107 3108 // Check if the access is smaller than the vector size and can we find 3109 // a reasonable extract index. 3110 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not 3111 // Extract. 3112 int StartIdx[2]; // StartIdx to extract from 3113 for (unsigned Input = 0; Input < 2; ++Input) { 3114 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) { 3115 RangeUse[Input] = 0; // Unused 3116 StartIdx[Input] = 0; 3117 continue; 3118 } 3119 3120 // Find a good start index that is a multiple of the mask length. Then 3121 // see if the rest of the elements are in range. 3122 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts; 3123 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts && 3124 StartIdx[Input] + MaskNumElts <= SrcNumElts) 3125 RangeUse[Input] = 1; // Extract from a multiple of the mask length. 3126 } 3127 3128 if (RangeUse[0] == 0 && RangeUse[1] == 0) { 3129 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3130 return; 3131 } 3132 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) { 3133 // Extract appropriate subvector and generate a vector shuffle 3134 for (unsigned Input = 0; Input < 2; ++Input) { 3135 SDValue &Src = Input == 0 ? Src1 : Src2; 3136 if (RangeUse[Input] == 0) 3137 Src = DAG.getUNDEF(VT); 3138 else { 3139 Src = DAG.getNode( 3140 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3141 DAG.getConstant(StartIdx[Input], DL, 3142 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3143 } 3144 } 3145 3146 // Calculate new mask. 3147 SmallVector<int, 8> MappedOps; 3148 for (unsigned i = 0; i != MaskNumElts; ++i) { 3149 int Idx = Mask[i]; 3150 if (Idx >= 0) { 3151 if (Idx < (int)SrcNumElts) 3152 Idx -= StartIdx[0]; 3153 else 3154 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3155 } 3156 MappedOps.push_back(Idx); 3157 } 3158 3159 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3160 return; 3161 } 3162 } 3163 3164 // We can't use either concat vectors or extract subvectors so fall back to 3165 // replacing the shuffle with extract and build vector. 3166 // to insert and build vector. 3167 EVT EltVT = VT.getVectorElementType(); 3168 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3169 SmallVector<SDValue,8> Ops; 3170 for (unsigned i = 0; i != MaskNumElts; ++i) { 3171 int Idx = Mask[i]; 3172 SDValue Res; 3173 3174 if (Idx < 0) { 3175 Res = DAG.getUNDEF(EltVT); 3176 } else { 3177 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3178 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3179 3180 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3181 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3182 } 3183 3184 Ops.push_back(Res); 3185 } 3186 3187 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops)); 3188 } 3189 3190 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3191 const Value *Op0 = I.getOperand(0); 3192 const Value *Op1 = I.getOperand(1); 3193 Type *AggTy = I.getType(); 3194 Type *ValTy = Op1->getType(); 3195 bool IntoUndef = isa<UndefValue>(Op0); 3196 bool FromUndef = isa<UndefValue>(Op1); 3197 3198 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices()); 3199 3200 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3201 SmallVector<EVT, 4> AggValueVTs; 3202 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3203 SmallVector<EVT, 4> ValValueVTs; 3204 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3205 3206 unsigned NumAggValues = AggValueVTs.size(); 3207 unsigned NumValValues = ValValueVTs.size(); 3208 SmallVector<SDValue, 4> Values(NumAggValues); 3209 3210 // Ignore an insertvalue that produces an empty object 3211 if (!NumAggValues) { 3212 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3213 return; 3214 } 3215 3216 SDValue Agg = getValue(Op0); 3217 unsigned i = 0; 3218 // Copy the beginning value(s) from the original aggregate. 3219 for (; i != LinearIndex; ++i) 3220 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3221 SDValue(Agg.getNode(), Agg.getResNo() + i); 3222 // Copy values from the inserted value(s). 3223 if (NumValValues) { 3224 SDValue Val = getValue(Op1); 3225 for (; i != LinearIndex + NumValValues; ++i) 3226 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3227 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3228 } 3229 // Copy remaining value(s) from the original aggregate. 3230 for (; i != NumAggValues; ++i) 3231 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3232 SDValue(Agg.getNode(), Agg.getResNo() + i); 3233 3234 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3235 DAG.getVTList(AggValueVTs), Values)); 3236 } 3237 3238 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3239 const Value *Op0 = I.getOperand(0); 3240 Type *AggTy = Op0->getType(); 3241 Type *ValTy = I.getType(); 3242 bool OutOfUndef = isa<UndefValue>(Op0); 3243 3244 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices()); 3245 3246 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3247 SmallVector<EVT, 4> ValValueVTs; 3248 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3249 3250 unsigned NumValValues = ValValueVTs.size(); 3251 3252 // Ignore a extractvalue that produces an empty object 3253 if (!NumValValues) { 3254 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3255 return; 3256 } 3257 3258 SmallVector<SDValue, 4> Values(NumValValues); 3259 3260 SDValue Agg = getValue(Op0); 3261 // Copy out the selected value(s). 3262 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3263 Values[i - LinearIndex] = 3264 OutOfUndef ? 3265 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3266 SDValue(Agg.getNode(), Agg.getResNo() + i); 3267 3268 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3269 DAG.getVTList(ValValueVTs), Values)); 3270 } 3271 3272 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3273 Value *Op0 = I.getOperand(0); 3274 // Note that the pointer operand may be a vector of pointers. Take the scalar 3275 // element which holds a pointer. 3276 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3277 SDValue N = getValue(Op0); 3278 SDLoc dl = getCurSDLoc(); 3279 3280 // Normalize Vector GEP - all scalar operands should be converted to the 3281 // splat vector. 3282 unsigned VectorWidth = I.getType()->isVectorTy() ? 3283 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3284 3285 if (VectorWidth && !N.getValueType().isVector()) { 3286 LLVMContext &Context = *DAG.getContext(); 3287 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3288 SmallVector<SDValue, 16> Ops(VectorWidth, N); 3289 N = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 3290 } 3291 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3292 GTI != E; ++GTI) { 3293 const Value *Idx = GTI.getOperand(); 3294 if (StructType *StTy = dyn_cast<StructType>(*GTI)) { 3295 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3296 if (Field) { 3297 // N = N + Offset 3298 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3299 3300 // In an inbouds GEP with an offset that is nonnegative even when 3301 // interpreted as signed, assume there is no unsigned overflow. 3302 SDNodeFlags Flags; 3303 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3304 Flags.setNoUnsignedWrap(true); 3305 3306 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3307 DAG.getConstant(Offset, dl, N.getValueType()), &Flags); 3308 } 3309 } else { 3310 MVT PtrTy = 3311 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS); 3312 unsigned PtrSize = PtrTy.getSizeInBits(); 3313 APInt ElementSize(PtrSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3314 3315 // If this is a scalar constant or a splat vector of constants, 3316 // handle it quickly. 3317 const auto *CI = dyn_cast<ConstantInt>(Idx); 3318 if (!CI && isa<ConstantDataVector>(Idx) && 3319 cast<ConstantDataVector>(Idx)->getSplatValue()) 3320 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3321 3322 if (CI) { 3323 if (CI->isZero()) 3324 continue; 3325 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize); 3326 LLVMContext &Context = *DAG.getContext(); 3327 SDValue OffsVal = VectorWidth ? 3328 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, PtrTy, VectorWidth)) : 3329 DAG.getConstant(Offs, dl, PtrTy); 3330 3331 // In an inbouds GEP with an offset that is nonnegative even when 3332 // interpreted as signed, assume there is no unsigned overflow. 3333 SDNodeFlags Flags; 3334 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3335 Flags.setNoUnsignedWrap(true); 3336 3337 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, &Flags); 3338 continue; 3339 } 3340 3341 // N = N + Idx * ElementSize; 3342 SDValue IdxN = getValue(Idx); 3343 3344 if (!IdxN.getValueType().isVector() && VectorWidth) { 3345 MVT VT = MVT::getVectorVT(IdxN.getValueType().getSimpleVT(), VectorWidth); 3346 SmallVector<SDValue, 16> Ops(VectorWidth, IdxN); 3347 IdxN = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 3348 } 3349 // If the index is smaller or larger than intptr_t, truncate or extend 3350 // it. 3351 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3352 3353 // If this is a multiply by a power of two, turn it into a shl 3354 // immediately. This is a very common case. 3355 if (ElementSize != 1) { 3356 if (ElementSize.isPowerOf2()) { 3357 unsigned Amt = ElementSize.logBase2(); 3358 IdxN = DAG.getNode(ISD::SHL, dl, 3359 N.getValueType(), IdxN, 3360 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3361 } else { 3362 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3363 IdxN = DAG.getNode(ISD::MUL, dl, 3364 N.getValueType(), IdxN, Scale); 3365 } 3366 } 3367 3368 N = DAG.getNode(ISD::ADD, dl, 3369 N.getValueType(), N, IdxN); 3370 } 3371 } 3372 3373 setValue(&I, N); 3374 } 3375 3376 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3377 // If this is a fixed sized alloca in the entry block of the function, 3378 // allocate it statically on the stack. 3379 if (FuncInfo.StaticAllocaMap.count(&I)) 3380 return; // getValue will auto-populate this. 3381 3382 SDLoc dl = getCurSDLoc(); 3383 Type *Ty = I.getAllocatedType(); 3384 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3385 auto &DL = DAG.getDataLayout(); 3386 uint64_t TySize = DL.getTypeAllocSize(Ty); 3387 unsigned Align = 3388 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3389 3390 SDValue AllocSize = getValue(I.getArraySize()); 3391 3392 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout()); 3393 if (AllocSize.getValueType() != IntPtr) 3394 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3395 3396 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3397 AllocSize, 3398 DAG.getConstant(TySize, dl, IntPtr)); 3399 3400 // Handle alignment. If the requested alignment is less than or equal to 3401 // the stack alignment, ignore it. If the size is greater than or equal to 3402 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3403 unsigned StackAlign = 3404 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3405 if (Align <= StackAlign) 3406 Align = 0; 3407 3408 // Round the size of the allocation up to the stack alignment size 3409 // by add SA-1 to the size. This doesn't overflow because we're computing 3410 // an address inside an alloca. 3411 SDNodeFlags Flags; 3412 Flags.setNoUnsignedWrap(true); 3413 AllocSize = DAG.getNode(ISD::ADD, dl, 3414 AllocSize.getValueType(), AllocSize, 3415 DAG.getIntPtrConstant(StackAlign - 1, dl), &Flags); 3416 3417 // Mask out the low bits for alignment purposes. 3418 AllocSize = DAG.getNode(ISD::AND, dl, 3419 AllocSize.getValueType(), AllocSize, 3420 DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1), 3421 dl)); 3422 3423 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) }; 3424 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3425 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3426 setValue(&I, DSA); 3427 DAG.setRoot(DSA.getValue(1)); 3428 3429 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3430 } 3431 3432 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3433 if (I.isAtomic()) 3434 return visitAtomicLoad(I); 3435 3436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3437 const Value *SV = I.getOperand(0); 3438 if (TLI.supportSwiftError()) { 3439 // Swifterror values can come from either a function parameter with 3440 // swifterror attribute or an alloca with swifterror attribute. 3441 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3442 if (Arg->hasSwiftErrorAttr()) 3443 return visitLoadFromSwiftError(I); 3444 } 3445 3446 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3447 if (Alloca->isSwiftError()) 3448 return visitLoadFromSwiftError(I); 3449 } 3450 } 3451 3452 SDValue Ptr = getValue(SV); 3453 3454 Type *Ty = I.getType(); 3455 3456 bool isVolatile = I.isVolatile(); 3457 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3458 3459 // The IR notion of invariant_load only guarantees that all *non-faulting* 3460 // invariant loads result in the same value. The MI notion of invariant load 3461 // guarantees that the load can be legally moved to any location within its 3462 // containing function. The MI notion of invariant_load is stronger than the 3463 // IR notion of invariant_load -- an MI invariant_load is an IR invariant_load 3464 // with a guarantee that the location being loaded from is dereferenceable 3465 // throughout the function's lifetime. 3466 3467 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr && 3468 isDereferenceablePointer(SV, DAG.getDataLayout()); 3469 unsigned Alignment = I.getAlignment(); 3470 3471 AAMDNodes AAInfo; 3472 I.getAAMetadata(AAInfo); 3473 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3474 3475 SmallVector<EVT, 4> ValueVTs; 3476 SmallVector<uint64_t, 4> Offsets; 3477 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3478 unsigned NumValues = ValueVTs.size(); 3479 if (NumValues == 0) 3480 return; 3481 3482 SDValue Root; 3483 bool ConstantMemory = false; 3484 if (isVolatile || NumValues > MaxParallelChains) 3485 // Serialize volatile loads with other side effects. 3486 Root = getRoot(); 3487 else if (AA->pointsToConstantMemory(MemoryLocation( 3488 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) { 3489 // Do not serialize (non-volatile) loads of constant memory with anything. 3490 Root = DAG.getEntryNode(); 3491 ConstantMemory = true; 3492 } else { 3493 // Do not serialize non-volatile loads against each other. 3494 Root = DAG.getRoot(); 3495 } 3496 3497 SDLoc dl = getCurSDLoc(); 3498 3499 if (isVolatile) 3500 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3501 3502 // An aggregate load cannot wrap around the address space, so offsets to its 3503 // parts don't wrap either. 3504 SDNodeFlags Flags; 3505 Flags.setNoUnsignedWrap(true); 3506 3507 SmallVector<SDValue, 4> Values(NumValues); 3508 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3509 EVT PtrVT = Ptr.getValueType(); 3510 unsigned ChainI = 0; 3511 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3512 // Serializing loads here may result in excessive register pressure, and 3513 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3514 // could recover a bit by hoisting nodes upward in the chain by recognizing 3515 // they are side-effect free or do not alias. The optimizer should really 3516 // avoid this case by converting large object/array copies to llvm.memcpy 3517 // (MaxParallelChains should always remain as failsafe). 3518 if (ChainI == MaxParallelChains) { 3519 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3520 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3521 makeArrayRef(Chains.data(), ChainI)); 3522 Root = Chain; 3523 ChainI = 0; 3524 } 3525 SDValue A = DAG.getNode(ISD::ADD, dl, 3526 PtrVT, Ptr, 3527 DAG.getConstant(Offsets[i], dl, PtrVT), 3528 &Flags); 3529 auto MMOFlags = MachineMemOperand::MONone; 3530 if (isVolatile) 3531 MMOFlags |= MachineMemOperand::MOVolatile; 3532 if (isNonTemporal) 3533 MMOFlags |= MachineMemOperand::MONonTemporal; 3534 if (isInvariant) 3535 MMOFlags |= MachineMemOperand::MOInvariant; 3536 3537 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3538 MachinePointerInfo(SV, Offsets[i]), Alignment, 3539 MMOFlags, AAInfo, Ranges); 3540 3541 Values[i] = L; 3542 Chains[ChainI] = L.getValue(1); 3543 } 3544 3545 if (!ConstantMemory) { 3546 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3547 makeArrayRef(Chains.data(), ChainI)); 3548 if (isVolatile) 3549 DAG.setRoot(Chain); 3550 else 3551 PendingLoads.push_back(Chain); 3552 } 3553 3554 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3555 DAG.getVTList(ValueVTs), Values)); 3556 } 3557 3558 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3559 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3560 assert(TLI.supportSwiftError() && 3561 "call visitStoreToSwiftError when backend supports swifterror"); 3562 3563 SmallVector<EVT, 4> ValueVTs; 3564 SmallVector<uint64_t, 4> Offsets; 3565 const Value *SrcV = I.getOperand(0); 3566 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3567 SrcV->getType(), ValueVTs, &Offsets); 3568 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3569 "expect a single EVT for swifterror"); 3570 3571 SDValue Src = getValue(SrcV); 3572 // Create a virtual register, then update the virtual register. 3573 auto &DL = DAG.getDataLayout(); 3574 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL)); 3575 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC); 3576 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3577 // Chain can be getRoot or getControlRoot. 3578 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3579 SDValue(Src.getNode(), Src.getResNo())); 3580 DAG.setRoot(CopyNode); 3581 FuncInfo.setSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3582 } 3583 3584 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3585 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3586 "call visitLoadFromSwiftError when backend supports swifterror"); 3587 3588 assert(!I.isVolatile() && 3589 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3590 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3591 "Support volatile, non temporal, invariant for load_from_swift_error"); 3592 3593 const Value *SV = I.getOperand(0); 3594 Type *Ty = I.getType(); 3595 AAMDNodes AAInfo; 3596 I.getAAMetadata(AAInfo); 3597 assert(!AA->pointsToConstantMemory(MemoryLocation( 3598 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo)) && 3599 "load_from_swift_error should not be constant memory"); 3600 3601 SmallVector<EVT, 4> ValueVTs; 3602 SmallVector<uint64_t, 4> Offsets; 3603 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3604 ValueVTs, &Offsets); 3605 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3606 "expect a single EVT for swifterror"); 3607 3608 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3609 SDValue L = DAG.getCopyFromReg(getRoot(), getCurSDLoc(), 3610 FuncInfo.findSwiftErrorVReg(FuncInfo.MBB, SV), 3611 ValueVTs[0]); 3612 3613 setValue(&I, L); 3614 } 3615 3616 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3617 if (I.isAtomic()) 3618 return visitAtomicStore(I); 3619 3620 const Value *SrcV = I.getOperand(0); 3621 const Value *PtrV = I.getOperand(1); 3622 3623 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3624 if (TLI.supportSwiftError()) { 3625 // Swifterror values can come from either a function parameter with 3626 // swifterror attribute or an alloca with swifterror attribute. 3627 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3628 if (Arg->hasSwiftErrorAttr()) 3629 return visitStoreToSwiftError(I); 3630 } 3631 3632 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3633 if (Alloca->isSwiftError()) 3634 return visitStoreToSwiftError(I); 3635 } 3636 } 3637 3638 SmallVector<EVT, 4> ValueVTs; 3639 SmallVector<uint64_t, 4> Offsets; 3640 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3641 SrcV->getType(), ValueVTs, &Offsets); 3642 unsigned NumValues = ValueVTs.size(); 3643 if (NumValues == 0) 3644 return; 3645 3646 // Get the lowered operands. Note that we do this after 3647 // checking if NumResults is zero, because with zero results 3648 // the operands won't have values in the map. 3649 SDValue Src = getValue(SrcV); 3650 SDValue Ptr = getValue(PtrV); 3651 3652 SDValue Root = getRoot(); 3653 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3654 SDLoc dl = getCurSDLoc(); 3655 EVT PtrVT = Ptr.getValueType(); 3656 unsigned Alignment = I.getAlignment(); 3657 AAMDNodes AAInfo; 3658 I.getAAMetadata(AAInfo); 3659 3660 auto MMOFlags = MachineMemOperand::MONone; 3661 if (I.isVolatile()) 3662 MMOFlags |= MachineMemOperand::MOVolatile; 3663 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3664 MMOFlags |= MachineMemOperand::MONonTemporal; 3665 3666 // An aggregate load cannot wrap around the address space, so offsets to its 3667 // parts don't wrap either. 3668 SDNodeFlags Flags; 3669 Flags.setNoUnsignedWrap(true); 3670 3671 unsigned ChainI = 0; 3672 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3673 // See visitLoad comments. 3674 if (ChainI == MaxParallelChains) { 3675 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3676 makeArrayRef(Chains.data(), ChainI)); 3677 Root = Chain; 3678 ChainI = 0; 3679 } 3680 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3681 DAG.getConstant(Offsets[i], dl, PtrVT), &Flags); 3682 SDValue St = DAG.getStore( 3683 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3684 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3685 Chains[ChainI] = St; 3686 } 3687 3688 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3689 makeArrayRef(Chains.data(), ChainI)); 3690 DAG.setRoot(StoreNode); 3691 } 3692 3693 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) { 3694 SDLoc sdl = getCurSDLoc(); 3695 3696 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3697 Value *PtrOperand = I.getArgOperand(1); 3698 SDValue Ptr = getValue(PtrOperand); 3699 SDValue Src0 = getValue(I.getArgOperand(0)); 3700 SDValue Mask = getValue(I.getArgOperand(3)); 3701 EVT VT = Src0.getValueType(); 3702 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3703 if (!Alignment) 3704 Alignment = DAG.getEVTAlignment(VT); 3705 3706 AAMDNodes AAInfo; 3707 I.getAAMetadata(AAInfo); 3708 3709 MachineMemOperand *MMO = 3710 DAG.getMachineFunction(). 3711 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3712 MachineMemOperand::MOStore, VT.getStoreSize(), 3713 Alignment, AAInfo); 3714 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3715 MMO, false); 3716 DAG.setRoot(StoreNode); 3717 setValue(&I, StoreNode); 3718 } 3719 3720 // Get a uniform base for the Gather/Scatter intrinsic. 3721 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3722 // We try to represent it as a base pointer + vector of indices. 3723 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3724 // The first operand of the GEP may be a single pointer or a vector of pointers 3725 // Example: 3726 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3727 // or 3728 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3729 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3730 // 3731 // When the first GEP operand is a single pointer - it is the uniform base we 3732 // are looking for. If first operand of the GEP is a splat vector - we 3733 // extract the spalt value and use it as a uniform base. 3734 // In all other cases the function returns 'false'. 3735 // 3736 static bool getUniformBase(const Value *& Ptr, SDValue& Base, SDValue& Index, 3737 SelectionDAGBuilder* SDB) { 3738 3739 SelectionDAG& DAG = SDB->DAG; 3740 LLVMContext &Context = *DAG.getContext(); 3741 3742 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3743 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3744 if (!GEP || GEP->getNumOperands() > 2) 3745 return false; 3746 3747 const Value *GEPPtr = GEP->getPointerOperand(); 3748 if (!GEPPtr->getType()->isVectorTy()) 3749 Ptr = GEPPtr; 3750 else if (!(Ptr = getSplatValue(GEPPtr))) 3751 return false; 3752 3753 Value *IndexVal = GEP->getOperand(1); 3754 3755 // The operands of the GEP may be defined in another basic block. 3756 // In this case we'll not find nodes for the operands. 3757 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 3758 return false; 3759 3760 Base = SDB->getValue(Ptr); 3761 Index = SDB->getValue(IndexVal); 3762 3763 // Suppress sign extension. 3764 if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) { 3765 if (SDB->findValue(Sext->getOperand(0))) { 3766 IndexVal = Sext->getOperand(0); 3767 Index = SDB->getValue(IndexVal); 3768 } 3769 } 3770 if (!Index.getValueType().isVector()) { 3771 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 3772 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 3773 SmallVector<SDValue, 16> Ops(GEPWidth, Index); 3774 Index = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Index), VT, Ops); 3775 } 3776 return true; 3777 } 3778 3779 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 3780 SDLoc sdl = getCurSDLoc(); 3781 3782 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 3783 const Value *Ptr = I.getArgOperand(1); 3784 SDValue Src0 = getValue(I.getArgOperand(0)); 3785 SDValue Mask = getValue(I.getArgOperand(3)); 3786 EVT VT = Src0.getValueType(); 3787 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3788 if (!Alignment) 3789 Alignment = DAG.getEVTAlignment(VT); 3790 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3791 3792 AAMDNodes AAInfo; 3793 I.getAAMetadata(AAInfo); 3794 3795 SDValue Base; 3796 SDValue Index; 3797 const Value *BasePtr = Ptr; 3798 bool UniformBase = getUniformBase(BasePtr, Base, Index, this); 3799 3800 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 3801 MachineMemOperand *MMO = DAG.getMachineFunction(). 3802 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 3803 MachineMemOperand::MOStore, VT.getStoreSize(), 3804 Alignment, AAInfo); 3805 if (!UniformBase) { 3806 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 3807 Index = getValue(Ptr); 3808 } 3809 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index }; 3810 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 3811 Ops, MMO); 3812 DAG.setRoot(Scatter); 3813 setValue(&I, Scatter); 3814 } 3815 3816 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) { 3817 SDLoc sdl = getCurSDLoc(); 3818 3819 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 3820 Value *PtrOperand = I.getArgOperand(0); 3821 SDValue Ptr = getValue(PtrOperand); 3822 SDValue Src0 = getValue(I.getArgOperand(3)); 3823 SDValue Mask = getValue(I.getArgOperand(2)); 3824 3825 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3826 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3827 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 3828 if (!Alignment) 3829 Alignment = DAG.getEVTAlignment(VT); 3830 3831 AAMDNodes AAInfo; 3832 I.getAAMetadata(AAInfo); 3833 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3834 3835 // Do not serialize masked loads of constant memory with anything. 3836 bool AddToChain = !AA->pointsToConstantMemory(MemoryLocation( 3837 PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo)); 3838 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 3839 3840 MachineMemOperand *MMO = 3841 DAG.getMachineFunction(). 3842 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3843 MachineMemOperand::MOLoad, VT.getStoreSize(), 3844 Alignment, AAInfo, Ranges); 3845 3846 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 3847 ISD::NON_EXTLOAD); 3848 if (AddToChain) { 3849 SDValue OutChain = Load.getValue(1); 3850 DAG.setRoot(OutChain); 3851 } 3852 setValue(&I, Load); 3853 } 3854 3855 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 3856 SDLoc sdl = getCurSDLoc(); 3857 3858 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 3859 const Value *Ptr = I.getArgOperand(0); 3860 SDValue Src0 = getValue(I.getArgOperand(3)); 3861 SDValue Mask = getValue(I.getArgOperand(2)); 3862 3863 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3864 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3865 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 3866 if (!Alignment) 3867 Alignment = DAG.getEVTAlignment(VT); 3868 3869 AAMDNodes AAInfo; 3870 I.getAAMetadata(AAInfo); 3871 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3872 3873 SDValue Root = DAG.getRoot(); 3874 SDValue Base; 3875 SDValue Index; 3876 const Value *BasePtr = Ptr; 3877 bool UniformBase = getUniformBase(BasePtr, Base, Index, this); 3878 bool ConstantMemory = false; 3879 if (UniformBase && 3880 AA->pointsToConstantMemory(MemoryLocation( 3881 BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()), 3882 AAInfo))) { 3883 // Do not serialize (non-volatile) loads of constant memory with anything. 3884 Root = DAG.getEntryNode(); 3885 ConstantMemory = true; 3886 } 3887 3888 MachineMemOperand *MMO = 3889 DAG.getMachineFunction(). 3890 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 3891 MachineMemOperand::MOLoad, VT.getStoreSize(), 3892 Alignment, AAInfo, Ranges); 3893 3894 if (!UniformBase) { 3895 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 3896 Index = getValue(Ptr); 3897 } 3898 SDValue Ops[] = { Root, Src0, Mask, Base, Index }; 3899 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 3900 Ops, MMO); 3901 3902 SDValue OutChain = Gather.getValue(1); 3903 if (!ConstantMemory) 3904 PendingLoads.push_back(OutChain); 3905 setValue(&I, Gather); 3906 } 3907 3908 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 3909 SDLoc dl = getCurSDLoc(); 3910 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 3911 AtomicOrdering FailureOrder = I.getFailureOrdering(); 3912 SynchronizationScope Scope = I.getSynchScope(); 3913 3914 SDValue InChain = getRoot(); 3915 3916 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 3917 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 3918 SDValue L = DAG.getAtomicCmpSwap( 3919 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 3920 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 3921 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 3922 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope); 3923 3924 SDValue OutChain = L.getValue(2); 3925 3926 setValue(&I, L); 3927 DAG.setRoot(OutChain); 3928 } 3929 3930 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 3931 SDLoc dl = getCurSDLoc(); 3932 ISD::NodeType NT; 3933 switch (I.getOperation()) { 3934 default: llvm_unreachable("Unknown atomicrmw operation"); 3935 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 3936 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 3937 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 3938 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 3939 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 3940 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 3941 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 3942 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 3943 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 3944 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 3945 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 3946 } 3947 AtomicOrdering Order = I.getOrdering(); 3948 SynchronizationScope Scope = I.getSynchScope(); 3949 3950 SDValue InChain = getRoot(); 3951 3952 SDValue L = 3953 DAG.getAtomic(NT, dl, 3954 getValue(I.getValOperand()).getSimpleValueType(), 3955 InChain, 3956 getValue(I.getPointerOperand()), 3957 getValue(I.getValOperand()), 3958 I.getPointerOperand(), 3959 /* Alignment=*/ 0, Order, Scope); 3960 3961 SDValue OutChain = L.getValue(1); 3962 3963 setValue(&I, L); 3964 DAG.setRoot(OutChain); 3965 } 3966 3967 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 3968 SDLoc dl = getCurSDLoc(); 3969 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3970 SDValue Ops[3]; 3971 Ops[0] = getRoot(); 3972 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 3973 TLI.getPointerTy(DAG.getDataLayout())); 3974 Ops[2] = DAG.getConstant(I.getSynchScope(), dl, 3975 TLI.getPointerTy(DAG.getDataLayout())); 3976 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 3977 } 3978 3979 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 3980 SDLoc dl = getCurSDLoc(); 3981 AtomicOrdering Order = I.getOrdering(); 3982 SynchronizationScope Scope = I.getSynchScope(); 3983 3984 SDValue InChain = getRoot(); 3985 3986 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3987 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3988 3989 if (I.getAlignment() < VT.getSizeInBits() / 8) 3990 report_fatal_error("Cannot generate unaligned atomic load"); 3991 3992 MachineMemOperand *MMO = 3993 DAG.getMachineFunction(). 3994 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 3995 MachineMemOperand::MOVolatile | 3996 MachineMemOperand::MOLoad, 3997 VT.getStoreSize(), 3998 I.getAlignment() ? I.getAlignment() : 3999 DAG.getEVTAlignment(VT)); 4000 4001 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4002 SDValue L = 4003 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4004 getValue(I.getPointerOperand()), MMO, 4005 Order, Scope); 4006 4007 SDValue OutChain = L.getValue(1); 4008 4009 setValue(&I, L); 4010 DAG.setRoot(OutChain); 4011 } 4012 4013 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4014 SDLoc dl = getCurSDLoc(); 4015 4016 AtomicOrdering Order = I.getOrdering(); 4017 SynchronizationScope Scope = I.getSynchScope(); 4018 4019 SDValue InChain = getRoot(); 4020 4021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4022 EVT VT = 4023 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4024 4025 if (I.getAlignment() < VT.getSizeInBits() / 8) 4026 report_fatal_error("Cannot generate unaligned atomic store"); 4027 4028 SDValue OutChain = 4029 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4030 InChain, 4031 getValue(I.getPointerOperand()), 4032 getValue(I.getValueOperand()), 4033 I.getPointerOperand(), I.getAlignment(), 4034 Order, Scope); 4035 4036 DAG.setRoot(OutChain); 4037 } 4038 4039 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4040 /// node. 4041 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4042 unsigned Intrinsic) { 4043 bool HasChain = !I.doesNotAccessMemory(); 4044 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 4045 4046 // Build the operand list. 4047 SmallVector<SDValue, 8> Ops; 4048 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4049 if (OnlyLoad) { 4050 // We don't need to serialize loads against other loads. 4051 Ops.push_back(DAG.getRoot()); 4052 } else { 4053 Ops.push_back(getRoot()); 4054 } 4055 } 4056 4057 // Info is set by getTgtMemInstrinsic 4058 TargetLowering::IntrinsicInfo Info; 4059 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4060 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic); 4061 4062 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4063 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4064 Info.opc == ISD::INTRINSIC_W_CHAIN) 4065 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4066 TLI.getPointerTy(DAG.getDataLayout()))); 4067 4068 // Add all operands of the call to the operand list. 4069 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4070 SDValue Op = getValue(I.getArgOperand(i)); 4071 Ops.push_back(Op); 4072 } 4073 4074 SmallVector<EVT, 4> ValueVTs; 4075 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4076 4077 if (HasChain) 4078 ValueVTs.push_back(MVT::Other); 4079 4080 SDVTList VTs = DAG.getVTList(ValueVTs); 4081 4082 // Create the node. 4083 SDValue Result; 4084 if (IsTgtIntrinsic) { 4085 // This is target intrinsic that touches memory 4086 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), 4087 VTs, Ops, Info.memVT, 4088 MachinePointerInfo(Info.ptrVal, Info.offset), 4089 Info.align, Info.vol, 4090 Info.readMem, Info.writeMem, Info.size); 4091 } else if (!HasChain) { 4092 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4093 } else if (!I.getType()->isVoidTy()) { 4094 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4095 } else { 4096 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4097 } 4098 4099 if (HasChain) { 4100 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4101 if (OnlyLoad) 4102 PendingLoads.push_back(Chain); 4103 else 4104 DAG.setRoot(Chain); 4105 } 4106 4107 if (!I.getType()->isVoidTy()) { 4108 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4109 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4110 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4111 } else 4112 Result = lowerRangeToAssertZExt(DAG, I, Result); 4113 4114 setValue(&I, Result); 4115 } 4116 } 4117 4118 /// GetSignificand - Get the significand and build it into a floating-point 4119 /// number with exponent of 1: 4120 /// 4121 /// Op = (Op & 0x007fffff) | 0x3f800000; 4122 /// 4123 /// where Op is the hexadecimal representation of floating point value. 4124 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4125 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4126 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4127 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4128 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4129 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4130 } 4131 4132 /// GetExponent - Get the exponent: 4133 /// 4134 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4135 /// 4136 /// where Op is the hexadecimal representation of floating point value. 4137 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4138 const TargetLowering &TLI, const SDLoc &dl) { 4139 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4140 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4141 SDValue t1 = DAG.getNode( 4142 ISD::SRL, dl, MVT::i32, t0, 4143 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4144 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4145 DAG.getConstant(127, dl, MVT::i32)); 4146 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4147 } 4148 4149 /// getF32Constant - Get 32-bit floating point constant. 4150 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4151 const SDLoc &dl) { 4152 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl, 4153 MVT::f32); 4154 } 4155 4156 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4157 SelectionDAG &DAG) { 4158 // TODO: What fast-math-flags should be set on the floating-point nodes? 4159 4160 // IntegerPartOfX = ((int32_t)(t0); 4161 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4162 4163 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4164 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4165 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4166 4167 // IntegerPartOfX <<= 23; 4168 IntegerPartOfX = DAG.getNode( 4169 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4170 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4171 DAG.getDataLayout()))); 4172 4173 SDValue TwoToFractionalPartOfX; 4174 if (LimitFloatPrecision <= 6) { 4175 // For floating-point precision of 6: 4176 // 4177 // TwoToFractionalPartOfX = 4178 // 0.997535578f + 4179 // (0.735607626f + 0.252464424f * x) * x; 4180 // 4181 // error 0.0144103317, which is 6 bits 4182 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4183 getF32Constant(DAG, 0x3e814304, dl)); 4184 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4185 getF32Constant(DAG, 0x3f3c50c8, dl)); 4186 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4187 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4188 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4189 } else if (LimitFloatPrecision <= 12) { 4190 // For floating-point precision of 12: 4191 // 4192 // TwoToFractionalPartOfX = 4193 // 0.999892986f + 4194 // (0.696457318f + 4195 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4196 // 4197 // error 0.000107046256, which is 13 to 14 bits 4198 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4199 getF32Constant(DAG, 0x3da235e3, dl)); 4200 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4201 getF32Constant(DAG, 0x3e65b8f3, dl)); 4202 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4203 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4204 getF32Constant(DAG, 0x3f324b07, dl)); 4205 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4206 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4207 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4208 } else { // LimitFloatPrecision <= 18 4209 // For floating-point precision of 18: 4210 // 4211 // TwoToFractionalPartOfX = 4212 // 0.999999982f + 4213 // (0.693148872f + 4214 // (0.240227044f + 4215 // (0.554906021e-1f + 4216 // (0.961591928e-2f + 4217 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4218 // error 2.47208000*10^(-7), which is better than 18 bits 4219 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4220 getF32Constant(DAG, 0x3924b03e, dl)); 4221 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4222 getF32Constant(DAG, 0x3ab24b87, dl)); 4223 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4224 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4225 getF32Constant(DAG, 0x3c1d8c17, dl)); 4226 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4227 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4228 getF32Constant(DAG, 0x3d634a1d, dl)); 4229 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4230 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4231 getF32Constant(DAG, 0x3e75fe14, dl)); 4232 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4233 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4234 getF32Constant(DAG, 0x3f317234, dl)); 4235 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4236 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4237 getF32Constant(DAG, 0x3f800000, dl)); 4238 } 4239 4240 // Add the exponent into the result in integer domain. 4241 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4242 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4243 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4244 } 4245 4246 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4247 /// limited-precision mode. 4248 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4249 const TargetLowering &TLI) { 4250 if (Op.getValueType() == MVT::f32 && 4251 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4252 4253 // Put the exponent in the right bit position for later addition to the 4254 // final result: 4255 // 4256 // #define LOG2OFe 1.4426950f 4257 // t0 = Op * LOG2OFe 4258 4259 // TODO: What fast-math-flags should be set here? 4260 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4261 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4262 return getLimitedPrecisionExp2(t0, dl, DAG); 4263 } 4264 4265 // No special expansion. 4266 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4267 } 4268 4269 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4270 /// limited-precision mode. 4271 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4272 const TargetLowering &TLI) { 4273 4274 // TODO: What fast-math-flags should be set on the floating-point nodes? 4275 4276 if (Op.getValueType() == MVT::f32 && 4277 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4278 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4279 4280 // Scale the exponent by log(2) [0.69314718f]. 4281 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4282 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4283 getF32Constant(DAG, 0x3f317218, dl)); 4284 4285 // Get the significand and build it into a floating-point number with 4286 // exponent of 1. 4287 SDValue X = GetSignificand(DAG, Op1, dl); 4288 4289 SDValue LogOfMantissa; 4290 if (LimitFloatPrecision <= 6) { 4291 // For floating-point precision of 6: 4292 // 4293 // LogofMantissa = 4294 // -1.1609546f + 4295 // (1.4034025f - 0.23903021f * x) * x; 4296 // 4297 // error 0.0034276066, which is better than 8 bits 4298 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4299 getF32Constant(DAG, 0xbe74c456, dl)); 4300 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4301 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4302 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4303 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4304 getF32Constant(DAG, 0x3f949a29, dl)); 4305 } else if (LimitFloatPrecision <= 12) { 4306 // For floating-point precision of 12: 4307 // 4308 // LogOfMantissa = 4309 // -1.7417939f + 4310 // (2.8212026f + 4311 // (-1.4699568f + 4312 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4313 // 4314 // error 0.000061011436, which is 14 bits 4315 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4316 getF32Constant(DAG, 0xbd67b6d6, dl)); 4317 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4318 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4319 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4320 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4321 getF32Constant(DAG, 0x3fbc278b, dl)); 4322 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4323 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4324 getF32Constant(DAG, 0x40348e95, dl)); 4325 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4326 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4327 getF32Constant(DAG, 0x3fdef31a, dl)); 4328 } else { // LimitFloatPrecision <= 18 4329 // For floating-point precision of 18: 4330 // 4331 // LogOfMantissa = 4332 // -2.1072184f + 4333 // (4.2372794f + 4334 // (-3.7029485f + 4335 // (2.2781945f + 4336 // (-0.87823314f + 4337 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4338 // 4339 // error 0.0000023660568, which is better than 18 bits 4340 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4341 getF32Constant(DAG, 0xbc91e5ac, dl)); 4342 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4343 getF32Constant(DAG, 0x3e4350aa, dl)); 4344 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4345 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4346 getF32Constant(DAG, 0x3f60d3e3, dl)); 4347 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4348 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4349 getF32Constant(DAG, 0x4011cdf0, dl)); 4350 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4351 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4352 getF32Constant(DAG, 0x406cfd1c, dl)); 4353 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4354 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4355 getF32Constant(DAG, 0x408797cb, dl)); 4356 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4357 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4358 getF32Constant(DAG, 0x4006dcab, dl)); 4359 } 4360 4361 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4362 } 4363 4364 // No special expansion. 4365 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4366 } 4367 4368 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4369 /// limited-precision mode. 4370 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4371 const TargetLowering &TLI) { 4372 4373 // TODO: What fast-math-flags should be set on the floating-point nodes? 4374 4375 if (Op.getValueType() == MVT::f32 && 4376 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4377 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4378 4379 // Get the exponent. 4380 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4381 4382 // Get the significand and build it into a floating-point number with 4383 // exponent of 1. 4384 SDValue X = GetSignificand(DAG, Op1, dl); 4385 4386 // Different possible minimax approximations of significand in 4387 // floating-point for various degrees of accuracy over [1,2]. 4388 SDValue Log2ofMantissa; 4389 if (LimitFloatPrecision <= 6) { 4390 // For floating-point precision of 6: 4391 // 4392 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4393 // 4394 // error 0.0049451742, which is more than 7 bits 4395 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4396 getF32Constant(DAG, 0xbeb08fe0, dl)); 4397 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4398 getF32Constant(DAG, 0x40019463, dl)); 4399 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4400 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4401 getF32Constant(DAG, 0x3fd6633d, dl)); 4402 } else if (LimitFloatPrecision <= 12) { 4403 // For floating-point precision of 12: 4404 // 4405 // Log2ofMantissa = 4406 // -2.51285454f + 4407 // (4.07009056f + 4408 // (-2.12067489f + 4409 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4410 // 4411 // error 0.0000876136000, which is better than 13 bits 4412 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4413 getF32Constant(DAG, 0xbda7262e, dl)); 4414 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4415 getF32Constant(DAG, 0x3f25280b, dl)); 4416 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4417 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4418 getF32Constant(DAG, 0x4007b923, dl)); 4419 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4420 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4421 getF32Constant(DAG, 0x40823e2f, dl)); 4422 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4423 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4424 getF32Constant(DAG, 0x4020d29c, dl)); 4425 } else { // LimitFloatPrecision <= 18 4426 // For floating-point precision of 18: 4427 // 4428 // Log2ofMantissa = 4429 // -3.0400495f + 4430 // (6.1129976f + 4431 // (-5.3420409f + 4432 // (3.2865683f + 4433 // (-1.2669343f + 4434 // (0.27515199f - 4435 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4436 // 4437 // error 0.0000018516, which is better than 18 bits 4438 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4439 getF32Constant(DAG, 0xbcd2769e, dl)); 4440 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4441 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4442 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4443 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4444 getF32Constant(DAG, 0x3fa22ae7, dl)); 4445 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4446 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4447 getF32Constant(DAG, 0x40525723, dl)); 4448 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4449 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4450 getF32Constant(DAG, 0x40aaf200, dl)); 4451 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4452 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4453 getF32Constant(DAG, 0x40c39dad, dl)); 4454 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4455 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4456 getF32Constant(DAG, 0x4042902c, dl)); 4457 } 4458 4459 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4460 } 4461 4462 // No special expansion. 4463 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4464 } 4465 4466 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4467 /// limited-precision mode. 4468 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4469 const TargetLowering &TLI) { 4470 4471 // TODO: What fast-math-flags should be set on the floating-point nodes? 4472 4473 if (Op.getValueType() == MVT::f32 && 4474 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4475 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4476 4477 // Scale the exponent by log10(2) [0.30102999f]. 4478 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4479 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4480 getF32Constant(DAG, 0x3e9a209a, dl)); 4481 4482 // Get the significand and build it into a floating-point number with 4483 // exponent of 1. 4484 SDValue X = GetSignificand(DAG, Op1, dl); 4485 4486 SDValue Log10ofMantissa; 4487 if (LimitFloatPrecision <= 6) { 4488 // For floating-point precision of 6: 4489 // 4490 // Log10ofMantissa = 4491 // -0.50419619f + 4492 // (0.60948995f - 0.10380950f * x) * x; 4493 // 4494 // error 0.0014886165, which is 6 bits 4495 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4496 getF32Constant(DAG, 0xbdd49a13, dl)); 4497 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4498 getF32Constant(DAG, 0x3f1c0789, dl)); 4499 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4500 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4501 getF32Constant(DAG, 0x3f011300, dl)); 4502 } else if (LimitFloatPrecision <= 12) { 4503 // For floating-point precision of 12: 4504 // 4505 // Log10ofMantissa = 4506 // -0.64831180f + 4507 // (0.91751397f + 4508 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4509 // 4510 // error 0.00019228036, which is better than 12 bits 4511 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4512 getF32Constant(DAG, 0x3d431f31, dl)); 4513 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4514 getF32Constant(DAG, 0x3ea21fb2, dl)); 4515 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4516 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4517 getF32Constant(DAG, 0x3f6ae232, dl)); 4518 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4519 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4520 getF32Constant(DAG, 0x3f25f7c3, dl)); 4521 } else { // LimitFloatPrecision <= 18 4522 // For floating-point precision of 18: 4523 // 4524 // Log10ofMantissa = 4525 // -0.84299375f + 4526 // (1.5327582f + 4527 // (-1.0688956f + 4528 // (0.49102474f + 4529 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4530 // 4531 // error 0.0000037995730, which is better than 18 bits 4532 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4533 getF32Constant(DAG, 0x3c5d51ce, dl)); 4534 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4535 getF32Constant(DAG, 0x3e00685a, dl)); 4536 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4537 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4538 getF32Constant(DAG, 0x3efb6798, dl)); 4539 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4540 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4541 getF32Constant(DAG, 0x3f88d192, dl)); 4542 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4543 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4544 getF32Constant(DAG, 0x3fc4316c, dl)); 4545 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4546 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4547 getF32Constant(DAG, 0x3f57ce70, dl)); 4548 } 4549 4550 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4551 } 4552 4553 // No special expansion. 4554 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4555 } 4556 4557 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4558 /// limited-precision mode. 4559 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4560 const TargetLowering &TLI) { 4561 if (Op.getValueType() == MVT::f32 && 4562 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4563 return getLimitedPrecisionExp2(Op, dl, DAG); 4564 4565 // No special expansion. 4566 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4567 } 4568 4569 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4570 /// limited-precision mode with x == 10.0f. 4571 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4572 SelectionDAG &DAG, const TargetLowering &TLI) { 4573 bool IsExp10 = false; 4574 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4575 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4576 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4577 APFloat Ten(10.0f); 4578 IsExp10 = LHSC->isExactlyValue(Ten); 4579 } 4580 } 4581 4582 // TODO: What fast-math-flags should be set on the FMUL node? 4583 if (IsExp10) { 4584 // Put the exponent in the right bit position for later addition to the 4585 // final result: 4586 // 4587 // #define LOG2OF10 3.3219281f 4588 // t0 = Op * LOG2OF10; 4589 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4590 getF32Constant(DAG, 0x40549a78, dl)); 4591 return getLimitedPrecisionExp2(t0, dl, DAG); 4592 } 4593 4594 // No special expansion. 4595 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4596 } 4597 4598 4599 /// ExpandPowI - Expand a llvm.powi intrinsic. 4600 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4601 SelectionDAG &DAG) { 4602 // If RHS is a constant, we can expand this out to a multiplication tree, 4603 // otherwise we end up lowering to a call to __powidf2 (for example). When 4604 // optimizing for size, we only want to do this if the expansion would produce 4605 // a small number of multiplies, otherwise we do the full expansion. 4606 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4607 // Get the exponent as a positive value. 4608 unsigned Val = RHSC->getSExtValue(); 4609 if ((int)Val < 0) Val = -Val; 4610 4611 // powi(x, 0) -> 1.0 4612 if (Val == 0) 4613 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4614 4615 const Function *F = DAG.getMachineFunction().getFunction(); 4616 if (!F->optForSize() || 4617 // If optimizing for size, don't insert too many multiplies. 4618 // This inserts up to 5 multiplies. 4619 countPopulation(Val) + Log2_32(Val) < 7) { 4620 // We use the simple binary decomposition method to generate the multiply 4621 // sequence. There are more optimal ways to do this (for example, 4622 // powi(x,15) generates one more multiply than it should), but this has 4623 // the benefit of being both really simple and much better than a libcall. 4624 SDValue Res; // Logically starts equal to 1.0 4625 SDValue CurSquare = LHS; 4626 // TODO: Intrinsics should have fast-math-flags that propagate to these 4627 // nodes. 4628 while (Val) { 4629 if (Val & 1) { 4630 if (Res.getNode()) 4631 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4632 else 4633 Res = CurSquare; // 1.0*CurSquare. 4634 } 4635 4636 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4637 CurSquare, CurSquare); 4638 Val >>= 1; 4639 } 4640 4641 // If the original was negative, invert the result, producing 1/(x*x*x). 4642 if (RHSC->getSExtValue() < 0) 4643 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4644 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4645 return Res; 4646 } 4647 } 4648 4649 // Otherwise, expand to a libcall. 4650 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4651 } 4652 4653 // getUnderlyingArgReg - Find underlying register used for a truncated or 4654 // bitcasted argument. 4655 static unsigned getUnderlyingArgReg(const SDValue &N) { 4656 switch (N.getOpcode()) { 4657 case ISD::CopyFromReg: 4658 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4659 case ISD::BITCAST: 4660 case ISD::AssertZext: 4661 case ISD::AssertSext: 4662 case ISD::TRUNCATE: 4663 return getUnderlyingArgReg(N.getOperand(0)); 4664 default: 4665 return 0; 4666 } 4667 } 4668 4669 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function 4670 /// argument, create the corresponding DBG_VALUE machine instruction for it now. 4671 /// At the end of instruction selection, they will be inserted to the entry BB. 4672 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4673 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4674 DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) { 4675 const Argument *Arg = dyn_cast<Argument>(V); 4676 if (!Arg) 4677 return false; 4678 4679 MachineFunction &MF = DAG.getMachineFunction(); 4680 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4681 4682 // Ignore inlined function arguments here. 4683 // 4684 // FIXME: Should we be checking DL->inlinedAt() to determine this? 4685 if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction())) 4686 return false; 4687 4688 Optional<MachineOperand> Op; 4689 // Some arguments' frame index is recorded during argument lowering. 4690 if (int FI = FuncInfo.getArgumentFrameIndex(Arg)) 4691 Op = MachineOperand::CreateFI(FI); 4692 4693 if (!Op && N.getNode()) { 4694 unsigned Reg = getUnderlyingArgReg(N); 4695 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4696 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4697 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4698 if (PR) 4699 Reg = PR; 4700 } 4701 if (Reg) 4702 Op = MachineOperand::CreateReg(Reg, false); 4703 } 4704 4705 if (!Op) { 4706 // Check if ValueMap has reg number. 4707 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4708 if (VMI != FuncInfo.ValueMap.end()) 4709 Op = MachineOperand::CreateReg(VMI->second, false); 4710 } 4711 4712 if (!Op && N.getNode()) 4713 // Check if frame index is available. 4714 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4715 if (FrameIndexSDNode *FINode = 4716 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4717 Op = MachineOperand::CreateFI(FINode->getIndex()); 4718 4719 if (!Op) 4720 return false; 4721 4722 assert(Variable->isValidLocationForIntrinsic(DL) && 4723 "Expected inlined-at fields to agree"); 4724 if (Op->isReg()) 4725 FuncInfo.ArgDbgValues.push_back( 4726 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 4727 Op->getReg(), Offset, Variable, Expr)); 4728 else 4729 FuncInfo.ArgDbgValues.push_back( 4730 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)) 4731 .addOperand(*Op) 4732 .addImm(Offset) 4733 .addMetadata(Variable) 4734 .addMetadata(Expr)); 4735 4736 return true; 4737 } 4738 4739 /// Return the appropriate SDDbgValue based on N. 4740 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 4741 DILocalVariable *Variable, 4742 DIExpression *Expr, int64_t Offset, 4743 DebugLoc dl, 4744 unsigned DbgSDNodeOrder) { 4745 SDDbgValue *SDV; 4746 auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode()); 4747 if (FISDN && Expr->startsWithDeref()) { 4748 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 4749 // stack slot locations as such instead of as indirectly addressed 4750 // locations. 4751 ArrayRef<uint64_t> TrailingElements(Expr->elements_begin() + 1, 4752 Expr->elements_end()); 4753 DIExpression *DerefedDIExpr = 4754 DIExpression::get(*DAG.getContext(), TrailingElements); 4755 int FI = FISDN->getIndex(); 4756 SDV = DAG.getFrameIndexDbgValue(Variable, DerefedDIExpr, FI, 0, dl, 4757 DbgSDNodeOrder); 4758 } else { 4759 SDV = DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, 4760 Offset, dl, DbgSDNodeOrder); 4761 } 4762 return SDV; 4763 } 4764 4765 // VisualStudio defines setjmp as _setjmp 4766 #if defined(_MSC_VER) && defined(setjmp) && \ 4767 !defined(setjmp_undefined_for_msvc) 4768 # pragma push_macro("setjmp") 4769 # undef setjmp 4770 # define setjmp_undefined_for_msvc 4771 #endif 4772 4773 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 4774 /// we want to emit this as a call to a named external function, return the name 4775 /// otherwise lower it and return null. 4776 const char * 4777 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 4778 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4779 SDLoc sdl = getCurSDLoc(); 4780 DebugLoc dl = getCurDebugLoc(); 4781 SDValue Res; 4782 4783 switch (Intrinsic) { 4784 default: 4785 // By default, turn this into a target intrinsic node. 4786 visitTargetIntrinsic(I, Intrinsic); 4787 return nullptr; 4788 case Intrinsic::vastart: visitVAStart(I); return nullptr; 4789 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 4790 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 4791 case Intrinsic::returnaddress: 4792 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 4793 TLI.getPointerTy(DAG.getDataLayout()), 4794 getValue(I.getArgOperand(0)))); 4795 return nullptr; 4796 case Intrinsic::frameaddress: 4797 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 4798 TLI.getPointerTy(DAG.getDataLayout()), 4799 getValue(I.getArgOperand(0)))); 4800 return nullptr; 4801 case Intrinsic::read_register: { 4802 Value *Reg = I.getArgOperand(0); 4803 SDValue Chain = getRoot(); 4804 SDValue RegName = 4805 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 4806 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4807 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 4808 DAG.getVTList(VT, MVT::Other), Chain, RegName); 4809 setValue(&I, Res); 4810 DAG.setRoot(Res.getValue(1)); 4811 return nullptr; 4812 } 4813 case Intrinsic::write_register: { 4814 Value *Reg = I.getArgOperand(0); 4815 Value *RegValue = I.getArgOperand(1); 4816 SDValue Chain = getRoot(); 4817 SDValue RegName = 4818 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 4819 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 4820 RegName, getValue(RegValue))); 4821 return nullptr; 4822 } 4823 case Intrinsic::setjmp: 4824 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 4825 case Intrinsic::longjmp: 4826 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 4827 case Intrinsic::memcpy: { 4828 SDValue Op1 = getValue(I.getArgOperand(0)); 4829 SDValue Op2 = getValue(I.getArgOperand(1)); 4830 SDValue Op3 = getValue(I.getArgOperand(2)); 4831 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4832 if (!Align) 4833 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment. 4834 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4835 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4836 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4837 false, isTC, 4838 MachinePointerInfo(I.getArgOperand(0)), 4839 MachinePointerInfo(I.getArgOperand(1))); 4840 updateDAGForMaybeTailCall(MC); 4841 return nullptr; 4842 } 4843 case Intrinsic::memset: { 4844 SDValue Op1 = getValue(I.getArgOperand(0)); 4845 SDValue Op2 = getValue(I.getArgOperand(1)); 4846 SDValue Op3 = getValue(I.getArgOperand(2)); 4847 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4848 if (!Align) 4849 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment. 4850 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4851 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4852 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4853 isTC, MachinePointerInfo(I.getArgOperand(0))); 4854 updateDAGForMaybeTailCall(MS); 4855 return nullptr; 4856 } 4857 case Intrinsic::memmove: { 4858 SDValue Op1 = getValue(I.getArgOperand(0)); 4859 SDValue Op2 = getValue(I.getArgOperand(1)); 4860 SDValue Op3 = getValue(I.getArgOperand(2)); 4861 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4862 if (!Align) 4863 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment. 4864 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4865 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4866 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4867 isTC, MachinePointerInfo(I.getArgOperand(0)), 4868 MachinePointerInfo(I.getArgOperand(1))); 4869 updateDAGForMaybeTailCall(MM); 4870 return nullptr; 4871 } 4872 case Intrinsic::dbg_declare: { 4873 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 4874 DILocalVariable *Variable = DI.getVariable(); 4875 DIExpression *Expression = DI.getExpression(); 4876 const Value *Address = DI.getAddress(); 4877 assert(Variable && "Missing variable"); 4878 if (!Address) { 4879 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4880 return nullptr; 4881 } 4882 4883 // Check if address has undef value. 4884 if (isa<UndefValue>(Address) || 4885 (Address->use_empty() && !isa<Argument>(Address))) { 4886 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4887 return nullptr; 4888 } 4889 4890 SDValue &N = NodeMap[Address]; 4891 if (!N.getNode() && isa<Argument>(Address)) 4892 // Check unused arguments map. 4893 N = UnusedArgNodeMap[Address]; 4894 SDDbgValue *SDV; 4895 if (N.getNode()) { 4896 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 4897 Address = BCI->getOperand(0); 4898 // Parameters are handled specially. 4899 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 4900 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 4901 if (isParameter && FINode) { 4902 // Byval parameter. We have a frame index at this point. 4903 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, 4904 FINode->getIndex(), 0, dl, SDNodeOrder); 4905 } else if (isa<Argument>(Address)) { 4906 // Address is an argument, so try to emit its dbg value using 4907 // virtual register info from the FuncInfo.ValueMap. 4908 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false, 4909 N); 4910 return nullptr; 4911 } else { 4912 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 4913 true, 0, dl, SDNodeOrder); 4914 } 4915 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 4916 } else { 4917 // If Address is an argument then try to emit its dbg value using 4918 // virtual register info from the FuncInfo.ValueMap. 4919 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false, 4920 N)) { 4921 // If variable is pinned by a alloca in dominating bb then 4922 // use StaticAllocaMap. 4923 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) { 4924 if (AI->getParent() != DI.getParent()) { 4925 DenseMap<const AllocaInst*, int>::iterator SI = 4926 FuncInfo.StaticAllocaMap.find(AI); 4927 if (SI != FuncInfo.StaticAllocaMap.end()) { 4928 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second, 4929 0, dl, SDNodeOrder); 4930 DAG.AddDbgValue(SDV, nullptr, false); 4931 return nullptr; 4932 } 4933 } 4934 } 4935 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4936 } 4937 } 4938 return nullptr; 4939 } 4940 case Intrinsic::dbg_value: { 4941 const DbgValueInst &DI = cast<DbgValueInst>(I); 4942 assert(DI.getVariable() && "Missing variable"); 4943 4944 DILocalVariable *Variable = DI.getVariable(); 4945 DIExpression *Expression = DI.getExpression(); 4946 uint64_t Offset = DI.getOffset(); 4947 const Value *V = DI.getValue(); 4948 if (!V) 4949 return nullptr; 4950 4951 SDDbgValue *SDV; 4952 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 4953 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl, 4954 SDNodeOrder); 4955 DAG.AddDbgValue(SDV, nullptr, false); 4956 } else { 4957 // Do not use getValue() in here; we don't want to generate code at 4958 // this point if it hasn't been done yet. 4959 SDValue N = NodeMap[V]; 4960 if (!N.getNode() && isa<Argument>(V)) 4961 // Check unused arguments map. 4962 N = UnusedArgNodeMap[V]; 4963 if (N.getNode()) { 4964 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset, 4965 false, N)) { 4966 SDV = getDbgValue(N, Variable, Expression, Offset, dl, SDNodeOrder); 4967 DAG.AddDbgValue(SDV, N.getNode(), false); 4968 } 4969 } else if (!V->use_empty() ) { 4970 // Do not call getValue(V) yet, as we don't want to generate code. 4971 // Remember it for later. 4972 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder); 4973 DanglingDebugInfoMap[V] = DDI; 4974 } else { 4975 // We may expand this to cover more cases. One case where we have no 4976 // data available is an unreferenced parameter. 4977 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4978 } 4979 } 4980 4981 // Build a debug info table entry. 4982 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 4983 V = BCI->getOperand(0); 4984 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 4985 // Don't handle byval struct arguments or VLAs, for example. 4986 if (!AI) { 4987 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 4988 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 4989 return nullptr; 4990 } 4991 DenseMap<const AllocaInst*, int>::iterator SI = 4992 FuncInfo.StaticAllocaMap.find(AI); 4993 if (SI == FuncInfo.StaticAllocaMap.end()) 4994 return nullptr; // VLAs. 4995 return nullptr; 4996 } 4997 4998 case Intrinsic::eh_typeid_for: { 4999 // Find the type id for the given typeinfo. 5000 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5001 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV); 5002 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5003 setValue(&I, Res); 5004 return nullptr; 5005 } 5006 5007 case Intrinsic::eh_return_i32: 5008 case Intrinsic::eh_return_i64: 5009 DAG.getMachineFunction().getMMI().setCallsEHReturn(true); 5010 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5011 MVT::Other, 5012 getControlRoot(), 5013 getValue(I.getArgOperand(0)), 5014 getValue(I.getArgOperand(1)))); 5015 return nullptr; 5016 case Intrinsic::eh_unwind_init: 5017 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true); 5018 return nullptr; 5019 case Intrinsic::eh_dwarf_cfa: { 5020 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl, 5021 TLI.getPointerTy(DAG.getDataLayout())); 5022 SDValue Offset = DAG.getNode(ISD::ADD, sdl, 5023 CfaArg.getValueType(), 5024 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl, 5025 CfaArg.getValueType()), 5026 CfaArg); 5027 SDValue FA = DAG.getNode( 5028 ISD::FRAMEADDR, sdl, TLI.getPointerTy(DAG.getDataLayout()), 5029 DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 5030 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(), 5031 FA, Offset)); 5032 return nullptr; 5033 } 5034 case Intrinsic::eh_sjlj_callsite: { 5035 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5036 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5037 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5038 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5039 5040 MMI.setCurrentCallSite(CI->getZExtValue()); 5041 return nullptr; 5042 } 5043 case Intrinsic::eh_sjlj_functioncontext: { 5044 // Get and store the index of the function context. 5045 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5046 AllocaInst *FnCtx = 5047 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5048 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5049 MFI.setFunctionContextIndex(FI); 5050 return nullptr; 5051 } 5052 case Intrinsic::eh_sjlj_setjmp: { 5053 SDValue Ops[2]; 5054 Ops[0] = getRoot(); 5055 Ops[1] = getValue(I.getArgOperand(0)); 5056 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5057 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5058 setValue(&I, Op.getValue(0)); 5059 DAG.setRoot(Op.getValue(1)); 5060 return nullptr; 5061 } 5062 case Intrinsic::eh_sjlj_longjmp: { 5063 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5064 getRoot(), getValue(I.getArgOperand(0)))); 5065 return nullptr; 5066 } 5067 case Intrinsic::eh_sjlj_setup_dispatch: { 5068 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5069 getRoot())); 5070 return nullptr; 5071 } 5072 5073 case Intrinsic::masked_gather: 5074 visitMaskedGather(I); 5075 return nullptr; 5076 case Intrinsic::masked_load: 5077 visitMaskedLoad(I); 5078 return nullptr; 5079 case Intrinsic::masked_scatter: 5080 visitMaskedScatter(I); 5081 return nullptr; 5082 case Intrinsic::masked_store: 5083 visitMaskedStore(I); 5084 return nullptr; 5085 case Intrinsic::x86_mmx_pslli_w: 5086 case Intrinsic::x86_mmx_pslli_d: 5087 case Intrinsic::x86_mmx_pslli_q: 5088 case Intrinsic::x86_mmx_psrli_w: 5089 case Intrinsic::x86_mmx_psrli_d: 5090 case Intrinsic::x86_mmx_psrli_q: 5091 case Intrinsic::x86_mmx_psrai_w: 5092 case Intrinsic::x86_mmx_psrai_d: { 5093 SDValue ShAmt = getValue(I.getArgOperand(1)); 5094 if (isa<ConstantSDNode>(ShAmt)) { 5095 visitTargetIntrinsic(I, Intrinsic); 5096 return nullptr; 5097 } 5098 unsigned NewIntrinsic = 0; 5099 EVT ShAmtVT = MVT::v2i32; 5100 switch (Intrinsic) { 5101 case Intrinsic::x86_mmx_pslli_w: 5102 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5103 break; 5104 case Intrinsic::x86_mmx_pslli_d: 5105 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5106 break; 5107 case Intrinsic::x86_mmx_pslli_q: 5108 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5109 break; 5110 case Intrinsic::x86_mmx_psrli_w: 5111 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5112 break; 5113 case Intrinsic::x86_mmx_psrli_d: 5114 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5115 break; 5116 case Intrinsic::x86_mmx_psrli_q: 5117 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5118 break; 5119 case Intrinsic::x86_mmx_psrai_w: 5120 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5121 break; 5122 case Intrinsic::x86_mmx_psrai_d: 5123 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5124 break; 5125 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5126 } 5127 5128 // The vector shift intrinsics with scalars uses 32b shift amounts but 5129 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5130 // to be zero. 5131 // We must do this early because v2i32 is not a legal type. 5132 SDValue ShOps[2]; 5133 ShOps[0] = ShAmt; 5134 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5135 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps); 5136 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5137 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5138 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5139 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5140 getValue(I.getArgOperand(0)), ShAmt); 5141 setValue(&I, Res); 5142 return nullptr; 5143 } 5144 case Intrinsic::convertff: 5145 case Intrinsic::convertfsi: 5146 case Intrinsic::convertfui: 5147 case Intrinsic::convertsif: 5148 case Intrinsic::convertuif: 5149 case Intrinsic::convertss: 5150 case Intrinsic::convertsu: 5151 case Intrinsic::convertus: 5152 case Intrinsic::convertuu: { 5153 ISD::CvtCode Code = ISD::CVT_INVALID; 5154 switch (Intrinsic) { 5155 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5156 case Intrinsic::convertff: Code = ISD::CVT_FF; break; 5157 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break; 5158 case Intrinsic::convertfui: Code = ISD::CVT_FU; break; 5159 case Intrinsic::convertsif: Code = ISD::CVT_SF; break; 5160 case Intrinsic::convertuif: Code = ISD::CVT_UF; break; 5161 case Intrinsic::convertss: Code = ISD::CVT_SS; break; 5162 case Intrinsic::convertsu: Code = ISD::CVT_SU; break; 5163 case Intrinsic::convertus: Code = ISD::CVT_US; break; 5164 case Intrinsic::convertuu: Code = ISD::CVT_UU; break; 5165 } 5166 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5167 const Value *Op1 = I.getArgOperand(0); 5168 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1), 5169 DAG.getValueType(DestVT), 5170 DAG.getValueType(getValue(Op1).getValueType()), 5171 getValue(I.getArgOperand(1)), 5172 getValue(I.getArgOperand(2)), 5173 Code); 5174 setValue(&I, Res); 5175 return nullptr; 5176 } 5177 case Intrinsic::powi: 5178 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5179 getValue(I.getArgOperand(1)), DAG)); 5180 return nullptr; 5181 case Intrinsic::log: 5182 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5183 return nullptr; 5184 case Intrinsic::log2: 5185 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5186 return nullptr; 5187 case Intrinsic::log10: 5188 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5189 return nullptr; 5190 case Intrinsic::exp: 5191 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5192 return nullptr; 5193 case Intrinsic::exp2: 5194 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5195 return nullptr; 5196 case Intrinsic::pow: 5197 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5198 getValue(I.getArgOperand(1)), DAG, TLI)); 5199 return nullptr; 5200 case Intrinsic::sqrt: 5201 case Intrinsic::fabs: 5202 case Intrinsic::sin: 5203 case Intrinsic::cos: 5204 case Intrinsic::floor: 5205 case Intrinsic::ceil: 5206 case Intrinsic::trunc: 5207 case Intrinsic::rint: 5208 case Intrinsic::nearbyint: 5209 case Intrinsic::round: 5210 case Intrinsic::canonicalize: { 5211 unsigned Opcode; 5212 switch (Intrinsic) { 5213 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5214 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5215 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5216 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5217 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5218 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5219 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5220 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5221 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5222 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5223 case Intrinsic::round: Opcode = ISD::FROUND; break; 5224 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5225 } 5226 5227 setValue(&I, DAG.getNode(Opcode, sdl, 5228 getValue(I.getArgOperand(0)).getValueType(), 5229 getValue(I.getArgOperand(0)))); 5230 return nullptr; 5231 } 5232 case Intrinsic::minnum: { 5233 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5234 unsigned Opc = 5235 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT) 5236 ? ISD::FMINNAN 5237 : ISD::FMINNUM; 5238 setValue(&I, DAG.getNode(Opc, sdl, VT, 5239 getValue(I.getArgOperand(0)), 5240 getValue(I.getArgOperand(1)))); 5241 return nullptr; 5242 } 5243 case Intrinsic::maxnum: { 5244 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5245 unsigned Opc = 5246 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT) 5247 ? ISD::FMAXNAN 5248 : ISD::FMAXNUM; 5249 setValue(&I, DAG.getNode(Opc, sdl, VT, 5250 getValue(I.getArgOperand(0)), 5251 getValue(I.getArgOperand(1)))); 5252 return nullptr; 5253 } 5254 case Intrinsic::copysign: 5255 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5256 getValue(I.getArgOperand(0)).getValueType(), 5257 getValue(I.getArgOperand(0)), 5258 getValue(I.getArgOperand(1)))); 5259 return nullptr; 5260 case Intrinsic::fma: 5261 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5262 getValue(I.getArgOperand(0)).getValueType(), 5263 getValue(I.getArgOperand(0)), 5264 getValue(I.getArgOperand(1)), 5265 getValue(I.getArgOperand(2)))); 5266 return nullptr; 5267 case Intrinsic::fmuladd: { 5268 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5269 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5270 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5271 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5272 getValue(I.getArgOperand(0)).getValueType(), 5273 getValue(I.getArgOperand(0)), 5274 getValue(I.getArgOperand(1)), 5275 getValue(I.getArgOperand(2)))); 5276 } else { 5277 // TODO: Intrinsic calls should have fast-math-flags. 5278 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5279 getValue(I.getArgOperand(0)).getValueType(), 5280 getValue(I.getArgOperand(0)), 5281 getValue(I.getArgOperand(1))); 5282 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5283 getValue(I.getArgOperand(0)).getValueType(), 5284 Mul, 5285 getValue(I.getArgOperand(2))); 5286 setValue(&I, Add); 5287 } 5288 return nullptr; 5289 } 5290 case Intrinsic::convert_to_fp16: 5291 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5292 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5293 getValue(I.getArgOperand(0)), 5294 DAG.getTargetConstant(0, sdl, 5295 MVT::i32)))); 5296 return nullptr; 5297 case Intrinsic::convert_from_fp16: 5298 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5299 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5300 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5301 getValue(I.getArgOperand(0))))); 5302 return nullptr; 5303 case Intrinsic::pcmarker: { 5304 SDValue Tmp = getValue(I.getArgOperand(0)); 5305 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5306 return nullptr; 5307 } 5308 case Intrinsic::readcyclecounter: { 5309 SDValue Op = getRoot(); 5310 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5311 DAG.getVTList(MVT::i64, MVT::Other), Op); 5312 setValue(&I, Res); 5313 DAG.setRoot(Res.getValue(1)); 5314 return nullptr; 5315 } 5316 case Intrinsic::bitreverse: 5317 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5318 getValue(I.getArgOperand(0)).getValueType(), 5319 getValue(I.getArgOperand(0)))); 5320 return nullptr; 5321 case Intrinsic::bswap: 5322 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5323 getValue(I.getArgOperand(0)).getValueType(), 5324 getValue(I.getArgOperand(0)))); 5325 return nullptr; 5326 case Intrinsic::cttz: { 5327 SDValue Arg = getValue(I.getArgOperand(0)); 5328 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5329 EVT Ty = Arg.getValueType(); 5330 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5331 sdl, Ty, Arg)); 5332 return nullptr; 5333 } 5334 case Intrinsic::ctlz: { 5335 SDValue Arg = getValue(I.getArgOperand(0)); 5336 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5337 EVT Ty = Arg.getValueType(); 5338 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5339 sdl, Ty, Arg)); 5340 return nullptr; 5341 } 5342 case Intrinsic::ctpop: { 5343 SDValue Arg = getValue(I.getArgOperand(0)); 5344 EVT Ty = Arg.getValueType(); 5345 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5346 return nullptr; 5347 } 5348 case Intrinsic::stacksave: { 5349 SDValue Op = getRoot(); 5350 Res = DAG.getNode( 5351 ISD::STACKSAVE, sdl, 5352 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5353 setValue(&I, Res); 5354 DAG.setRoot(Res.getValue(1)); 5355 return nullptr; 5356 } 5357 case Intrinsic::stackrestore: { 5358 Res = getValue(I.getArgOperand(0)); 5359 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5360 return nullptr; 5361 } 5362 case Intrinsic::get_dynamic_area_offset: { 5363 SDValue Op = getRoot(); 5364 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5365 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5366 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5367 // target. 5368 if (PtrTy != ResTy) 5369 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5370 " intrinsic!"); 5371 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5372 Op); 5373 DAG.setRoot(Op); 5374 setValue(&I, Res); 5375 return nullptr; 5376 } 5377 case Intrinsic::stackguard: { 5378 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5379 MachineFunction &MF = DAG.getMachineFunction(); 5380 const Module &M = *MF.getFunction()->getParent(); 5381 SDValue Chain = getRoot(); 5382 if (TLI.useLoadStackGuardNode()) { 5383 Res = getLoadStackGuard(DAG, sdl, Chain); 5384 } else { 5385 const Value *Global = TLI.getSDagStackGuard(M); 5386 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5387 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5388 MachinePointerInfo(Global, 0), Align, 5389 MachineMemOperand::MOVolatile); 5390 } 5391 DAG.setRoot(Chain); 5392 setValue(&I, Res); 5393 return nullptr; 5394 } 5395 case Intrinsic::stackprotector: { 5396 // Emit code into the DAG to store the stack guard onto the stack. 5397 MachineFunction &MF = DAG.getMachineFunction(); 5398 MachineFrameInfo &MFI = MF.getFrameInfo(); 5399 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5400 SDValue Src, Chain = getRoot(); 5401 5402 if (TLI.useLoadStackGuardNode()) 5403 Src = getLoadStackGuard(DAG, sdl, Chain); 5404 else 5405 Src = getValue(I.getArgOperand(0)); // The guard's value. 5406 5407 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5408 5409 int FI = FuncInfo.StaticAllocaMap[Slot]; 5410 MFI.setStackProtectorIndex(FI); 5411 5412 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5413 5414 // Store the stack protector onto the stack. 5415 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5416 DAG.getMachineFunction(), FI), 5417 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5418 setValue(&I, Res); 5419 DAG.setRoot(Res); 5420 return nullptr; 5421 } 5422 case Intrinsic::objectsize: { 5423 // If we don't know by now, we're never going to know. 5424 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5425 5426 assert(CI && "Non-constant type in __builtin_object_size?"); 5427 5428 SDValue Arg = getValue(I.getCalledValue()); 5429 EVT Ty = Arg.getValueType(); 5430 5431 if (CI->isZero()) 5432 Res = DAG.getConstant(-1ULL, sdl, Ty); 5433 else 5434 Res = DAG.getConstant(0, sdl, Ty); 5435 5436 setValue(&I, Res); 5437 return nullptr; 5438 } 5439 case Intrinsic::annotation: 5440 case Intrinsic::ptr_annotation: 5441 // Drop the intrinsic, but forward the value 5442 setValue(&I, getValue(I.getOperand(0))); 5443 return nullptr; 5444 case Intrinsic::assume: 5445 case Intrinsic::var_annotation: 5446 // Discard annotate attributes and assumptions 5447 return nullptr; 5448 5449 case Intrinsic::init_trampoline: { 5450 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5451 5452 SDValue Ops[6]; 5453 Ops[0] = getRoot(); 5454 Ops[1] = getValue(I.getArgOperand(0)); 5455 Ops[2] = getValue(I.getArgOperand(1)); 5456 Ops[3] = getValue(I.getArgOperand(2)); 5457 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5458 Ops[5] = DAG.getSrcValue(F); 5459 5460 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5461 5462 DAG.setRoot(Res); 5463 return nullptr; 5464 } 5465 case Intrinsic::adjust_trampoline: { 5466 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5467 TLI.getPointerTy(DAG.getDataLayout()), 5468 getValue(I.getArgOperand(0)))); 5469 return nullptr; 5470 } 5471 case Intrinsic::gcroot: { 5472 MachineFunction &MF = DAG.getMachineFunction(); 5473 const Function *F = MF.getFunction(); 5474 (void)F; 5475 assert(F->hasGC() && 5476 "only valid in functions with gc specified, enforced by Verifier"); 5477 assert(GFI && "implied by previous"); 5478 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5479 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5480 5481 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5482 GFI->addStackRoot(FI->getIndex(), TypeMap); 5483 return nullptr; 5484 } 5485 case Intrinsic::gcread: 5486 case Intrinsic::gcwrite: 5487 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 5488 case Intrinsic::flt_rounds: 5489 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 5490 return nullptr; 5491 5492 case Intrinsic::expect: { 5493 // Just replace __builtin_expect(exp, c) with EXP. 5494 setValue(&I, getValue(I.getArgOperand(0))); 5495 return nullptr; 5496 } 5497 5498 case Intrinsic::debugtrap: 5499 case Intrinsic::trap: { 5500 StringRef TrapFuncName = 5501 I.getAttributes() 5502 .getAttribute(AttributeSet::FunctionIndex, "trap-func-name") 5503 .getValueAsString(); 5504 if (TrapFuncName.empty()) { 5505 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 5506 ISD::TRAP : ISD::DEBUGTRAP; 5507 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 5508 return nullptr; 5509 } 5510 TargetLowering::ArgListTy Args; 5511 5512 TargetLowering::CallLoweringInfo CLI(DAG); 5513 CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee( 5514 CallingConv::C, I.getType(), 5515 DAG.getExternalSymbol(TrapFuncName.data(), 5516 TLI.getPointerTy(DAG.getDataLayout())), 5517 std::move(Args)); 5518 5519 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5520 DAG.setRoot(Result.second); 5521 return nullptr; 5522 } 5523 5524 case Intrinsic::uadd_with_overflow: 5525 case Intrinsic::sadd_with_overflow: 5526 case Intrinsic::usub_with_overflow: 5527 case Intrinsic::ssub_with_overflow: 5528 case Intrinsic::umul_with_overflow: 5529 case Intrinsic::smul_with_overflow: { 5530 ISD::NodeType Op; 5531 switch (Intrinsic) { 5532 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5533 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 5534 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 5535 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 5536 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 5537 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 5538 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 5539 } 5540 SDValue Op1 = getValue(I.getArgOperand(0)); 5541 SDValue Op2 = getValue(I.getArgOperand(1)); 5542 5543 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 5544 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 5545 return nullptr; 5546 } 5547 case Intrinsic::prefetch: { 5548 SDValue Ops[5]; 5549 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 5550 Ops[0] = getRoot(); 5551 Ops[1] = getValue(I.getArgOperand(0)); 5552 Ops[2] = getValue(I.getArgOperand(1)); 5553 Ops[3] = getValue(I.getArgOperand(2)); 5554 Ops[4] = getValue(I.getArgOperand(3)); 5555 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 5556 DAG.getVTList(MVT::Other), Ops, 5557 EVT::getIntegerVT(*Context, 8), 5558 MachinePointerInfo(I.getArgOperand(0)), 5559 0, /* align */ 5560 false, /* volatile */ 5561 rw==0, /* read */ 5562 rw==1)); /* write */ 5563 return nullptr; 5564 } 5565 case Intrinsic::lifetime_start: 5566 case Intrinsic::lifetime_end: { 5567 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 5568 // Stack coloring is not enabled in O0, discard region information. 5569 if (TM.getOptLevel() == CodeGenOpt::None) 5570 return nullptr; 5571 5572 SmallVector<Value *, 4> Allocas; 5573 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 5574 5575 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 5576 E = Allocas.end(); Object != E; ++Object) { 5577 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 5578 5579 // Could not find an Alloca. 5580 if (!LifetimeObject) 5581 continue; 5582 5583 // First check that the Alloca is static, otherwise it won't have a 5584 // valid frame index. 5585 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 5586 if (SI == FuncInfo.StaticAllocaMap.end()) 5587 return nullptr; 5588 5589 int FI = SI->second; 5590 5591 SDValue Ops[2]; 5592 Ops[0] = getRoot(); 5593 Ops[1] = 5594 DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true); 5595 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 5596 5597 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 5598 DAG.setRoot(Res); 5599 } 5600 return nullptr; 5601 } 5602 case Intrinsic::invariant_start: 5603 // Discard region information. 5604 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 5605 return nullptr; 5606 case Intrinsic::invariant_end: 5607 // Discard region information. 5608 return nullptr; 5609 case Intrinsic::clear_cache: 5610 return TLI.getClearCacheBuiltinName(); 5611 case Intrinsic::donothing: 5612 // ignore 5613 return nullptr; 5614 case Intrinsic::experimental_stackmap: { 5615 visitStackmap(I); 5616 return nullptr; 5617 } 5618 case Intrinsic::experimental_patchpoint_void: 5619 case Intrinsic::experimental_patchpoint_i64: { 5620 visitPatchpoint(&I); 5621 return nullptr; 5622 } 5623 case Intrinsic::experimental_gc_statepoint: { 5624 LowerStatepoint(ImmutableStatepoint(&I)); 5625 return nullptr; 5626 } 5627 case Intrinsic::experimental_gc_result: { 5628 visitGCResult(cast<GCResultInst>(I)); 5629 return nullptr; 5630 } 5631 case Intrinsic::experimental_gc_relocate: { 5632 visitGCRelocate(cast<GCRelocateInst>(I)); 5633 return nullptr; 5634 } 5635 case Intrinsic::instrprof_increment: 5636 llvm_unreachable("instrprof failed to lower an increment"); 5637 case Intrinsic::instrprof_value_profile: 5638 llvm_unreachable("instrprof failed to lower a value profiling call"); 5639 case Intrinsic::localescape: { 5640 MachineFunction &MF = DAG.getMachineFunction(); 5641 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5642 5643 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 5644 // is the same on all targets. 5645 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 5646 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 5647 if (isa<ConstantPointerNull>(Arg)) 5648 continue; // Skip null pointers. They represent a hole in index space. 5649 AllocaInst *Slot = cast<AllocaInst>(Arg); 5650 assert(FuncInfo.StaticAllocaMap.count(Slot) && 5651 "can only escape static allocas"); 5652 int FI = FuncInfo.StaticAllocaMap[Slot]; 5653 MCSymbol *FrameAllocSym = 5654 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5655 GlobalValue::getRealLinkageName(MF.getName()), Idx); 5656 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 5657 TII->get(TargetOpcode::LOCAL_ESCAPE)) 5658 .addSym(FrameAllocSym) 5659 .addFrameIndex(FI); 5660 } 5661 5662 return nullptr; 5663 } 5664 5665 case Intrinsic::localrecover: { 5666 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 5667 MachineFunction &MF = DAG.getMachineFunction(); 5668 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 5669 5670 // Get the symbol that defines the frame offset. 5671 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 5672 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 5673 unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX)); 5674 MCSymbol *FrameAllocSym = 5675 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5676 GlobalValue::getRealLinkageName(Fn->getName()), IdxVal); 5677 5678 // Create a MCSymbol for the label to avoid any target lowering 5679 // that would make this PC relative. 5680 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 5681 SDValue OffsetVal = 5682 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 5683 5684 // Add the offset to the FP. 5685 Value *FP = I.getArgOperand(1); 5686 SDValue FPVal = getValue(FP); 5687 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 5688 setValue(&I, Add); 5689 5690 return nullptr; 5691 } 5692 5693 case Intrinsic::eh_exceptionpointer: 5694 case Intrinsic::eh_exceptioncode: { 5695 // Get the exception pointer vreg, copy from it, and resize it to fit. 5696 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 5697 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 5698 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 5699 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 5700 SDValue N = 5701 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 5702 if (Intrinsic == Intrinsic::eh_exceptioncode) 5703 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 5704 setValue(&I, N); 5705 return nullptr; 5706 } 5707 5708 case Intrinsic::experimental_deoptimize: 5709 LowerDeoptimizeCall(&I); 5710 return nullptr; 5711 } 5712 } 5713 5714 std::pair<SDValue, SDValue> 5715 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 5716 const BasicBlock *EHPadBB) { 5717 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5718 MCSymbol *BeginLabel = nullptr; 5719 5720 if (EHPadBB) { 5721 // Insert a label before the invoke call to mark the try range. This can be 5722 // used to detect deletion of the invoke via the MachineModuleInfo. 5723 BeginLabel = MMI.getContext().createTempSymbol(); 5724 5725 // For SjLj, keep track of which landing pads go with which invokes 5726 // so as to maintain the ordering of pads in the LSDA. 5727 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 5728 if (CallSiteIndex) { 5729 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 5730 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 5731 5732 // Now that the call site is handled, stop tracking it. 5733 MMI.setCurrentCallSite(0); 5734 } 5735 5736 // Both PendingLoads and PendingExports must be flushed here; 5737 // this call might not return. 5738 (void)getRoot(); 5739 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 5740 5741 CLI.setChain(getRoot()); 5742 } 5743 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5744 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5745 5746 assert((CLI.IsTailCall || Result.second.getNode()) && 5747 "Non-null chain expected with non-tail call!"); 5748 assert((Result.second.getNode() || !Result.first.getNode()) && 5749 "Null value expected with tail call!"); 5750 5751 if (!Result.second.getNode()) { 5752 // As a special case, a null chain means that a tail call has been emitted 5753 // and the DAG root is already updated. 5754 HasTailCall = true; 5755 5756 // Since there's no actual continuation from this block, nothing can be 5757 // relying on us setting vregs for them. 5758 PendingExports.clear(); 5759 } else { 5760 DAG.setRoot(Result.second); 5761 } 5762 5763 if (EHPadBB) { 5764 // Insert a label at the end of the invoke call to mark the try range. This 5765 // can be used to detect deletion of the invoke via the MachineModuleInfo. 5766 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 5767 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 5768 5769 // Inform MachineModuleInfo of range. 5770 if (MMI.hasEHFunclets()) { 5771 assert(CLI.CS); 5772 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 5773 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS->getInstruction()), 5774 BeginLabel, EndLabel); 5775 } else { 5776 MMI.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 5777 } 5778 } 5779 5780 return Result; 5781 } 5782 5783 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 5784 bool isTailCall, 5785 const BasicBlock *EHPadBB) { 5786 auto &DL = DAG.getDataLayout(); 5787 FunctionType *FTy = CS.getFunctionType(); 5788 Type *RetTy = CS.getType(); 5789 5790 TargetLowering::ArgListTy Args; 5791 TargetLowering::ArgListEntry Entry; 5792 Args.reserve(CS.arg_size()); 5793 5794 const Value *SwiftErrorVal = nullptr; 5795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5796 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 5797 i != e; ++i) { 5798 const Value *V = *i; 5799 5800 // Skip empty types 5801 if (V->getType()->isEmptyTy()) 5802 continue; 5803 5804 SDValue ArgNode = getValue(V); 5805 Entry.Node = ArgNode; Entry.Ty = V->getType(); 5806 5807 // Skip the first return-type Attribute to get to params. 5808 Entry.setAttributes(&CS, i - CS.arg_begin() + 1); 5809 5810 // Use swifterror virtual register as input to the call. 5811 if (Entry.isSwiftError && TLI.supportSwiftError()) { 5812 SwiftErrorVal = V; 5813 // We find the virtual register for the actual swifterror argument. 5814 // Instead of using the Value, we use the virtual register instead. 5815 Entry.Node = DAG.getRegister( 5816 FuncInfo.findSwiftErrorVReg(FuncInfo.MBB, V), 5817 EVT(TLI.getPointerTy(DL))); 5818 } 5819 5820 Args.push_back(Entry); 5821 5822 // If we have an explicit sret argument that is an Instruction, (i.e., it 5823 // might point to function-local memory), we can't meaningfully tail-call. 5824 if (Entry.isSRet && isa<Instruction>(V)) 5825 isTailCall = false; 5826 } 5827 5828 // Check if target-independent constraints permit a tail call here. 5829 // Target-dependent constraints are checked within TLI->LowerCallTo. 5830 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 5831 isTailCall = false; 5832 5833 TargetLowering::CallLoweringInfo CLI(DAG); 5834 CLI.setDebugLoc(getCurSDLoc()) 5835 .setChain(getRoot()) 5836 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 5837 .setTailCall(isTailCall) 5838 .setConvergent(CS.isConvergent()); 5839 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 5840 5841 if (Result.first.getNode()) { 5842 const Instruction *Inst = CS.getInstruction(); 5843 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 5844 setValue(Inst, Result.first); 5845 } 5846 5847 // The last element of CLI.InVals has the SDValue for swifterror return. 5848 // Here we copy it to a virtual register and update SwiftErrorMap for 5849 // book-keeping. 5850 if (SwiftErrorVal && TLI.supportSwiftError()) { 5851 // Get the last element of InVals. 5852 SDValue Src = CLI.InVals.back(); 5853 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL)); 5854 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC); 5855 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 5856 // We update the virtual register for the actual swifterror argument. 5857 FuncInfo.setSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 5858 DAG.setRoot(CopyNode); 5859 } 5860 } 5861 5862 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 5863 /// value is equal or not-equal to zero. 5864 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) { 5865 for (const User *U : V->users()) { 5866 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U)) 5867 if (IC->isEquality()) 5868 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 5869 if (C->isNullValue()) 5870 continue; 5871 // Unknown instruction. 5872 return false; 5873 } 5874 return true; 5875 } 5876 5877 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 5878 Type *LoadTy, 5879 SelectionDAGBuilder &Builder) { 5880 5881 // Check to see if this load can be trivially constant folded, e.g. if the 5882 // input is from a string literal. 5883 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 5884 // Cast pointer to the type we really want to load. 5885 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 5886 PointerType::getUnqual(LoadTy)); 5887 5888 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 5889 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 5890 return Builder.getValue(LoadCst); 5891 } 5892 5893 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 5894 // still constant memory, the input chain can be the entry node. 5895 SDValue Root; 5896 bool ConstantMemory = false; 5897 5898 // Do not serialize (non-volatile) loads of constant memory with anything. 5899 if (Builder.AA->pointsToConstantMemory(PtrVal)) { 5900 Root = Builder.DAG.getEntryNode(); 5901 ConstantMemory = true; 5902 } else { 5903 // Do not serialize non-volatile loads against each other. 5904 Root = Builder.DAG.getRoot(); 5905 } 5906 5907 SDValue Ptr = Builder.getValue(PtrVal); 5908 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 5909 Ptr, MachinePointerInfo(PtrVal), 5910 /* Alignment = */ 1); 5911 5912 if (!ConstantMemory) 5913 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 5914 return LoadVal; 5915 } 5916 5917 /// processIntegerCallValue - Record the value for an instruction that 5918 /// produces an integer result, converting the type where necessary. 5919 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 5920 SDValue Value, 5921 bool IsSigned) { 5922 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 5923 I.getType(), true); 5924 if (IsSigned) 5925 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 5926 else 5927 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 5928 setValue(&I, Value); 5929 } 5930 5931 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form. 5932 /// If so, return true and lower it, otherwise return false and it will be 5933 /// lowered like a normal call. 5934 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 5935 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t) 5936 if (I.getNumArgOperands() != 3) 5937 return false; 5938 5939 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 5940 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() || 5941 !I.getArgOperand(2)->getType()->isIntegerTy() || 5942 !I.getType()->isIntegerTy()) 5943 return false; 5944 5945 const Value *Size = I.getArgOperand(2); 5946 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 5947 if (CSize && CSize->getZExtValue() == 0) { 5948 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 5949 I.getType(), true); 5950 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 5951 return true; 5952 } 5953 5954 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 5955 std::pair<SDValue, SDValue> Res = 5956 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(), 5957 getValue(LHS), getValue(RHS), getValue(Size), 5958 MachinePointerInfo(LHS), 5959 MachinePointerInfo(RHS)); 5960 if (Res.first.getNode()) { 5961 processIntegerCallValue(I, Res.first, true); 5962 PendingLoads.push_back(Res.second); 5963 return true; 5964 } 5965 5966 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 5967 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 5968 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) { 5969 bool ActuallyDoIt = true; 5970 MVT LoadVT; 5971 Type *LoadTy; 5972 switch (CSize->getZExtValue()) { 5973 default: 5974 LoadVT = MVT::Other; 5975 LoadTy = nullptr; 5976 ActuallyDoIt = false; 5977 break; 5978 case 2: 5979 LoadVT = MVT::i16; 5980 LoadTy = Type::getInt16Ty(CSize->getContext()); 5981 break; 5982 case 4: 5983 LoadVT = MVT::i32; 5984 LoadTy = Type::getInt32Ty(CSize->getContext()); 5985 break; 5986 case 8: 5987 LoadVT = MVT::i64; 5988 LoadTy = Type::getInt64Ty(CSize->getContext()); 5989 break; 5990 /* 5991 case 16: 5992 LoadVT = MVT::v4i32; 5993 LoadTy = Type::getInt32Ty(CSize->getContext()); 5994 LoadTy = VectorType::get(LoadTy, 4); 5995 break; 5996 */ 5997 } 5998 5999 // This turns into unaligned loads. We only do this if the target natively 6000 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6001 // we'll only produce a small number of byte loads. 6002 6003 // Require that we can find a legal MVT, and only do this if the target 6004 // supports unaligned loads of that type. Expanding into byte loads would 6005 // bloat the code. 6006 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6007 if (ActuallyDoIt && CSize->getZExtValue() > 4) { 6008 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6009 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6010 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6011 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6012 // TODO: Check alignment of src and dest ptrs. 6013 if (!TLI.isTypeLegal(LoadVT) || 6014 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) || 6015 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS)) 6016 ActuallyDoIt = false; 6017 } 6018 6019 if (ActuallyDoIt) { 6020 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this); 6021 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this); 6022 6023 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal, 6024 ISD::SETNE); 6025 processIntegerCallValue(I, Res, false); 6026 return true; 6027 } 6028 } 6029 6030 6031 return false; 6032 } 6033 6034 /// visitMemChrCall -- See if we can lower a memchr call into an optimized 6035 /// form. If so, return true and lower it, otherwise return false and it 6036 /// will be lowered like a normal call. 6037 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6038 // Verify that the prototype makes sense. void *memchr(void *, int, size_t) 6039 if (I.getNumArgOperands() != 3) 6040 return false; 6041 6042 const Value *Src = I.getArgOperand(0); 6043 const Value *Char = I.getArgOperand(1); 6044 const Value *Length = I.getArgOperand(2); 6045 if (!Src->getType()->isPointerTy() || 6046 !Char->getType()->isIntegerTy() || 6047 !Length->getType()->isIntegerTy() || 6048 !I.getType()->isPointerTy()) 6049 return false; 6050 6051 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6052 std::pair<SDValue, SDValue> Res = 6053 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6054 getValue(Src), getValue(Char), getValue(Length), 6055 MachinePointerInfo(Src)); 6056 if (Res.first.getNode()) { 6057 setValue(&I, Res.first); 6058 PendingLoads.push_back(Res.second); 6059 return true; 6060 } 6061 6062 return false; 6063 } 6064 6065 /// 6066 /// visitMemPCpyCall -- lower a mempcpy call as a memcpy followed by code to 6067 /// to adjust the dst pointer by the size of the copied memory. 6068 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6069 6070 // Verify argument count: void *mempcpy(void *, const void *, size_t) 6071 if (I.getNumArgOperands() != 3) 6072 return false; 6073 6074 SDValue Dst = getValue(I.getArgOperand(0)); 6075 SDValue Src = getValue(I.getArgOperand(1)); 6076 SDValue Size = getValue(I.getArgOperand(2)); 6077 6078 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6079 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6080 unsigned Align = std::min(DstAlign, SrcAlign); 6081 if (Align == 0) // Alignment of one or both could not be inferred. 6082 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6083 6084 bool isVol = false; 6085 SDLoc sdl = getCurSDLoc(); 6086 6087 // In the mempcpy context we need to pass in a false value for isTailCall 6088 // because the return pointer needs to be adjusted by the size of 6089 // the copied memory. 6090 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6091 false, /*isTailCall=*/false, 6092 MachinePointerInfo(I.getArgOperand(0)), 6093 MachinePointerInfo(I.getArgOperand(1))); 6094 assert(MC.getNode() != nullptr && 6095 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6096 DAG.setRoot(MC); 6097 6098 // Check if Size needs to be truncated or extended. 6099 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6100 6101 // Adjust return pointer to point just past the last dst byte. 6102 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6103 Dst, Size); 6104 setValue(&I, DstPlusSize); 6105 return true; 6106 } 6107 6108 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an 6109 /// optimized form. If so, return true and lower it, otherwise return false 6110 /// and it will be lowered like a normal call. 6111 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6112 // Verify that the prototype makes sense. char *strcpy(char *, char *) 6113 if (I.getNumArgOperands() != 2) 6114 return false; 6115 6116 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6117 if (!Arg0->getType()->isPointerTy() || 6118 !Arg1->getType()->isPointerTy() || 6119 !I.getType()->isPointerTy()) 6120 return false; 6121 6122 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6123 std::pair<SDValue, SDValue> Res = 6124 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6125 getValue(Arg0), getValue(Arg1), 6126 MachinePointerInfo(Arg0), 6127 MachinePointerInfo(Arg1), isStpcpy); 6128 if (Res.first.getNode()) { 6129 setValue(&I, Res.first); 6130 DAG.setRoot(Res.second); 6131 return true; 6132 } 6133 6134 return false; 6135 } 6136 6137 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form. 6138 /// If so, return true and lower it, otherwise return false and it will be 6139 /// lowered like a normal call. 6140 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6141 // Verify that the prototype makes sense. int strcmp(void*,void*) 6142 if (I.getNumArgOperands() != 2) 6143 return false; 6144 6145 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6146 if (!Arg0->getType()->isPointerTy() || 6147 !Arg1->getType()->isPointerTy() || 6148 !I.getType()->isIntegerTy()) 6149 return false; 6150 6151 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6152 std::pair<SDValue, SDValue> Res = 6153 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6154 getValue(Arg0), getValue(Arg1), 6155 MachinePointerInfo(Arg0), 6156 MachinePointerInfo(Arg1)); 6157 if (Res.first.getNode()) { 6158 processIntegerCallValue(I, Res.first, true); 6159 PendingLoads.push_back(Res.second); 6160 return true; 6161 } 6162 6163 return false; 6164 } 6165 6166 /// visitStrLenCall -- See if we can lower a strlen call into an optimized 6167 /// form. If so, return true and lower it, otherwise return false and it 6168 /// will be lowered like a normal call. 6169 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6170 // Verify that the prototype makes sense. size_t strlen(char *) 6171 if (I.getNumArgOperands() != 1) 6172 return false; 6173 6174 const Value *Arg0 = I.getArgOperand(0); 6175 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy()) 6176 return false; 6177 6178 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6179 std::pair<SDValue, SDValue> Res = 6180 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6181 getValue(Arg0), MachinePointerInfo(Arg0)); 6182 if (Res.first.getNode()) { 6183 processIntegerCallValue(I, Res.first, false); 6184 PendingLoads.push_back(Res.second); 6185 return true; 6186 } 6187 6188 return false; 6189 } 6190 6191 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized 6192 /// form. If so, return true and lower it, otherwise return false and it 6193 /// will be lowered like a normal call. 6194 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6195 // Verify that the prototype makes sense. size_t strnlen(char *, size_t) 6196 if (I.getNumArgOperands() != 2) 6197 return false; 6198 6199 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6200 if (!Arg0->getType()->isPointerTy() || 6201 !Arg1->getType()->isIntegerTy() || 6202 !I.getType()->isIntegerTy()) 6203 return false; 6204 6205 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6206 std::pair<SDValue, SDValue> Res = 6207 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6208 getValue(Arg0), getValue(Arg1), 6209 MachinePointerInfo(Arg0)); 6210 if (Res.first.getNode()) { 6211 processIntegerCallValue(I, Res.first, false); 6212 PendingLoads.push_back(Res.second); 6213 return true; 6214 } 6215 6216 return false; 6217 } 6218 6219 /// visitUnaryFloatCall - If a call instruction is a unary floating-point 6220 /// operation (as expected), translate it to an SDNode with the specified opcode 6221 /// and return true. 6222 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6223 unsigned Opcode) { 6224 // Sanity check that it really is a unary floating-point call. 6225 if (I.getNumArgOperands() != 1 || 6226 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 6227 I.getType() != I.getArgOperand(0)->getType() || 6228 !I.onlyReadsMemory()) 6229 return false; 6230 6231 SDValue Tmp = getValue(I.getArgOperand(0)); 6232 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6233 return true; 6234 } 6235 6236 /// visitBinaryFloatCall - If a call instruction is a binary floating-point 6237 /// operation (as expected), translate it to an SDNode with the specified opcode 6238 /// and return true. 6239 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6240 unsigned Opcode) { 6241 // Sanity check that it really is a binary floating-point call. 6242 if (I.getNumArgOperands() != 2 || 6243 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 6244 I.getType() != I.getArgOperand(0)->getType() || 6245 I.getType() != I.getArgOperand(1)->getType() || 6246 !I.onlyReadsMemory()) 6247 return false; 6248 6249 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6250 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6251 EVT VT = Tmp0.getValueType(); 6252 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6253 return true; 6254 } 6255 6256 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6257 // Handle inline assembly differently. 6258 if (isa<InlineAsm>(I.getCalledValue())) { 6259 visitInlineAsm(&I); 6260 return; 6261 } 6262 6263 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6264 ComputeUsesVAFloatArgument(I, &MMI); 6265 6266 const char *RenameFn = nullptr; 6267 if (Function *F = I.getCalledFunction()) { 6268 if (F->isDeclaration()) { 6269 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) { 6270 if (unsigned IID = II->getIntrinsicID(F)) { 6271 RenameFn = visitIntrinsicCall(I, IID); 6272 if (!RenameFn) 6273 return; 6274 } 6275 } 6276 if (Intrinsic::ID IID = F->getIntrinsicID()) { 6277 RenameFn = visitIntrinsicCall(I, IID); 6278 if (!RenameFn) 6279 return; 6280 } 6281 } 6282 6283 // Check for well-known libc/libm calls. If the function is internal, it 6284 // can't be a library call. Don't do the check if marked as nobuiltin for 6285 // some reason. 6286 LibFunc::Func Func; 6287 if (!I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName() && 6288 LibInfo->getLibFunc(F->getName(), Func) && 6289 LibInfo->hasOptimizedCodeGen(Func)) { 6290 switch (Func) { 6291 default: break; 6292 case LibFunc::copysign: 6293 case LibFunc::copysignf: 6294 case LibFunc::copysignl: 6295 if (I.getNumArgOperands() == 2 && // Basic sanity checks. 6296 I.getArgOperand(0)->getType()->isFloatingPointTy() && 6297 I.getType() == I.getArgOperand(0)->getType() && 6298 I.getType() == I.getArgOperand(1)->getType() && 6299 I.onlyReadsMemory()) { 6300 SDValue LHS = getValue(I.getArgOperand(0)); 6301 SDValue RHS = getValue(I.getArgOperand(1)); 6302 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 6303 LHS.getValueType(), LHS, RHS)); 6304 return; 6305 } 6306 break; 6307 case LibFunc::fabs: 6308 case LibFunc::fabsf: 6309 case LibFunc::fabsl: 6310 if (visitUnaryFloatCall(I, ISD::FABS)) 6311 return; 6312 break; 6313 case LibFunc::fmin: 6314 case LibFunc::fminf: 6315 case LibFunc::fminl: 6316 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 6317 return; 6318 break; 6319 case LibFunc::fmax: 6320 case LibFunc::fmaxf: 6321 case LibFunc::fmaxl: 6322 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 6323 return; 6324 break; 6325 case LibFunc::sin: 6326 case LibFunc::sinf: 6327 case LibFunc::sinl: 6328 if (visitUnaryFloatCall(I, ISD::FSIN)) 6329 return; 6330 break; 6331 case LibFunc::cos: 6332 case LibFunc::cosf: 6333 case LibFunc::cosl: 6334 if (visitUnaryFloatCall(I, ISD::FCOS)) 6335 return; 6336 break; 6337 case LibFunc::sqrt: 6338 case LibFunc::sqrtf: 6339 case LibFunc::sqrtl: 6340 case LibFunc::sqrt_finite: 6341 case LibFunc::sqrtf_finite: 6342 case LibFunc::sqrtl_finite: 6343 if (visitUnaryFloatCall(I, ISD::FSQRT)) 6344 return; 6345 break; 6346 case LibFunc::floor: 6347 case LibFunc::floorf: 6348 case LibFunc::floorl: 6349 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 6350 return; 6351 break; 6352 case LibFunc::nearbyint: 6353 case LibFunc::nearbyintf: 6354 case LibFunc::nearbyintl: 6355 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 6356 return; 6357 break; 6358 case LibFunc::ceil: 6359 case LibFunc::ceilf: 6360 case LibFunc::ceill: 6361 if (visitUnaryFloatCall(I, ISD::FCEIL)) 6362 return; 6363 break; 6364 case LibFunc::rint: 6365 case LibFunc::rintf: 6366 case LibFunc::rintl: 6367 if (visitUnaryFloatCall(I, ISD::FRINT)) 6368 return; 6369 break; 6370 case LibFunc::round: 6371 case LibFunc::roundf: 6372 case LibFunc::roundl: 6373 if (visitUnaryFloatCall(I, ISD::FROUND)) 6374 return; 6375 break; 6376 case LibFunc::trunc: 6377 case LibFunc::truncf: 6378 case LibFunc::truncl: 6379 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 6380 return; 6381 break; 6382 case LibFunc::log2: 6383 case LibFunc::log2f: 6384 case LibFunc::log2l: 6385 if (visitUnaryFloatCall(I, ISD::FLOG2)) 6386 return; 6387 break; 6388 case LibFunc::exp2: 6389 case LibFunc::exp2f: 6390 case LibFunc::exp2l: 6391 if (visitUnaryFloatCall(I, ISD::FEXP2)) 6392 return; 6393 break; 6394 case LibFunc::memcmp: 6395 if (visitMemCmpCall(I)) 6396 return; 6397 break; 6398 case LibFunc::mempcpy: 6399 if (visitMemPCpyCall(I)) 6400 return; 6401 break; 6402 case LibFunc::memchr: 6403 if (visitMemChrCall(I)) 6404 return; 6405 break; 6406 case LibFunc::strcpy: 6407 if (visitStrCpyCall(I, false)) 6408 return; 6409 break; 6410 case LibFunc::stpcpy: 6411 if (visitStrCpyCall(I, true)) 6412 return; 6413 break; 6414 case LibFunc::strcmp: 6415 if (visitStrCmpCall(I)) 6416 return; 6417 break; 6418 case LibFunc::strlen: 6419 if (visitStrLenCall(I)) 6420 return; 6421 break; 6422 case LibFunc::strnlen: 6423 if (visitStrNLenCall(I)) 6424 return; 6425 break; 6426 } 6427 } 6428 } 6429 6430 SDValue Callee; 6431 if (!RenameFn) 6432 Callee = getValue(I.getCalledValue()); 6433 else 6434 Callee = DAG.getExternalSymbol( 6435 RenameFn, 6436 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6437 6438 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 6439 // have to do anything here to lower funclet bundles. 6440 assert(!I.hasOperandBundlesOtherThan( 6441 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 6442 "Cannot lower calls with arbitrary operand bundles!"); 6443 6444 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 6445 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 6446 else 6447 // Check if we can potentially perform a tail call. More detailed checking 6448 // is be done within LowerCallTo, after more information about the call is 6449 // known. 6450 LowerCallTo(&I, Callee, I.isTailCall()); 6451 } 6452 6453 namespace { 6454 6455 /// AsmOperandInfo - This contains information for each constraint that we are 6456 /// lowering. 6457 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 6458 public: 6459 /// CallOperand - If this is the result output operand or a clobber 6460 /// this is null, otherwise it is the incoming operand to the CallInst. 6461 /// This gets modified as the asm is processed. 6462 SDValue CallOperand; 6463 6464 /// AssignedRegs - If this is a register or register class operand, this 6465 /// contains the set of register corresponding to the operand. 6466 RegsForValue AssignedRegs; 6467 6468 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 6469 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) { 6470 } 6471 6472 /// Whether or not this operand accesses memory 6473 bool hasMemory(const TargetLowering &TLI) const { 6474 // Indirect operand accesses access memory. 6475 if (isIndirect) 6476 return true; 6477 6478 for (const auto &Code : Codes) 6479 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 6480 return true; 6481 6482 return false; 6483 } 6484 6485 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 6486 /// corresponds to. If there is no Value* for this operand, it returns 6487 /// MVT::Other. 6488 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 6489 const DataLayout &DL) const { 6490 if (!CallOperandVal) return MVT::Other; 6491 6492 if (isa<BasicBlock>(CallOperandVal)) 6493 return TLI.getPointerTy(DL); 6494 6495 llvm::Type *OpTy = CallOperandVal->getType(); 6496 6497 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 6498 // If this is an indirect operand, the operand is a pointer to the 6499 // accessed type. 6500 if (isIndirect) { 6501 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 6502 if (!PtrTy) 6503 report_fatal_error("Indirect operand for inline asm not a pointer!"); 6504 OpTy = PtrTy->getElementType(); 6505 } 6506 6507 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 6508 if (StructType *STy = dyn_cast<StructType>(OpTy)) 6509 if (STy->getNumElements() == 1) 6510 OpTy = STy->getElementType(0); 6511 6512 // If OpTy is not a single value, it may be a struct/union that we 6513 // can tile with integers. 6514 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 6515 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 6516 switch (BitSize) { 6517 default: break; 6518 case 1: 6519 case 8: 6520 case 16: 6521 case 32: 6522 case 64: 6523 case 128: 6524 OpTy = IntegerType::get(Context, BitSize); 6525 break; 6526 } 6527 } 6528 6529 return TLI.getValueType(DL, OpTy, true); 6530 } 6531 }; 6532 6533 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector; 6534 6535 } // end anonymous namespace 6536 6537 /// Make sure that the output operand \p OpInfo and its corresponding input 6538 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 6539 /// out). 6540 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 6541 SDISelAsmOperandInfo &MatchingOpInfo, 6542 SelectionDAG &DAG) { 6543 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 6544 return; 6545 6546 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 6547 const auto &TLI = DAG.getTargetLoweringInfo(); 6548 6549 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 6550 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 6551 OpInfo.ConstraintVT); 6552 std::pair<unsigned, const TargetRegisterClass *> InputRC = 6553 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 6554 MatchingOpInfo.ConstraintVT); 6555 if ((OpInfo.ConstraintVT.isInteger() != 6556 MatchingOpInfo.ConstraintVT.isInteger()) || 6557 (MatchRC.second != InputRC.second)) { 6558 // FIXME: error out in a more elegant fashion 6559 report_fatal_error("Unsupported asm: input constraint" 6560 " with a matching output constraint of" 6561 " incompatible type!"); 6562 } 6563 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 6564 } 6565 6566 /// Get a direct memory input to behave well as an indirect operand. 6567 /// This may introduce stores, hence the need for a \p Chain. 6568 /// \return The (possibly updated) chain. 6569 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 6570 SDISelAsmOperandInfo &OpInfo, 6571 SelectionDAG &DAG) { 6572 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6573 6574 // If we don't have an indirect input, put it in the constpool if we can, 6575 // otherwise spill it to a stack slot. 6576 // TODO: This isn't quite right. We need to handle these according to 6577 // the addressing mode that the constraint wants. Also, this may take 6578 // an additional register for the computation and we don't want that 6579 // either. 6580 6581 // If the operand is a float, integer, or vector constant, spill to a 6582 // constant pool entry to get its address. 6583 const Value *OpVal = OpInfo.CallOperandVal; 6584 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 6585 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 6586 OpInfo.CallOperand = DAG.getConstantPool( 6587 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 6588 return Chain; 6589 } 6590 6591 // Otherwise, create a stack slot and emit a store to it before the asm. 6592 Type *Ty = OpVal->getType(); 6593 auto &DL = DAG.getDataLayout(); 6594 uint64_t TySize = DL.getTypeAllocSize(Ty); 6595 unsigned Align = DL.getPrefTypeAlignment(Ty); 6596 MachineFunction &MF = DAG.getMachineFunction(); 6597 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 6598 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy(DL)); 6599 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 6600 MachinePointerInfo::getFixedStack(MF, SSFI)); 6601 OpInfo.CallOperand = StackSlot; 6602 6603 return Chain; 6604 } 6605 6606 /// GetRegistersForValue - Assign registers (virtual or physical) for the 6607 /// specified operand. We prefer to assign virtual registers, to allow the 6608 /// register allocator to handle the assignment process. However, if the asm 6609 /// uses features that we can't model on machineinstrs, we have SDISel do the 6610 /// allocation. This produces generally horrible, but correct, code. 6611 /// 6612 /// OpInfo describes the operand. 6613 /// 6614 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI, 6615 const SDLoc &DL, 6616 SDISelAsmOperandInfo &OpInfo) { 6617 LLVMContext &Context = *DAG.getContext(); 6618 6619 MachineFunction &MF = DAG.getMachineFunction(); 6620 SmallVector<unsigned, 4> Regs; 6621 6622 // If this is a constraint for a single physreg, or a constraint for a 6623 // register class, find it. 6624 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 6625 TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(), 6626 OpInfo.ConstraintCode, 6627 OpInfo.ConstraintVT); 6628 6629 unsigned NumRegs = 1; 6630 if (OpInfo.ConstraintVT != MVT::Other) { 6631 // If this is a FP input in an integer register (or visa versa) insert a bit 6632 // cast of the input value. More generally, handle any case where the input 6633 // value disagrees with the register class we plan to stick this in. 6634 if (OpInfo.Type == InlineAsm::isInput && 6635 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) { 6636 // Try to convert to the first EVT that the reg class contains. If the 6637 // types are identical size, use a bitcast to convert (e.g. two differing 6638 // vector types). 6639 MVT RegVT = *PhysReg.second->vt_begin(); 6640 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) { 6641 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 6642 RegVT, OpInfo.CallOperand); 6643 OpInfo.ConstraintVT = RegVT; 6644 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 6645 // If the input is a FP value and we want it in FP registers, do a 6646 // bitcast to the corresponding integer type. This turns an f64 value 6647 // into i64, which can be passed with two i32 values on a 32-bit 6648 // machine. 6649 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 6650 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 6651 RegVT, OpInfo.CallOperand); 6652 OpInfo.ConstraintVT = RegVT; 6653 } 6654 } 6655 6656 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 6657 } 6658 6659 MVT RegVT; 6660 EVT ValueVT = OpInfo.ConstraintVT; 6661 6662 // If this is a constraint for a specific physical register, like {r17}, 6663 // assign it now. 6664 if (unsigned AssignedReg = PhysReg.first) { 6665 const TargetRegisterClass *RC = PhysReg.second; 6666 if (OpInfo.ConstraintVT == MVT::Other) 6667 ValueVT = *RC->vt_begin(); 6668 6669 // Get the actual register value type. This is important, because the user 6670 // may have asked for (e.g.) the AX register in i32 type. We need to 6671 // remember that AX is actually i16 to get the right extension. 6672 RegVT = *RC->vt_begin(); 6673 6674 // This is a explicit reference to a physical register. 6675 Regs.push_back(AssignedReg); 6676 6677 // If this is an expanded reference, add the rest of the regs to Regs. 6678 if (NumRegs != 1) { 6679 TargetRegisterClass::iterator I = RC->begin(); 6680 for (; *I != AssignedReg; ++I) 6681 assert(I != RC->end() && "Didn't find reg!"); 6682 6683 // Already added the first reg. 6684 --NumRegs; ++I; 6685 for (; NumRegs; --NumRegs, ++I) { 6686 assert(I != RC->end() && "Ran out of registers to allocate!"); 6687 Regs.push_back(*I); 6688 } 6689 } 6690 6691 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 6692 return; 6693 } 6694 6695 // Otherwise, if this was a reference to an LLVM register class, create vregs 6696 // for this reference. 6697 if (const TargetRegisterClass *RC = PhysReg.second) { 6698 RegVT = *RC->vt_begin(); 6699 if (OpInfo.ConstraintVT == MVT::Other) 6700 ValueVT = RegVT; 6701 6702 // Create the appropriate number of virtual registers. 6703 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6704 for (; NumRegs; --NumRegs) 6705 Regs.push_back(RegInfo.createVirtualRegister(RC)); 6706 6707 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 6708 return; 6709 } 6710 6711 // Otherwise, we couldn't allocate enough registers for this. 6712 } 6713 6714 static unsigned 6715 findMatchingInlineAsmOperand(unsigned OperandNo, 6716 const std::vector<SDValue> &AsmNodeOperands) { 6717 // Scan until we find the definition we already emitted of this operand. 6718 unsigned CurOp = InlineAsm::Op_FirstOperand; 6719 for (; OperandNo; --OperandNo) { 6720 // Advance to the next operand. 6721 unsigned OpFlag = 6722 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 6723 assert((InlineAsm::isRegDefKind(OpFlag) || 6724 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 6725 InlineAsm::isMemKind(OpFlag)) && 6726 "Skipped past definitions?"); 6727 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 6728 } 6729 return CurOp; 6730 } 6731 6732 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT 6733 /// \return true if it has succeeded, false otherwise 6734 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs, 6735 MVT RegVT, SelectionDAG &DAG) { 6736 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6737 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 6738 for (unsigned i = 0, e = NumRegs; i != e; ++i) { 6739 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 6740 Regs.push_back(RegInfo.createVirtualRegister(RC)); 6741 else 6742 return false; 6743 } 6744 return true; 6745 } 6746 6747 class ExtraFlags { 6748 unsigned Flags = 0; 6749 6750 public: 6751 explicit ExtraFlags(ImmutableCallSite CS) { 6752 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 6753 if (IA->hasSideEffects()) 6754 Flags |= InlineAsm::Extra_HasSideEffects; 6755 if (IA->isAlignStack()) 6756 Flags |= InlineAsm::Extra_IsAlignStack; 6757 if (CS.isConvergent()) 6758 Flags |= InlineAsm::Extra_IsConvergent; 6759 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 6760 } 6761 6762 void update(const llvm::TargetLowering::AsmOperandInfo &OpInfo) { 6763 // Ideally, we would only check against memory constraints. However, the 6764 // meaning of an Other constraint can be target-specific and we can't easily 6765 // reason about it. Therefore, be conservative and set MayLoad/MayStore 6766 // for Other constraints as well. 6767 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 6768 OpInfo.ConstraintType == TargetLowering::C_Other) { 6769 if (OpInfo.Type == InlineAsm::isInput) 6770 Flags |= InlineAsm::Extra_MayLoad; 6771 else if (OpInfo.Type == InlineAsm::isOutput) 6772 Flags |= InlineAsm::Extra_MayStore; 6773 else if (OpInfo.Type == InlineAsm::isClobber) 6774 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 6775 } 6776 } 6777 6778 unsigned get() const { return Flags; } 6779 }; 6780 6781 /// visitInlineAsm - Handle a call to an InlineAsm object. 6782 /// 6783 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 6784 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 6785 6786 /// ConstraintOperands - Information about all of the constraints. 6787 SDISelAsmOperandInfoVector ConstraintOperands; 6788 6789 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6790 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 6791 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 6792 6793 bool hasMemory = false; 6794 6795 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 6796 ExtraFlags ExtraInfo(CS); 6797 6798 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 6799 unsigned ResNo = 0; // ResNo - The result number of the next output. 6800 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 6801 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 6802 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 6803 6804 MVT OpVT = MVT::Other; 6805 6806 // Compute the value type for each operand. 6807 if (OpInfo.Type == InlineAsm::isInput || 6808 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 6809 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 6810 6811 // Process the call argument. BasicBlocks are labels, currently appearing 6812 // only in asm's. 6813 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 6814 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 6815 } else { 6816 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 6817 } 6818 6819 OpVT = 6820 OpInfo 6821 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 6822 .getSimpleVT(); 6823 } 6824 6825 if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 6826 // The return value of the call is this value. As such, there is no 6827 // corresponding argument. 6828 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 6829 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 6830 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 6831 STy->getElementType(ResNo)); 6832 } else { 6833 assert(ResNo == 0 && "Asm only has one result!"); 6834 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 6835 } 6836 ++ResNo; 6837 } 6838 6839 OpInfo.ConstraintVT = OpVT; 6840 6841 if (!hasMemory) 6842 hasMemory = OpInfo.hasMemory(TLI); 6843 6844 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 6845 // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]? 6846 auto TargetConstraint = TargetConstraints[i]; 6847 6848 // Compute the constraint code and ConstraintType to use. 6849 TLI.ComputeConstraintToUse(TargetConstraint, SDValue()); 6850 6851 ExtraInfo.update(TargetConstraint); 6852 } 6853 6854 SDValue Chain, Flag; 6855 6856 // We won't need to flush pending loads if this asm doesn't touch 6857 // memory and is nonvolatile. 6858 if (hasMemory || IA->hasSideEffects()) 6859 Chain = getRoot(); 6860 else 6861 Chain = DAG.getRoot(); 6862 6863 // Second pass over the constraints: compute which constraint option to use 6864 // and assign registers to constraints that want a specific physreg. 6865 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6866 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6867 6868 // If this is an output operand with a matching input operand, look up the 6869 // matching input. If their types mismatch, e.g. one is an integer, the 6870 // other is floating point, or their sizes are different, flag it as an 6871 // error. 6872 if (OpInfo.hasMatchingInput()) { 6873 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 6874 patchMatchingInput(OpInfo, Input, DAG); 6875 } 6876 6877 // Compute the constraint code and ConstraintType to use. 6878 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 6879 6880 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 6881 OpInfo.Type == InlineAsm::isClobber) 6882 continue; 6883 6884 // If this is a memory input, and if the operand is not indirect, do what we 6885 // need to to provide an address for the memory input. 6886 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 6887 !OpInfo.isIndirect) { 6888 assert((OpInfo.isMultipleAlternative || 6889 (OpInfo.Type == InlineAsm::isInput)) && 6890 "Can only indirectify direct input operands!"); 6891 6892 // Memory operands really want the address of the value. 6893 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 6894 6895 // There is no longer a Value* corresponding to this operand. 6896 OpInfo.CallOperandVal = nullptr; 6897 6898 // It is now an indirect operand. 6899 OpInfo.isIndirect = true; 6900 } 6901 6902 // If this constraint is for a specific register, allocate it before 6903 // anything else. 6904 if (OpInfo.ConstraintType == TargetLowering::C_Register) 6905 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 6906 } 6907 6908 // Third pass - Loop over all of the operands, assigning virtual or physregs 6909 // to register class operands. 6910 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6911 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6912 6913 // C_Register operands have already been allocated, Other/Memory don't need 6914 // to be. 6915 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 6916 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 6917 } 6918 6919 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 6920 std::vector<SDValue> AsmNodeOperands; 6921 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 6922 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 6923 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 6924 6925 // If we have a !srcloc metadata node associated with it, we want to attach 6926 // this to the ultimately generated inline asm machineinstr. To do this, we 6927 // pass in the third operand as this (potentially null) inline asm MDNode. 6928 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 6929 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 6930 6931 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 6932 // bits as operand 3. 6933 AsmNodeOperands.push_back(DAG.getTargetConstant( 6934 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 6935 6936 // Loop over all of the inputs, copying the operand values into the 6937 // appropriate registers and processing the output regs. 6938 RegsForValue RetValRegs; 6939 6940 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 6941 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 6942 6943 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6944 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6945 6946 switch (OpInfo.Type) { 6947 case InlineAsm::isOutput: { 6948 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 6949 OpInfo.ConstraintType != TargetLowering::C_Register) { 6950 // Memory output, or 'other' output (e.g. 'X' constraint). 6951 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 6952 6953 unsigned ConstraintID = 6954 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 6955 assert(ConstraintID != InlineAsm::Constraint_Unknown && 6956 "Failed to convert memory constraint code to constraint id."); 6957 6958 // Add information to the INLINEASM node to know about this output. 6959 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 6960 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 6961 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 6962 MVT::i32)); 6963 AsmNodeOperands.push_back(OpInfo.CallOperand); 6964 break; 6965 } 6966 6967 // Otherwise, this is a register or register class output. 6968 6969 // Copy the output from the appropriate register. Find a register that 6970 // we can use. 6971 if (OpInfo.AssignedRegs.Regs.empty()) { 6972 emitInlineAsmError( 6973 CS, "couldn't allocate output register for constraint '" + 6974 Twine(OpInfo.ConstraintCode) + "'"); 6975 return; 6976 } 6977 6978 // If this is an indirect operand, store through the pointer after the 6979 // asm. 6980 if (OpInfo.isIndirect) { 6981 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 6982 OpInfo.CallOperandVal)); 6983 } else { 6984 // This is the result value of the call. 6985 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 6986 // Concatenate this output onto the outputs list. 6987 RetValRegs.append(OpInfo.AssignedRegs); 6988 } 6989 6990 // Add information to the INLINEASM node to know that this register is 6991 // set. 6992 OpInfo.AssignedRegs 6993 .AddInlineAsmOperands(OpInfo.isEarlyClobber 6994 ? InlineAsm::Kind_RegDefEarlyClobber 6995 : InlineAsm::Kind_RegDef, 6996 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 6997 break; 6998 } 6999 case InlineAsm::isInput: { 7000 SDValue InOperandVal = OpInfo.CallOperand; 7001 7002 if (OpInfo.isMatchingInputConstraint()) { 7003 // If this is required to match an output register we have already set, 7004 // just use its register. 7005 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7006 AsmNodeOperands); 7007 unsigned OpFlag = 7008 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7009 if (InlineAsm::isRegDefKind(OpFlag) || 7010 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7011 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7012 if (OpInfo.isIndirect) { 7013 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7014 emitInlineAsmError(CS, "inline asm not supported yet:" 7015 " don't know how to handle tied " 7016 "indirect register inputs"); 7017 return; 7018 } 7019 7020 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7021 SmallVector<unsigned, 4> Regs; 7022 7023 if (!createVirtualRegs(Regs, 7024 InlineAsm::getNumOperandRegisters(OpFlag), 7025 RegVT, DAG)) { 7026 emitInlineAsmError(CS, "inline asm error: This value type register " 7027 "class is not natively supported!"); 7028 return; 7029 } 7030 7031 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7032 7033 SDLoc dl = getCurSDLoc(); 7034 // Use the produced MatchedRegs object to 7035 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7036 Chain, &Flag, CS.getInstruction()); 7037 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7038 true, OpInfo.getMatchedOperand(), dl, 7039 DAG, AsmNodeOperands); 7040 break; 7041 } 7042 7043 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7044 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7045 "Unexpected number of operands"); 7046 // Add information to the INLINEASM node to know about this input. 7047 // See InlineAsm.h isUseOperandTiedToDef. 7048 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7049 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7050 OpInfo.getMatchedOperand()); 7051 AsmNodeOperands.push_back(DAG.getTargetConstant( 7052 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7053 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7054 break; 7055 } 7056 7057 // Treat indirect 'X' constraint as memory. 7058 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7059 OpInfo.isIndirect) 7060 OpInfo.ConstraintType = TargetLowering::C_Memory; 7061 7062 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7063 std::vector<SDValue> Ops; 7064 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7065 Ops, DAG); 7066 if (Ops.empty()) { 7067 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7068 Twine(OpInfo.ConstraintCode) + "'"); 7069 return; 7070 } 7071 7072 // Add information to the INLINEASM node to know about this input. 7073 unsigned ResOpType = 7074 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7075 AsmNodeOperands.push_back(DAG.getTargetConstant( 7076 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7077 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7078 break; 7079 } 7080 7081 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7082 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7083 assert(InOperandVal.getValueType() == 7084 TLI.getPointerTy(DAG.getDataLayout()) && 7085 "Memory operands expect pointer values"); 7086 7087 unsigned ConstraintID = 7088 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7089 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7090 "Failed to convert memory constraint code to constraint id."); 7091 7092 // Add information to the INLINEASM node to know about this input. 7093 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7094 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7095 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7096 getCurSDLoc(), 7097 MVT::i32)); 7098 AsmNodeOperands.push_back(InOperandVal); 7099 break; 7100 } 7101 7102 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7103 OpInfo.ConstraintType == TargetLowering::C_Register) && 7104 "Unknown constraint type!"); 7105 7106 // TODO: Support this. 7107 if (OpInfo.isIndirect) { 7108 emitInlineAsmError( 7109 CS, "Don't know how to handle indirect register inputs yet " 7110 "for constraint '" + 7111 Twine(OpInfo.ConstraintCode) + "'"); 7112 return; 7113 } 7114 7115 // Copy the input into the appropriate registers. 7116 if (OpInfo.AssignedRegs.Regs.empty()) { 7117 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7118 Twine(OpInfo.ConstraintCode) + "'"); 7119 return; 7120 } 7121 7122 SDLoc dl = getCurSDLoc(); 7123 7124 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7125 Chain, &Flag, CS.getInstruction()); 7126 7127 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7128 dl, DAG, AsmNodeOperands); 7129 break; 7130 } 7131 case InlineAsm::isClobber: { 7132 // Add the clobbered value to the operand list, so that the register 7133 // allocator is aware that the physreg got clobbered. 7134 if (!OpInfo.AssignedRegs.Regs.empty()) 7135 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7136 false, 0, getCurSDLoc(), DAG, 7137 AsmNodeOperands); 7138 break; 7139 } 7140 } 7141 } 7142 7143 // Finish up input operands. Set the input chain and add the flag last. 7144 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7145 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7146 7147 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7148 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7149 Flag = Chain.getValue(1); 7150 7151 // If this asm returns a register value, copy the result from that register 7152 // and set it as the value of the call. 7153 if (!RetValRegs.Regs.empty()) { 7154 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7155 Chain, &Flag, CS.getInstruction()); 7156 7157 // FIXME: Why don't we do this for inline asms with MRVs? 7158 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 7159 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7160 7161 // If any of the results of the inline asm is a vector, it may have the 7162 // wrong width/num elts. This can happen for register classes that can 7163 // contain multiple different value types. The preg or vreg allocated may 7164 // not have the same VT as was expected. Convert it to the right type 7165 // with bit_convert. 7166 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 7167 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), 7168 ResultType, Val); 7169 7170 } else if (ResultType != Val.getValueType() && 7171 ResultType.isInteger() && Val.getValueType().isInteger()) { 7172 // If a result value was tied to an input value, the computed result may 7173 // have a wider width than the expected result. Extract the relevant 7174 // portion. 7175 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val); 7176 } 7177 7178 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 7179 } 7180 7181 setValue(CS.getInstruction(), Val); 7182 // Don't need to use this as a chain in this case. 7183 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 7184 return; 7185 } 7186 7187 std::vector<std::pair<SDValue, const Value *> > StoresToEmit; 7188 7189 // Process indirect outputs, first output all of the flagged copies out of 7190 // physregs. 7191 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 7192 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 7193 const Value *Ptr = IndirectStoresToEmit[i].second; 7194 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7195 Chain, &Flag, IA); 7196 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 7197 } 7198 7199 // Emit the non-flagged stores from the physregs. 7200 SmallVector<SDValue, 8> OutChains; 7201 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 7202 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first, 7203 getValue(StoresToEmit[i].second), 7204 MachinePointerInfo(StoresToEmit[i].second)); 7205 OutChains.push_back(Val); 7206 } 7207 7208 if (!OutChains.empty()) 7209 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7210 7211 DAG.setRoot(Chain); 7212 } 7213 7214 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7215 const Twine &Message) { 7216 LLVMContext &Ctx = *DAG.getContext(); 7217 Ctx.emitError(CS.getInstruction(), Message); 7218 7219 // Make sure we leave the DAG in a valid state 7220 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7221 auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7222 setValue(CS.getInstruction(), DAG.getUNDEF(VT)); 7223 } 7224 7225 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7226 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7227 MVT::Other, getRoot(), 7228 getValue(I.getArgOperand(0)), 7229 DAG.getSrcValue(I.getArgOperand(0)))); 7230 } 7231 7232 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7233 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7234 const DataLayout &DL = DAG.getDataLayout(); 7235 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7236 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7237 DAG.getSrcValue(I.getOperand(0)), 7238 DL.getABITypeAlignment(I.getType())); 7239 setValue(&I, V); 7240 DAG.setRoot(V.getValue(1)); 7241 } 7242 7243 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7244 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7245 MVT::Other, getRoot(), 7246 getValue(I.getArgOperand(0)), 7247 DAG.getSrcValue(I.getArgOperand(0)))); 7248 } 7249 7250 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7251 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7252 MVT::Other, getRoot(), 7253 getValue(I.getArgOperand(0)), 7254 getValue(I.getArgOperand(1)), 7255 DAG.getSrcValue(I.getArgOperand(0)), 7256 DAG.getSrcValue(I.getArgOperand(1)))); 7257 } 7258 7259 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7260 const Instruction &I, 7261 SDValue Op) { 7262 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7263 if (!Range) 7264 return Op; 7265 7266 Constant *Lo = cast<ConstantAsMetadata>(Range->getOperand(0))->getValue(); 7267 if (!Lo->isNullValue()) 7268 return Op; 7269 7270 Constant *Hi = cast<ConstantAsMetadata>(Range->getOperand(1))->getValue(); 7271 unsigned Bits = cast<ConstantInt>(Hi)->getValue().logBase2(); 7272 7273 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7274 7275 SDLoc SL = getCurSDLoc(); 7276 7277 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), 7278 Op, DAG.getValueType(SmallVT)); 7279 unsigned NumVals = Op.getNode()->getNumValues(); 7280 if (NumVals == 1) 7281 return ZExt; 7282 7283 SmallVector<SDValue, 4> Ops; 7284 7285 Ops.push_back(ZExt); 7286 for (unsigned I = 1; I != NumVals; ++I) 7287 Ops.push_back(Op.getValue(I)); 7288 7289 return DAG.getMergeValues(Ops, SL); 7290 } 7291 7292 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of 7293 /// the call being lowered. 7294 /// 7295 /// This is a helper for lowering intrinsics that follow a target calling 7296 /// convention or require stack pointer adjustment. Only a subset of the 7297 /// intrinsic's operands need to participate in the calling convention. 7298 void SelectionDAGBuilder::populateCallLoweringInfo( 7299 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 7300 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 7301 bool IsPatchPoint) { 7302 TargetLowering::ArgListTy Args; 7303 Args.reserve(NumArgs); 7304 7305 // Populate the argument list. 7306 // Attributes for args start at offset 1, after the return attribute. 7307 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1; 7308 ArgI != ArgE; ++ArgI) { 7309 const Value *V = CS->getOperand(ArgI); 7310 7311 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 7312 7313 TargetLowering::ArgListEntry Entry; 7314 Entry.Node = getValue(V); 7315 Entry.Ty = V->getType(); 7316 Entry.setAttributes(&CS, AttrI); 7317 Args.push_back(Entry); 7318 } 7319 7320 CLI.setDebugLoc(getCurSDLoc()) 7321 .setChain(getRoot()) 7322 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 7323 .setDiscardResult(CS->use_empty()) 7324 .setIsPatchPoint(IsPatchPoint); 7325 } 7326 7327 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap 7328 /// or patchpoint target node's operand list. 7329 /// 7330 /// Constants are converted to TargetConstants purely as an optimization to 7331 /// avoid constant materialization and register allocation. 7332 /// 7333 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 7334 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 7335 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 7336 /// address materialization and register allocation, but may also be required 7337 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 7338 /// alloca in the entry block, then the runtime may assume that the alloca's 7339 /// StackMap location can be read immediately after compilation and that the 7340 /// location is valid at any point during execution (this is similar to the 7341 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 7342 /// only available in a register, then the runtime would need to trap when 7343 /// execution reaches the StackMap in order to read the alloca's location. 7344 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 7345 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 7346 SelectionDAGBuilder &Builder) { 7347 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 7348 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 7349 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 7350 Ops.push_back( 7351 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 7352 Ops.push_back( 7353 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 7354 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 7355 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 7356 Ops.push_back(Builder.DAG.getTargetFrameIndex( 7357 FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout()))); 7358 } else 7359 Ops.push_back(OpVal); 7360 } 7361 } 7362 7363 /// \brief Lower llvm.experimental.stackmap directly to its target opcode. 7364 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 7365 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 7366 // [live variables...]) 7367 7368 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 7369 7370 SDValue Chain, InFlag, Callee, NullPtr; 7371 SmallVector<SDValue, 32> Ops; 7372 7373 SDLoc DL = getCurSDLoc(); 7374 Callee = getValue(CI.getCalledValue()); 7375 NullPtr = DAG.getIntPtrConstant(0, DL, true); 7376 7377 // The stackmap intrinsic only records the live variables (the arguemnts 7378 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 7379 // intrinsic, this won't be lowered to a function call. This means we don't 7380 // have to worry about calling conventions and target specific lowering code. 7381 // Instead we perform the call lowering right here. 7382 // 7383 // chain, flag = CALLSEQ_START(chain, 0) 7384 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 7385 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 7386 // 7387 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL); 7388 InFlag = Chain.getValue(1); 7389 7390 // Add the <id> and <numBytes> constants. 7391 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 7392 Ops.push_back(DAG.getTargetConstant( 7393 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 7394 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 7395 Ops.push_back(DAG.getTargetConstant( 7396 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 7397 MVT::i32)); 7398 7399 // Push live variables for the stack map. 7400 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 7401 7402 // We are not pushing any register mask info here on the operands list, 7403 // because the stackmap doesn't clobber anything. 7404 7405 // Push the chain and the glue flag. 7406 Ops.push_back(Chain); 7407 Ops.push_back(InFlag); 7408 7409 // Create the STACKMAP node. 7410 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7411 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 7412 Chain = SDValue(SM, 0); 7413 InFlag = Chain.getValue(1); 7414 7415 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 7416 7417 // Stackmaps don't generate values, so nothing goes into the NodeMap. 7418 7419 // Set the root to the target-lowered call chain. 7420 DAG.setRoot(Chain); 7421 7422 // Inform the Frame Information that we have a stackmap in this function. 7423 FuncInfo.MF->getFrameInfo().setHasStackMap(); 7424 } 7425 7426 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode. 7427 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 7428 const BasicBlock *EHPadBB) { 7429 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 7430 // i32 <numBytes>, 7431 // i8* <target>, 7432 // i32 <numArgs>, 7433 // [Args...], 7434 // [live variables...]) 7435 7436 CallingConv::ID CC = CS.getCallingConv(); 7437 bool IsAnyRegCC = CC == CallingConv::AnyReg; 7438 bool HasDef = !CS->getType()->isVoidTy(); 7439 SDLoc dl = getCurSDLoc(); 7440 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 7441 7442 // Handle immediate and symbolic callees. 7443 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 7444 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 7445 /*isTarget=*/true); 7446 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 7447 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 7448 SDLoc(SymbolicCallee), 7449 SymbolicCallee->getValueType(0)); 7450 7451 // Get the real number of arguments participating in the call <numArgs> 7452 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 7453 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 7454 7455 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 7456 // Intrinsics include all meta-operands up to but not including CC. 7457 unsigned NumMetaOpers = PatchPointOpers::CCPos; 7458 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 7459 "Not enough arguments provided to the patchpoint intrinsic"); 7460 7461 // For AnyRegCC the arguments are lowered later on manually. 7462 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 7463 Type *ReturnTy = 7464 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 7465 7466 TargetLowering::CallLoweringInfo CLI(DAG); 7467 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 7468 true); 7469 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7470 7471 SDNode *CallEnd = Result.second.getNode(); 7472 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 7473 CallEnd = CallEnd->getOperand(0).getNode(); 7474 7475 /// Get a call instruction from the call sequence chain. 7476 /// Tail calls are not allowed. 7477 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 7478 "Expected a callseq node."); 7479 SDNode *Call = CallEnd->getOperand(0).getNode(); 7480 bool HasGlue = Call->getGluedNode(); 7481 7482 // Replace the target specific call node with the patchable intrinsic. 7483 SmallVector<SDValue, 8> Ops; 7484 7485 // Add the <id> and <numBytes> constants. 7486 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 7487 Ops.push_back(DAG.getTargetConstant( 7488 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 7489 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 7490 Ops.push_back(DAG.getTargetConstant( 7491 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 7492 MVT::i32)); 7493 7494 // Add the callee. 7495 Ops.push_back(Callee); 7496 7497 // Adjust <numArgs> to account for any arguments that have been passed on the 7498 // stack instead. 7499 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 7500 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 7501 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 7502 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 7503 7504 // Add the calling convention 7505 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 7506 7507 // Add the arguments we omitted previously. The register allocator should 7508 // place these in any free register. 7509 if (IsAnyRegCC) 7510 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 7511 Ops.push_back(getValue(CS.getArgument(i))); 7512 7513 // Push the arguments from the call instruction up to the register mask. 7514 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 7515 Ops.append(Call->op_begin() + 2, e); 7516 7517 // Push live variables for the stack map. 7518 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 7519 7520 // Push the register mask info. 7521 if (HasGlue) 7522 Ops.push_back(*(Call->op_end()-2)); 7523 else 7524 Ops.push_back(*(Call->op_end()-1)); 7525 7526 // Push the chain (this is originally the first operand of the call, but 7527 // becomes now the last or second to last operand). 7528 Ops.push_back(*(Call->op_begin())); 7529 7530 // Push the glue flag (last operand). 7531 if (HasGlue) 7532 Ops.push_back(*(Call->op_end()-1)); 7533 7534 SDVTList NodeTys; 7535 if (IsAnyRegCC && HasDef) { 7536 // Create the return types based on the intrinsic definition 7537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7538 SmallVector<EVT, 3> ValueVTs; 7539 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7540 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 7541 7542 // There is always a chain and a glue type at the end 7543 ValueVTs.push_back(MVT::Other); 7544 ValueVTs.push_back(MVT::Glue); 7545 NodeTys = DAG.getVTList(ValueVTs); 7546 } else 7547 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7548 7549 // Replace the target specific call node with a PATCHPOINT node. 7550 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 7551 dl, NodeTys, Ops); 7552 7553 // Update the NodeMap. 7554 if (HasDef) { 7555 if (IsAnyRegCC) 7556 setValue(CS.getInstruction(), SDValue(MN, 0)); 7557 else 7558 setValue(CS.getInstruction(), Result.first); 7559 } 7560 7561 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 7562 // call sequence. Furthermore the location of the chain and glue can change 7563 // when the AnyReg calling convention is used and the intrinsic returns a 7564 // value. 7565 if (IsAnyRegCC && HasDef) { 7566 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 7567 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 7568 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 7569 } else 7570 DAG.ReplaceAllUsesWith(Call, MN); 7571 DAG.DeleteNode(Call); 7572 7573 // Inform the Frame Information that we have a patchpoint in this function. 7574 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 7575 } 7576 7577 /// Returns an AttributeSet representing the attributes applied to the return 7578 /// value of the given call. 7579 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 7580 SmallVector<Attribute::AttrKind, 2> Attrs; 7581 if (CLI.RetSExt) 7582 Attrs.push_back(Attribute::SExt); 7583 if (CLI.RetZExt) 7584 Attrs.push_back(Attribute::ZExt); 7585 if (CLI.IsInReg) 7586 Attrs.push_back(Attribute::InReg); 7587 7588 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex, 7589 Attrs); 7590 } 7591 7592 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 7593 /// implementation, which just calls LowerCall. 7594 /// FIXME: When all targets are 7595 /// migrated to using LowerCall, this hook should be integrated into SDISel. 7596 std::pair<SDValue, SDValue> 7597 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 7598 // Handle the incoming return values from the call. 7599 CLI.Ins.clear(); 7600 Type *OrigRetTy = CLI.RetTy; 7601 SmallVector<EVT, 4> RetTys; 7602 SmallVector<uint64_t, 4> Offsets; 7603 auto &DL = CLI.DAG.getDataLayout(); 7604 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 7605 7606 SmallVector<ISD::OutputArg, 4> Outs; 7607 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 7608 7609 bool CanLowerReturn = 7610 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 7611 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 7612 7613 SDValue DemoteStackSlot; 7614 int DemoteStackIdx = -100; 7615 if (!CanLowerReturn) { 7616 // FIXME: equivalent assert? 7617 // assert(!CS.hasInAllocaArgument() && 7618 // "sret demotion is incompatible with inalloca"); 7619 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 7620 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 7621 MachineFunction &MF = CLI.DAG.getMachineFunction(); 7622 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7623 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy); 7624 7625 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL)); 7626 ArgListEntry Entry; 7627 Entry.Node = DemoteStackSlot; 7628 Entry.Ty = StackSlotPtrType; 7629 Entry.isSExt = false; 7630 Entry.isZExt = false; 7631 Entry.isInReg = false; 7632 Entry.isSRet = true; 7633 Entry.isNest = false; 7634 Entry.isByVal = false; 7635 Entry.isReturned = false; 7636 Entry.isSwiftSelf = false; 7637 Entry.isSwiftError = false; 7638 Entry.Alignment = Align; 7639 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 7640 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 7641 7642 // sret demotion isn't compatible with tail-calls, since the sret argument 7643 // points into the callers stack frame. 7644 CLI.IsTailCall = false; 7645 } else { 7646 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 7647 EVT VT = RetTys[I]; 7648 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT); 7649 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT); 7650 for (unsigned i = 0; i != NumRegs; ++i) { 7651 ISD::InputArg MyFlags; 7652 MyFlags.VT = RegisterVT; 7653 MyFlags.ArgVT = VT; 7654 MyFlags.Used = CLI.IsReturnValueUsed; 7655 if (CLI.RetSExt) 7656 MyFlags.Flags.setSExt(); 7657 if (CLI.RetZExt) 7658 MyFlags.Flags.setZExt(); 7659 if (CLI.IsInReg) 7660 MyFlags.Flags.setInReg(); 7661 CLI.Ins.push_back(MyFlags); 7662 } 7663 } 7664 } 7665 7666 // We push in swifterror return as the last element of CLI.Ins. 7667 ArgListTy &Args = CLI.getArgs(); 7668 if (supportSwiftError()) { 7669 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 7670 if (Args[i].isSwiftError) { 7671 ISD::InputArg MyFlags; 7672 MyFlags.VT = getPointerTy(DL); 7673 MyFlags.ArgVT = EVT(getPointerTy(DL)); 7674 MyFlags.Flags.setSwiftError(); 7675 CLI.Ins.push_back(MyFlags); 7676 } 7677 } 7678 } 7679 7680 // Handle all of the outgoing arguments. 7681 CLI.Outs.clear(); 7682 CLI.OutVals.clear(); 7683 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 7684 SmallVector<EVT, 4> ValueVTs; 7685 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 7686 Type *FinalType = Args[i].Ty; 7687 if (Args[i].isByVal) 7688 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 7689 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 7690 FinalType, CLI.CallConv, CLI.IsVarArg); 7691 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 7692 ++Value) { 7693 EVT VT = ValueVTs[Value]; 7694 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 7695 SDValue Op = SDValue(Args[i].Node.getNode(), 7696 Args[i].Node.getResNo() + Value); 7697 ISD::ArgFlagsTy Flags; 7698 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy); 7699 7700 if (Args[i].isZExt) 7701 Flags.setZExt(); 7702 if (Args[i].isSExt) 7703 Flags.setSExt(); 7704 if (Args[i].isInReg) 7705 Flags.setInReg(); 7706 if (Args[i].isSRet) 7707 Flags.setSRet(); 7708 if (Args[i].isSwiftSelf) 7709 Flags.setSwiftSelf(); 7710 if (Args[i].isSwiftError) 7711 Flags.setSwiftError(); 7712 if (Args[i].isByVal) 7713 Flags.setByVal(); 7714 if (Args[i].isInAlloca) { 7715 Flags.setInAlloca(); 7716 // Set the byval flag for CCAssignFn callbacks that don't know about 7717 // inalloca. This way we can know how many bytes we should've allocated 7718 // and how many bytes a callee cleanup function will pop. If we port 7719 // inalloca to more targets, we'll have to add custom inalloca handling 7720 // in the various CC lowering callbacks. 7721 Flags.setByVal(); 7722 } 7723 if (Args[i].isByVal || Args[i].isInAlloca) { 7724 PointerType *Ty = cast<PointerType>(Args[i].Ty); 7725 Type *ElementTy = Ty->getElementType(); 7726 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 7727 // For ByVal, alignment should come from FE. BE will guess if this 7728 // info is not there but there are cases it cannot get right. 7729 unsigned FrameAlign; 7730 if (Args[i].Alignment) 7731 FrameAlign = Args[i].Alignment; 7732 else 7733 FrameAlign = getByValTypeAlignment(ElementTy, DL); 7734 Flags.setByValAlign(FrameAlign); 7735 } 7736 if (Args[i].isNest) 7737 Flags.setNest(); 7738 if (NeedsRegBlock) 7739 Flags.setInConsecutiveRegs(); 7740 Flags.setOrigAlign(OriginalAlignment); 7741 7742 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT); 7743 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT); 7744 SmallVector<SDValue, 4> Parts(NumParts); 7745 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 7746 7747 if (Args[i].isSExt) 7748 ExtendKind = ISD::SIGN_EXTEND; 7749 else if (Args[i].isZExt) 7750 ExtendKind = ISD::ZERO_EXTEND; 7751 7752 // Conservatively only handle 'returned' on non-vectors for now 7753 if (Args[i].isReturned && !Op.getValueType().isVector()) { 7754 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 7755 "unexpected use of 'returned'"); 7756 // Before passing 'returned' to the target lowering code, ensure that 7757 // either the register MVT and the actual EVT are the same size or that 7758 // the return value and argument are extended in the same way; in these 7759 // cases it's safe to pass the argument register value unchanged as the 7760 // return register value (although it's at the target's option whether 7761 // to do so) 7762 // TODO: allow code generation to take advantage of partially preserved 7763 // registers rather than clobbering the entire register when the 7764 // parameter extension method is not compatible with the return 7765 // extension method 7766 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 7767 (ExtendKind != ISD::ANY_EXTEND && 7768 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt)) 7769 Flags.setReturned(); 7770 } 7771 7772 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 7773 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind); 7774 7775 for (unsigned j = 0; j != NumParts; ++j) { 7776 // if it isn't first piece, alignment must be 1 7777 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 7778 i < CLI.NumFixedArgs, 7779 i, j*Parts[j].getValueType().getStoreSize()); 7780 if (NumParts > 1 && j == 0) 7781 MyFlags.Flags.setSplit(); 7782 else if (j != 0) { 7783 MyFlags.Flags.setOrigAlign(1); 7784 if (j == NumParts - 1) 7785 MyFlags.Flags.setSplitEnd(); 7786 } 7787 7788 CLI.Outs.push_back(MyFlags); 7789 CLI.OutVals.push_back(Parts[j]); 7790 } 7791 7792 if (NeedsRegBlock && Value == NumValues - 1) 7793 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 7794 } 7795 } 7796 7797 SmallVector<SDValue, 4> InVals; 7798 CLI.Chain = LowerCall(CLI, InVals); 7799 7800 // Update CLI.InVals to use outside of this function. 7801 CLI.InVals = InVals; 7802 7803 // Verify that the target's LowerCall behaved as expected. 7804 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 7805 "LowerCall didn't return a valid chain!"); 7806 assert((!CLI.IsTailCall || InVals.empty()) && 7807 "LowerCall emitted a return value for a tail call!"); 7808 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 7809 "LowerCall didn't emit the correct number of values!"); 7810 7811 // For a tail call, the return value is merely live-out and there aren't 7812 // any nodes in the DAG representing it. Return a special value to 7813 // indicate that a tail call has been emitted and no more Instructions 7814 // should be processed in the current block. 7815 if (CLI.IsTailCall) { 7816 CLI.DAG.setRoot(CLI.Chain); 7817 return std::make_pair(SDValue(), SDValue()); 7818 } 7819 7820 #ifndef NDEBUG 7821 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 7822 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 7823 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 7824 "LowerCall emitted a value with the wrong type!"); 7825 } 7826 #endif 7827 7828 SmallVector<SDValue, 4> ReturnValues; 7829 if (!CanLowerReturn) { 7830 // The instruction result is the result of loading from the 7831 // hidden sret parameter. 7832 SmallVector<EVT, 1> PVTs; 7833 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy); 7834 7835 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 7836 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 7837 EVT PtrVT = PVTs[0]; 7838 7839 unsigned NumValues = RetTys.size(); 7840 ReturnValues.resize(NumValues); 7841 SmallVector<SDValue, 4> Chains(NumValues); 7842 7843 // An aggregate return value cannot wrap around the address space, so 7844 // offsets to its parts don't wrap either. 7845 SDNodeFlags Flags; 7846 Flags.setNoUnsignedWrap(true); 7847 7848 for (unsigned i = 0; i < NumValues; ++i) { 7849 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 7850 CLI.DAG.getConstant(Offsets[i], CLI.DL, 7851 PtrVT), &Flags); 7852 SDValue L = CLI.DAG.getLoad( 7853 RetTys[i], CLI.DL, CLI.Chain, Add, 7854 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 7855 DemoteStackIdx, Offsets[i]), 7856 /* Alignment = */ 1); 7857 ReturnValues[i] = L; 7858 Chains[i] = L.getValue(1); 7859 } 7860 7861 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 7862 } else { 7863 // Collect the legal value parts into potentially illegal values 7864 // that correspond to the original function's return values. 7865 Optional<ISD::NodeType> AssertOp; 7866 if (CLI.RetSExt) 7867 AssertOp = ISD::AssertSext; 7868 else if (CLI.RetZExt) 7869 AssertOp = ISD::AssertZext; 7870 unsigned CurReg = 0; 7871 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 7872 EVT VT = RetTys[I]; 7873 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT); 7874 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT); 7875 7876 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 7877 NumRegs, RegisterVT, VT, nullptr, 7878 AssertOp)); 7879 CurReg += NumRegs; 7880 } 7881 7882 // For a function returning void, there is no return value. We can't create 7883 // such a node, so we just return a null return value in that case. In 7884 // that case, nothing will actually look at the value. 7885 if (ReturnValues.empty()) 7886 return std::make_pair(SDValue(), CLI.Chain); 7887 } 7888 7889 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 7890 CLI.DAG.getVTList(RetTys), ReturnValues); 7891 return std::make_pair(Res, CLI.Chain); 7892 } 7893 7894 void TargetLowering::LowerOperationWrapper(SDNode *N, 7895 SmallVectorImpl<SDValue> &Results, 7896 SelectionDAG &DAG) const { 7897 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 7898 Results.push_back(Res); 7899 } 7900 7901 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7902 llvm_unreachable("LowerOperation not implemented for this target!"); 7903 } 7904 7905 void 7906 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 7907 SDValue Op = getNonRegisterValue(V); 7908 assert((Op.getOpcode() != ISD::CopyFromReg || 7909 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 7910 "Copy from a reg to the same reg!"); 7911 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 7912 7913 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7914 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 7915 V->getType()); 7916 SDValue Chain = DAG.getEntryNode(); 7917 7918 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 7919 FuncInfo.PreferredExtendType.end()) 7920 ? ISD::ANY_EXTEND 7921 : FuncInfo.PreferredExtendType[V]; 7922 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 7923 PendingExports.push_back(Chain); 7924 } 7925 7926 #include "llvm/CodeGen/SelectionDAGISel.h" 7927 7928 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 7929 /// entry block, return true. This includes arguments used by switches, since 7930 /// the switch may expand into multiple basic blocks. 7931 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 7932 // With FastISel active, we may be splitting blocks, so force creation 7933 // of virtual registers for all non-dead arguments. 7934 if (FastISel) 7935 return A->use_empty(); 7936 7937 const BasicBlock &Entry = A->getParent()->front(); 7938 for (const User *U : A->users()) 7939 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 7940 return false; // Use not in entry block. 7941 7942 return true; 7943 } 7944 7945 void SelectionDAGISel::LowerArguments(const Function &F) { 7946 SelectionDAG &DAG = SDB->DAG; 7947 SDLoc dl = SDB->getCurSDLoc(); 7948 const DataLayout &DL = DAG.getDataLayout(); 7949 SmallVector<ISD::InputArg, 16> Ins; 7950 7951 if (!FuncInfo->CanLowerReturn) { 7952 // Put in an sret pointer parameter before all the other parameters. 7953 SmallVector<EVT, 1> ValueVTs; 7954 ComputeValueVTs(*TLI, DAG.getDataLayout(), 7955 PointerType::getUnqual(F.getReturnType()), ValueVTs); 7956 7957 // NOTE: Assuming that a pointer will never break down to more than one VT 7958 // or one register. 7959 ISD::ArgFlagsTy Flags; 7960 Flags.setSRet(); 7961 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 7962 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 7963 ISD::InputArg::NoArgIndex, 0); 7964 Ins.push_back(RetArg); 7965 } 7966 7967 // Set up the incoming argument description vector. 7968 unsigned Idx = 1; 7969 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); 7970 I != E; ++I, ++Idx) { 7971 SmallVector<EVT, 4> ValueVTs; 7972 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs); 7973 bool isArgValueUsed = !I->use_empty(); 7974 unsigned PartBase = 0; 7975 Type *FinalType = I->getType(); 7976 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) 7977 FinalType = cast<PointerType>(FinalType)->getElementType(); 7978 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 7979 FinalType, F.getCallingConv(), F.isVarArg()); 7980 for (unsigned Value = 0, NumValues = ValueVTs.size(); 7981 Value != NumValues; ++Value) { 7982 EVT VT = ValueVTs[Value]; 7983 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 7984 ISD::ArgFlagsTy Flags; 7985 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy); 7986 7987 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt)) 7988 Flags.setZExt(); 7989 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) 7990 Flags.setSExt(); 7991 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg)) 7992 Flags.setInReg(); 7993 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet)) 7994 Flags.setSRet(); 7995 if (F.getAttributes().hasAttribute(Idx, Attribute::SwiftSelf)) 7996 Flags.setSwiftSelf(); 7997 if (F.getAttributes().hasAttribute(Idx, Attribute::SwiftError)) 7998 Flags.setSwiftError(); 7999 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) 8000 Flags.setByVal(); 8001 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) { 8002 Flags.setInAlloca(); 8003 // Set the byval flag for CCAssignFn callbacks that don't know about 8004 // inalloca. This way we can know how many bytes we should've allocated 8005 // and how many bytes a callee cleanup function will pop. If we port 8006 // inalloca to more targets, we'll have to add custom inalloca handling 8007 // in the various CC lowering callbacks. 8008 Flags.setByVal(); 8009 } 8010 if (F.getCallingConv() == CallingConv::X86_INTR) { 8011 // IA Interrupt passes frame (1st parameter) by value in the stack. 8012 if (Idx == 1) 8013 Flags.setByVal(); 8014 } 8015 if (Flags.isByVal() || Flags.isInAlloca()) { 8016 PointerType *Ty = cast<PointerType>(I->getType()); 8017 Type *ElementTy = Ty->getElementType(); 8018 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8019 // For ByVal, alignment should be passed from FE. BE will guess if 8020 // this info is not there but there are cases it cannot get right. 8021 unsigned FrameAlign; 8022 if (F.getParamAlignment(Idx)) 8023 FrameAlign = F.getParamAlignment(Idx); 8024 else 8025 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 8026 Flags.setByValAlign(FrameAlign); 8027 } 8028 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest)) 8029 Flags.setNest(); 8030 if (NeedsRegBlock) 8031 Flags.setInConsecutiveRegs(); 8032 Flags.setOrigAlign(OriginalAlignment); 8033 8034 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 8035 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT); 8036 for (unsigned i = 0; i != NumRegs; ++i) { 8037 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 8038 Idx-1, PartBase+i*RegisterVT.getStoreSize()); 8039 if (NumRegs > 1 && i == 0) 8040 MyFlags.Flags.setSplit(); 8041 // if it isn't first piece, alignment must be 1 8042 else if (i > 0) { 8043 MyFlags.Flags.setOrigAlign(1); 8044 if (i == NumRegs - 1) 8045 MyFlags.Flags.setSplitEnd(); 8046 } 8047 Ins.push_back(MyFlags); 8048 } 8049 if (NeedsRegBlock && Value == NumValues - 1) 8050 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 8051 PartBase += VT.getStoreSize(); 8052 } 8053 } 8054 8055 // Call the target to set up the argument values. 8056 SmallVector<SDValue, 8> InVals; 8057 SDValue NewRoot = TLI->LowerFormalArguments( 8058 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 8059 8060 // Verify that the target's LowerFormalArguments behaved as expected. 8061 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 8062 "LowerFormalArguments didn't return a valid chain!"); 8063 assert(InVals.size() == Ins.size() && 8064 "LowerFormalArguments didn't emit the correct number of values!"); 8065 DEBUG({ 8066 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 8067 assert(InVals[i].getNode() && 8068 "LowerFormalArguments emitted a null value!"); 8069 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 8070 "LowerFormalArguments emitted a value with the wrong type!"); 8071 } 8072 }); 8073 8074 // Update the DAG with the new chain value resulting from argument lowering. 8075 DAG.setRoot(NewRoot); 8076 8077 // Set up the argument values. 8078 unsigned i = 0; 8079 Idx = 1; 8080 if (!FuncInfo->CanLowerReturn) { 8081 // Create a virtual register for the sret pointer, and put in a copy 8082 // from the sret argument into it. 8083 SmallVector<EVT, 1> ValueVTs; 8084 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8085 PointerType::getUnqual(F.getReturnType()), ValueVTs); 8086 MVT VT = ValueVTs[0].getSimpleVT(); 8087 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 8088 Optional<ISD::NodeType> AssertOp = None; 8089 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 8090 RegVT, VT, nullptr, AssertOp); 8091 8092 MachineFunction& MF = SDB->DAG.getMachineFunction(); 8093 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 8094 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 8095 FuncInfo->DemoteRegister = SRetReg; 8096 NewRoot = 8097 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 8098 DAG.setRoot(NewRoot); 8099 8100 // i indexes lowered arguments. Bump it past the hidden sret argument. 8101 // Idx indexes LLVM arguments. Don't touch it. 8102 ++i; 8103 } 8104 8105 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 8106 ++I, ++Idx) { 8107 SmallVector<SDValue, 4> ArgValues; 8108 SmallVector<EVT, 4> ValueVTs; 8109 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs); 8110 unsigned NumValues = ValueVTs.size(); 8111 8112 // If this argument is unused then remember its value. It is used to generate 8113 // debugging information. 8114 if (I->use_empty() && NumValues) { 8115 SDB->setUnusedArgValue(&*I, InVals[i]); 8116 8117 // Also remember any frame index for use in FastISel. 8118 if (FrameIndexSDNode *FI = 8119 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 8120 FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex()); 8121 } 8122 8123 for (unsigned Val = 0; Val != NumValues; ++Val) { 8124 EVT VT = ValueVTs[Val]; 8125 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 8126 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT); 8127 8128 if (!I->use_empty()) { 8129 Optional<ISD::NodeType> AssertOp; 8130 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) 8131 AssertOp = ISD::AssertSext; 8132 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt)) 8133 AssertOp = ISD::AssertZext; 8134 8135 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], 8136 NumParts, PartVT, VT, 8137 nullptr, AssertOp)); 8138 } 8139 8140 i += NumParts; 8141 } 8142 8143 // We don't need to do anything else for unused arguments. 8144 if (ArgValues.empty()) 8145 continue; 8146 8147 // Note down frame index. 8148 if (FrameIndexSDNode *FI = 8149 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 8150 FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex()); 8151 8152 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 8153 SDB->getCurSDLoc()); 8154 8155 SDB->setValue(&*I, Res); 8156 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 8157 if (LoadSDNode *LNode = 8158 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode())) 8159 if (FrameIndexSDNode *FI = 8160 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 8161 FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex()); 8162 } 8163 8164 // Update SwiftErrorMap. 8165 if (Res.getOpcode() == ISD::CopyFromReg && TLI->supportSwiftError() && 8166 F.getAttributes().hasAttribute(Idx, Attribute::SwiftError)) { 8167 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 8168 if (TargetRegisterInfo::isVirtualRegister(Reg)) 8169 FuncInfo->SwiftErrorMap[FuncInfo->MBB][0] = Reg; 8170 } 8171 8172 // If this argument is live outside of the entry block, insert a copy from 8173 // wherever we got it to the vreg that other BB's will reference it as. 8174 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 8175 // If we can, though, try to skip creating an unnecessary vreg. 8176 // FIXME: This isn't very clean... it would be nice to make this more 8177 // general. It's also subtly incompatible with the hacks FastISel 8178 // uses with vregs. 8179 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 8180 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 8181 FuncInfo->ValueMap[&*I] = Reg; 8182 continue; 8183 } 8184 } 8185 if (!isOnlyUsedInEntryBlock(&*I, TM.Options.EnableFastISel)) { 8186 FuncInfo->InitializeRegForValue(&*I); 8187 SDB->CopyToExportRegsIfNeeded(&*I); 8188 } 8189 } 8190 8191 assert(i == InVals.size() && "Argument register count mismatch!"); 8192 8193 // Finally, if the target has anything special to do, allow it to do so. 8194 EmitFunctionEntryCode(); 8195 } 8196 8197 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 8198 /// ensure constants are generated when needed. Remember the virtual registers 8199 /// that need to be added to the Machine PHI nodes as input. We cannot just 8200 /// directly add them, because expansion might result in multiple MBB's for one 8201 /// BB. As such, the start of the BB might correspond to a different MBB than 8202 /// the end. 8203 /// 8204 void 8205 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 8206 const TerminatorInst *TI = LLVMBB->getTerminator(); 8207 8208 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 8209 8210 // Check PHI nodes in successors that expect a value to be available from this 8211 // block. 8212 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 8213 const BasicBlock *SuccBB = TI->getSuccessor(succ); 8214 if (!isa<PHINode>(SuccBB->begin())) continue; 8215 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 8216 8217 // If this terminator has multiple identical successors (common for 8218 // switches), only handle each succ once. 8219 if (!SuccsHandled.insert(SuccMBB).second) 8220 continue; 8221 8222 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 8223 8224 // At this point we know that there is a 1-1 correspondence between LLVM PHI 8225 // nodes and Machine PHI nodes, but the incoming operands have not been 8226 // emitted yet. 8227 for (BasicBlock::const_iterator I = SuccBB->begin(); 8228 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 8229 // Ignore dead phi's. 8230 if (PN->use_empty()) continue; 8231 8232 // Skip empty types 8233 if (PN->getType()->isEmptyTy()) 8234 continue; 8235 8236 unsigned Reg; 8237 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 8238 8239 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 8240 unsigned &RegOut = ConstantsOut[C]; 8241 if (RegOut == 0) { 8242 RegOut = FuncInfo.CreateRegs(C->getType()); 8243 CopyValueToVirtualRegister(C, RegOut); 8244 } 8245 Reg = RegOut; 8246 } else { 8247 DenseMap<const Value *, unsigned>::iterator I = 8248 FuncInfo.ValueMap.find(PHIOp); 8249 if (I != FuncInfo.ValueMap.end()) 8250 Reg = I->second; 8251 else { 8252 assert(isa<AllocaInst>(PHIOp) && 8253 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 8254 "Didn't codegen value into a register!??"); 8255 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 8256 CopyValueToVirtualRegister(PHIOp, Reg); 8257 } 8258 } 8259 8260 // Remember that this register needs to added to the machine PHI node as 8261 // the input for this MBB. 8262 SmallVector<EVT, 4> ValueVTs; 8263 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8264 ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs); 8265 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 8266 EVT VT = ValueVTs[vti]; 8267 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 8268 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 8269 FuncInfo.PHINodesToUpdate.push_back( 8270 std::make_pair(&*MBBI++, Reg + i)); 8271 Reg += NumRegisters; 8272 } 8273 } 8274 } 8275 8276 ConstantsOut.clear(); 8277 } 8278 8279 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 8280 /// is 0. 8281 MachineBasicBlock * 8282 SelectionDAGBuilder::StackProtectorDescriptor:: 8283 AddSuccessorMBB(const BasicBlock *BB, 8284 MachineBasicBlock *ParentMBB, 8285 bool IsLikely, 8286 MachineBasicBlock *SuccMBB) { 8287 // If SuccBB has not been created yet, create it. 8288 if (!SuccMBB) { 8289 MachineFunction *MF = ParentMBB->getParent(); 8290 MachineFunction::iterator BBI(ParentMBB); 8291 SuccMBB = MF->CreateMachineBasicBlock(BB); 8292 MF->insert(++BBI, SuccMBB); 8293 } 8294 // Add it as a successor of ParentMBB. 8295 ParentMBB->addSuccessor( 8296 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 8297 return SuccMBB; 8298 } 8299 8300 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 8301 MachineFunction::iterator I(MBB); 8302 if (++I == FuncInfo.MF->end()) 8303 return nullptr; 8304 return &*I; 8305 } 8306 8307 /// During lowering new call nodes can be created (such as memset, etc.). 8308 /// Those will become new roots of the current DAG, but complications arise 8309 /// when they are tail calls. In such cases, the call lowering will update 8310 /// the root, but the builder still needs to know that a tail call has been 8311 /// lowered in order to avoid generating an additional return. 8312 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 8313 // If the node is null, we do have a tail call. 8314 if (MaybeTC.getNode() != nullptr) 8315 DAG.setRoot(MaybeTC); 8316 else 8317 HasTailCall = true; 8318 } 8319 8320 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters, 8321 unsigned *TotalCases, unsigned First, 8322 unsigned Last, 8323 unsigned Density) { 8324 assert(Last >= First); 8325 assert(TotalCases[Last] >= TotalCases[First]); 8326 8327 APInt LowCase = Clusters[First].Low->getValue(); 8328 APInt HighCase = Clusters[Last].High->getValue(); 8329 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 8330 8331 // FIXME: A range of consecutive cases has 100% density, but only requires one 8332 // comparison to lower. We should discriminate against such consecutive ranges 8333 // in jump tables. 8334 8335 uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100); 8336 uint64_t Range = Diff + 1; 8337 8338 uint64_t NumCases = 8339 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 8340 8341 assert(NumCases < UINT64_MAX / 100); 8342 assert(Range >= NumCases); 8343 8344 return NumCases * 100 >= Range * Density; 8345 } 8346 8347 static inline bool areJTsAllowed(const TargetLowering &TLI, 8348 const SwitchInst *SI) { 8349 const Function *Fn = SI->getParent()->getParent(); 8350 if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true") 8351 return false; 8352 8353 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) || 8354 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other); 8355 } 8356 8357 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters, 8358 unsigned First, unsigned Last, 8359 const SwitchInst *SI, 8360 MachineBasicBlock *DefaultMBB, 8361 CaseCluster &JTCluster) { 8362 assert(First <= Last); 8363 8364 auto Prob = BranchProbability::getZero(); 8365 unsigned NumCmps = 0; 8366 std::vector<MachineBasicBlock*> Table; 8367 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 8368 8369 // Initialize probabilities in JTProbs. 8370 for (unsigned I = First; I <= Last; ++I) 8371 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 8372 8373 for (unsigned I = First; I <= Last; ++I) { 8374 assert(Clusters[I].Kind == CC_Range); 8375 Prob += Clusters[I].Prob; 8376 APInt Low = Clusters[I].Low->getValue(); 8377 APInt High = Clusters[I].High->getValue(); 8378 NumCmps += (Low == High) ? 1 : 2; 8379 if (I != First) { 8380 // Fill the gap between this and the previous cluster. 8381 APInt PreviousHigh = Clusters[I - 1].High->getValue(); 8382 assert(PreviousHigh.slt(Low)); 8383 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 8384 for (uint64_t J = 0; J < Gap; J++) 8385 Table.push_back(DefaultMBB); 8386 } 8387 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 8388 for (uint64_t J = 0; J < ClusterSize; ++J) 8389 Table.push_back(Clusters[I].MBB); 8390 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 8391 } 8392 8393 unsigned NumDests = JTProbs.size(); 8394 if (isSuitableForBitTests(NumDests, NumCmps, 8395 Clusters[First].Low->getValue(), 8396 Clusters[Last].High->getValue())) { 8397 // Clusters[First..Last] should be lowered as bit tests instead. 8398 return false; 8399 } 8400 8401 // Create the MBB that will load from and jump through the table. 8402 // Note: We create it here, but it's not inserted into the function yet. 8403 MachineFunction *CurMF = FuncInfo.MF; 8404 MachineBasicBlock *JumpTableMBB = 8405 CurMF->CreateMachineBasicBlock(SI->getParent()); 8406 8407 // Add successors. Note: use table order for determinism. 8408 SmallPtrSet<MachineBasicBlock *, 8> Done; 8409 for (MachineBasicBlock *Succ : Table) { 8410 if (Done.count(Succ)) 8411 continue; 8412 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 8413 Done.insert(Succ); 8414 } 8415 JumpTableMBB->normalizeSuccProbs(); 8416 8417 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8418 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 8419 ->createJumpTableIndex(Table); 8420 8421 // Set up the jump table info. 8422 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 8423 JumpTableHeader JTH(Clusters[First].Low->getValue(), 8424 Clusters[Last].High->getValue(), SI->getCondition(), 8425 nullptr, false); 8426 JTCases.emplace_back(std::move(JTH), std::move(JT)); 8427 8428 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 8429 JTCases.size() - 1, Prob); 8430 return true; 8431 } 8432 8433 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 8434 const SwitchInst *SI, 8435 MachineBasicBlock *DefaultMBB) { 8436 #ifndef NDEBUG 8437 // Clusters must be non-empty, sorted, and only contain Range clusters. 8438 assert(!Clusters.empty()); 8439 for (CaseCluster &C : Clusters) 8440 assert(C.Kind == CC_Range); 8441 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 8442 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 8443 #endif 8444 8445 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8446 if (!areJTsAllowed(TLI, SI)) 8447 return; 8448 8449 const int64_t N = Clusters.size(); 8450 const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries(); 8451 8452 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 8453 SmallVector<unsigned, 8> TotalCases(N); 8454 8455 for (unsigned i = 0; i < N; ++i) { 8456 APInt Hi = Clusters[i].High->getValue(); 8457 APInt Lo = Clusters[i].Low->getValue(); 8458 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 8459 if (i != 0) 8460 TotalCases[i] += TotalCases[i - 1]; 8461 } 8462 8463 unsigned MinDensity = JumpTableDensity; 8464 if (DefaultMBB->getParent()->getFunction()->optForSize()) 8465 MinDensity = OptsizeJumpTableDensity; 8466 if (N >= MinJumpTableSize 8467 && isDense(Clusters, &TotalCases[0], 0, N - 1, MinDensity)) { 8468 // Cheap case: the whole range might be suitable for jump table. 8469 CaseCluster JTCluster; 8470 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 8471 Clusters[0] = JTCluster; 8472 Clusters.resize(1); 8473 return; 8474 } 8475 } 8476 8477 // The algorithm below is not suitable for -O0. 8478 if (TM.getOptLevel() == CodeGenOpt::None) 8479 return; 8480 8481 // Split Clusters into minimum number of dense partitions. The algorithm uses 8482 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 8483 // for the Case Statement'" (1994), but builds the MinPartitions array in 8484 // reverse order to make it easier to reconstruct the partitions in ascending 8485 // order. In the choice between two optimal partitionings, it picks the one 8486 // which yields more jump tables. 8487 8488 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 8489 SmallVector<unsigned, 8> MinPartitions(N); 8490 // LastElement[i] is the last element of the partition starting at i. 8491 SmallVector<unsigned, 8> LastElement(N); 8492 // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1]. 8493 SmallVector<unsigned, 8> NumTables(N); 8494 8495 // Base case: There is only one way to partition Clusters[N-1]. 8496 MinPartitions[N - 1] = 1; 8497 LastElement[N - 1] = N - 1; 8498 assert(MinJumpTableSize > 1); 8499 NumTables[N - 1] = 0; 8500 8501 // Note: loop indexes are signed to avoid underflow. 8502 for (int64_t i = N - 2; i >= 0; i--) { 8503 // Find optimal partitioning of Clusters[i..N-1]. 8504 // Baseline: Put Clusters[i] into a partition on its own. 8505 MinPartitions[i] = MinPartitions[i + 1] + 1; 8506 LastElement[i] = i; 8507 NumTables[i] = NumTables[i + 1]; 8508 8509 // Search for a solution that results in fewer partitions. 8510 for (int64_t j = N - 1; j > i; j--) { 8511 // Try building a partition from Clusters[i..j]. 8512 if (isDense(Clusters, &TotalCases[0], i, j, MinDensity)) { 8513 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 8514 bool IsTable = j - i + 1 >= MinJumpTableSize; 8515 unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]); 8516 8517 // If this j leads to fewer partitions, or same number of partitions 8518 // with more lookup tables, it is a better partitioning. 8519 if (NumPartitions < MinPartitions[i] || 8520 (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) { 8521 MinPartitions[i] = NumPartitions; 8522 LastElement[i] = j; 8523 NumTables[i] = Tables; 8524 } 8525 } 8526 } 8527 } 8528 8529 // Iterate over the partitions, replacing some with jump tables in-place. 8530 unsigned DstIndex = 0; 8531 for (unsigned First = 0, Last; First < N; First = Last + 1) { 8532 Last = LastElement[First]; 8533 assert(Last >= First); 8534 assert(DstIndex <= First); 8535 unsigned NumClusters = Last - First + 1; 8536 8537 CaseCluster JTCluster; 8538 if (NumClusters >= MinJumpTableSize && 8539 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 8540 Clusters[DstIndex++] = JTCluster; 8541 } else { 8542 for (unsigned I = First; I <= Last; ++I) 8543 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 8544 } 8545 } 8546 Clusters.resize(DstIndex); 8547 } 8548 8549 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) { 8550 // FIXME: Using the pointer type doesn't seem ideal. 8551 uint64_t BW = DAG.getDataLayout().getPointerSizeInBits(); 8552 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1; 8553 return Range <= BW; 8554 } 8555 8556 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests, 8557 unsigned NumCmps, 8558 const APInt &Low, 8559 const APInt &High) { 8560 // FIXME: I don't think NumCmps is the correct metric: a single case and a 8561 // range of cases both require only one branch to lower. Just looking at the 8562 // number of clusters and destinations should be enough to decide whether to 8563 // build bit tests. 8564 8565 // To lower a range with bit tests, the range must fit the bitwidth of a 8566 // machine word. 8567 if (!rangeFitsInWord(Low, High)) 8568 return false; 8569 8570 // Decide whether it's profitable to lower this range with bit tests. Each 8571 // destination requires a bit test and branch, and there is an overall range 8572 // check branch. For a small number of clusters, separate comparisons might be 8573 // cheaper, and for many destinations, splitting the range might be better. 8574 return (NumDests == 1 && NumCmps >= 3) || 8575 (NumDests == 2 && NumCmps >= 5) || 8576 (NumDests == 3 && NumCmps >= 6); 8577 } 8578 8579 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 8580 unsigned First, unsigned Last, 8581 const SwitchInst *SI, 8582 CaseCluster &BTCluster) { 8583 assert(First <= Last); 8584 if (First == Last) 8585 return false; 8586 8587 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 8588 unsigned NumCmps = 0; 8589 for (int64_t I = First; I <= Last; ++I) { 8590 assert(Clusters[I].Kind == CC_Range); 8591 Dests.set(Clusters[I].MBB->getNumber()); 8592 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 8593 } 8594 unsigned NumDests = Dests.count(); 8595 8596 APInt Low = Clusters[First].Low->getValue(); 8597 APInt High = Clusters[Last].High->getValue(); 8598 assert(Low.slt(High)); 8599 8600 if (!isSuitableForBitTests(NumDests, NumCmps, Low, High)) 8601 return false; 8602 8603 APInt LowBound; 8604 APInt CmpRange; 8605 8606 const int BitWidth = DAG.getTargetLoweringInfo() 8607 .getPointerTy(DAG.getDataLayout()) 8608 .getSizeInBits(); 8609 assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!"); 8610 8611 // Check if the clusters cover a contiguous range such that no value in the 8612 // range will jump to the default statement. 8613 bool ContiguousRange = true; 8614 for (int64_t I = First + 1; I <= Last; ++I) { 8615 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 8616 ContiguousRange = false; 8617 break; 8618 } 8619 } 8620 8621 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 8622 // Optimize the case where all the case values fit in a word without having 8623 // to subtract minValue. In this case, we can optimize away the subtraction. 8624 LowBound = APInt::getNullValue(Low.getBitWidth()); 8625 CmpRange = High; 8626 ContiguousRange = false; 8627 } else { 8628 LowBound = Low; 8629 CmpRange = High - Low; 8630 } 8631 8632 CaseBitsVector CBV; 8633 auto TotalProb = BranchProbability::getZero(); 8634 for (unsigned i = First; i <= Last; ++i) { 8635 // Find the CaseBits for this destination. 8636 unsigned j; 8637 for (j = 0; j < CBV.size(); ++j) 8638 if (CBV[j].BB == Clusters[i].MBB) 8639 break; 8640 if (j == CBV.size()) 8641 CBV.push_back( 8642 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 8643 CaseBits *CB = &CBV[j]; 8644 8645 // Update Mask, Bits and ExtraProb. 8646 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 8647 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 8648 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 8649 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 8650 CB->Bits += Hi - Lo + 1; 8651 CB->ExtraProb += Clusters[i].Prob; 8652 TotalProb += Clusters[i].Prob; 8653 } 8654 8655 BitTestInfo BTI; 8656 std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) { 8657 // Sort by probability first, number of bits second. 8658 if (a.ExtraProb != b.ExtraProb) 8659 return a.ExtraProb > b.ExtraProb; 8660 return a.Bits > b.Bits; 8661 }); 8662 8663 for (auto &CB : CBV) { 8664 MachineBasicBlock *BitTestBB = 8665 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 8666 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 8667 } 8668 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 8669 SI->getCondition(), -1U, MVT::Other, false, 8670 ContiguousRange, nullptr, nullptr, std::move(BTI), 8671 TotalProb); 8672 8673 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 8674 BitTestCases.size() - 1, TotalProb); 8675 return true; 8676 } 8677 8678 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 8679 const SwitchInst *SI) { 8680 // Partition Clusters into as few subsets as possible, where each subset has a 8681 // range that fits in a machine word and has <= 3 unique destinations. 8682 8683 #ifndef NDEBUG 8684 // Clusters must be sorted and contain Range or JumpTable clusters. 8685 assert(!Clusters.empty()); 8686 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 8687 for (const CaseCluster &C : Clusters) 8688 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 8689 for (unsigned i = 1; i < Clusters.size(); ++i) 8690 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 8691 #endif 8692 8693 // The algorithm below is not suitable for -O0. 8694 if (TM.getOptLevel() == CodeGenOpt::None) 8695 return; 8696 8697 // If target does not have legal shift left, do not emit bit tests at all. 8698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8699 EVT PTy = TLI.getPointerTy(DAG.getDataLayout()); 8700 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 8701 return; 8702 8703 int BitWidth = PTy.getSizeInBits(); 8704 const int64_t N = Clusters.size(); 8705 8706 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 8707 SmallVector<unsigned, 8> MinPartitions(N); 8708 // LastElement[i] is the last element of the partition starting at i. 8709 SmallVector<unsigned, 8> LastElement(N); 8710 8711 // FIXME: This might not be the best algorithm for finding bit test clusters. 8712 8713 // Base case: There is only one way to partition Clusters[N-1]. 8714 MinPartitions[N - 1] = 1; 8715 LastElement[N - 1] = N - 1; 8716 8717 // Note: loop indexes are signed to avoid underflow. 8718 for (int64_t i = N - 2; i >= 0; --i) { 8719 // Find optimal partitioning of Clusters[i..N-1]. 8720 // Baseline: Put Clusters[i] into a partition on its own. 8721 MinPartitions[i] = MinPartitions[i + 1] + 1; 8722 LastElement[i] = i; 8723 8724 // Search for a solution that results in fewer partitions. 8725 // Note: the search is limited by BitWidth, reducing time complexity. 8726 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 8727 // Try building a partition from Clusters[i..j]. 8728 8729 // Check the range. 8730 if (!rangeFitsInWord(Clusters[i].Low->getValue(), 8731 Clusters[j].High->getValue())) 8732 continue; 8733 8734 // Check nbr of destinations and cluster types. 8735 // FIXME: This works, but doesn't seem very efficient. 8736 bool RangesOnly = true; 8737 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 8738 for (int64_t k = i; k <= j; k++) { 8739 if (Clusters[k].Kind != CC_Range) { 8740 RangesOnly = false; 8741 break; 8742 } 8743 Dests.set(Clusters[k].MBB->getNumber()); 8744 } 8745 if (!RangesOnly || Dests.count() > 3) 8746 break; 8747 8748 // Check if it's a better partition. 8749 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 8750 if (NumPartitions < MinPartitions[i]) { 8751 // Found a better partition. 8752 MinPartitions[i] = NumPartitions; 8753 LastElement[i] = j; 8754 } 8755 } 8756 } 8757 8758 // Iterate over the partitions, replacing with bit-test clusters in-place. 8759 unsigned DstIndex = 0; 8760 for (unsigned First = 0, Last; First < N; First = Last + 1) { 8761 Last = LastElement[First]; 8762 assert(First <= Last); 8763 assert(DstIndex <= First); 8764 8765 CaseCluster BitTestCluster; 8766 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 8767 Clusters[DstIndex++] = BitTestCluster; 8768 } else { 8769 size_t NumClusters = Last - First + 1; 8770 std::memmove(&Clusters[DstIndex], &Clusters[First], 8771 sizeof(Clusters[0]) * NumClusters); 8772 DstIndex += NumClusters; 8773 } 8774 } 8775 Clusters.resize(DstIndex); 8776 } 8777 8778 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 8779 MachineBasicBlock *SwitchMBB, 8780 MachineBasicBlock *DefaultMBB) { 8781 MachineFunction *CurMF = FuncInfo.MF; 8782 MachineBasicBlock *NextMBB = nullptr; 8783 MachineFunction::iterator BBI(W.MBB); 8784 if (++BBI != FuncInfo.MF->end()) 8785 NextMBB = &*BBI; 8786 8787 unsigned Size = W.LastCluster - W.FirstCluster + 1; 8788 8789 BranchProbabilityInfo *BPI = FuncInfo.BPI; 8790 8791 if (Size == 2 && W.MBB == SwitchMBB) { 8792 // If any two of the cases has the same destination, and if one value 8793 // is the same as the other, but has one bit unset that the other has set, 8794 // use bit manipulation to do two compares at once. For example: 8795 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 8796 // TODO: This could be extended to merge any 2 cases in switches with 3 8797 // cases. 8798 // TODO: Handle cases where W.CaseBB != SwitchBB. 8799 CaseCluster &Small = *W.FirstCluster; 8800 CaseCluster &Big = *W.LastCluster; 8801 8802 if (Small.Low == Small.High && Big.Low == Big.High && 8803 Small.MBB == Big.MBB) { 8804 const APInt &SmallValue = Small.Low->getValue(); 8805 const APInt &BigValue = Big.Low->getValue(); 8806 8807 // Check that there is only one bit different. 8808 APInt CommonBit = BigValue ^ SmallValue; 8809 if (CommonBit.isPowerOf2()) { 8810 SDValue CondLHS = getValue(Cond); 8811 EVT VT = CondLHS.getValueType(); 8812 SDLoc DL = getCurSDLoc(); 8813 8814 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 8815 DAG.getConstant(CommonBit, DL, VT)); 8816 SDValue Cond = DAG.getSetCC( 8817 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 8818 ISD::SETEQ); 8819 8820 // Update successor info. 8821 // Both Small and Big will jump to Small.BB, so we sum up the 8822 // probabilities. 8823 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 8824 if (BPI) 8825 addSuccessorWithProb( 8826 SwitchMBB, DefaultMBB, 8827 // The default destination is the first successor in IR. 8828 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 8829 else 8830 addSuccessorWithProb(SwitchMBB, DefaultMBB); 8831 8832 // Insert the true branch. 8833 SDValue BrCond = 8834 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 8835 DAG.getBasicBlock(Small.MBB)); 8836 // Insert the false branch. 8837 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 8838 DAG.getBasicBlock(DefaultMBB)); 8839 8840 DAG.setRoot(BrCond); 8841 return; 8842 } 8843 } 8844 } 8845 8846 if (TM.getOptLevel() != CodeGenOpt::None) { 8847 // Order cases by probability so the most likely case will be checked first. 8848 std::sort(W.FirstCluster, W.LastCluster + 1, 8849 [](const CaseCluster &a, const CaseCluster &b) { 8850 return a.Prob > b.Prob; 8851 }); 8852 8853 // Rearrange the case blocks so that the last one falls through if possible 8854 // without without changing the order of probabilities. 8855 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 8856 --I; 8857 if (I->Prob > W.LastCluster->Prob) 8858 break; 8859 if (I->Kind == CC_Range && I->MBB == NextMBB) { 8860 std::swap(*I, *W.LastCluster); 8861 break; 8862 } 8863 } 8864 } 8865 8866 // Compute total probability. 8867 BranchProbability DefaultProb = W.DefaultProb; 8868 BranchProbability UnhandledProbs = DefaultProb; 8869 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 8870 UnhandledProbs += I->Prob; 8871 8872 MachineBasicBlock *CurMBB = W.MBB; 8873 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 8874 MachineBasicBlock *Fallthrough; 8875 if (I == W.LastCluster) { 8876 // For the last cluster, fall through to the default destination. 8877 Fallthrough = DefaultMBB; 8878 } else { 8879 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 8880 CurMF->insert(BBI, Fallthrough); 8881 // Put Cond in a virtual register to make it available from the new blocks. 8882 ExportFromCurrentBlock(Cond); 8883 } 8884 UnhandledProbs -= I->Prob; 8885 8886 switch (I->Kind) { 8887 case CC_JumpTable: { 8888 // FIXME: Optimize away range check based on pivot comparisons. 8889 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 8890 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 8891 8892 // The jump block hasn't been inserted yet; insert it here. 8893 MachineBasicBlock *JumpMBB = JT->MBB; 8894 CurMF->insert(BBI, JumpMBB); 8895 8896 auto JumpProb = I->Prob; 8897 auto FallthroughProb = UnhandledProbs; 8898 8899 // If the default statement is a target of the jump table, we evenly 8900 // distribute the default probability to successors of CurMBB. Also 8901 // update the probability on the edge from JumpMBB to Fallthrough. 8902 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 8903 SE = JumpMBB->succ_end(); 8904 SI != SE; ++SI) { 8905 if (*SI == DefaultMBB) { 8906 JumpProb += DefaultProb / 2; 8907 FallthroughProb -= DefaultProb / 2; 8908 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 8909 JumpMBB->normalizeSuccProbs(); 8910 break; 8911 } 8912 } 8913 8914 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 8915 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 8916 CurMBB->normalizeSuccProbs(); 8917 8918 // The jump table header will be inserted in our current block, do the 8919 // range check, and fall through to our fallthrough block. 8920 JTH->HeaderBB = CurMBB; 8921 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 8922 8923 // If we're in the right place, emit the jump table header right now. 8924 if (CurMBB == SwitchMBB) { 8925 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 8926 JTH->Emitted = true; 8927 } 8928 break; 8929 } 8930 case CC_BitTests: { 8931 // FIXME: Optimize away range check based on pivot comparisons. 8932 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 8933 8934 // The bit test blocks haven't been inserted yet; insert them here. 8935 for (BitTestCase &BTC : BTB->Cases) 8936 CurMF->insert(BBI, BTC.ThisBB); 8937 8938 // Fill in fields of the BitTestBlock. 8939 BTB->Parent = CurMBB; 8940 BTB->Default = Fallthrough; 8941 8942 BTB->DefaultProb = UnhandledProbs; 8943 // If the cases in bit test don't form a contiguous range, we evenly 8944 // distribute the probability on the edge to Fallthrough to two 8945 // successors of CurMBB. 8946 if (!BTB->ContiguousRange) { 8947 BTB->Prob += DefaultProb / 2; 8948 BTB->DefaultProb -= DefaultProb / 2; 8949 } 8950 8951 // If we're in the right place, emit the bit test header right now. 8952 if (CurMBB == SwitchMBB) { 8953 visitBitTestHeader(*BTB, SwitchMBB); 8954 BTB->Emitted = true; 8955 } 8956 break; 8957 } 8958 case CC_Range: { 8959 const Value *RHS, *LHS, *MHS; 8960 ISD::CondCode CC; 8961 if (I->Low == I->High) { 8962 // Check Cond == I->Low. 8963 CC = ISD::SETEQ; 8964 LHS = Cond; 8965 RHS=I->Low; 8966 MHS = nullptr; 8967 } else { 8968 // Check I->Low <= Cond <= I->High. 8969 CC = ISD::SETLE; 8970 LHS = I->Low; 8971 MHS = Cond; 8972 RHS = I->High; 8973 } 8974 8975 // The false probability is the sum of all unhandled cases. 8976 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Prob, 8977 UnhandledProbs); 8978 8979 if (CurMBB == SwitchMBB) 8980 visitSwitchCase(CB, SwitchMBB); 8981 else 8982 SwitchCases.push_back(CB); 8983 8984 break; 8985 } 8986 } 8987 CurMBB = Fallthrough; 8988 } 8989 } 8990 8991 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 8992 CaseClusterIt First, 8993 CaseClusterIt Last) { 8994 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 8995 if (X.Prob != CC.Prob) 8996 return X.Prob > CC.Prob; 8997 8998 // Ties are broken by comparing the case value. 8999 return X.Low->getValue().slt(CC.Low->getValue()); 9000 }); 9001 } 9002 9003 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 9004 const SwitchWorkListItem &W, 9005 Value *Cond, 9006 MachineBasicBlock *SwitchMBB) { 9007 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 9008 "Clusters not sorted?"); 9009 9010 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 9011 9012 // Balance the tree based on branch probabilities to create a near-optimal (in 9013 // terms of search time given key frequency) binary search tree. See e.g. Kurt 9014 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 9015 CaseClusterIt LastLeft = W.FirstCluster; 9016 CaseClusterIt FirstRight = W.LastCluster; 9017 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 9018 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 9019 9020 // Move LastLeft and FirstRight towards each other from opposite directions to 9021 // find a partitioning of the clusters which balances the probability on both 9022 // sides. If LeftProb and RightProb are equal, alternate which side is 9023 // taken to ensure 0-probability nodes are distributed evenly. 9024 unsigned I = 0; 9025 while (LastLeft + 1 < FirstRight) { 9026 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 9027 LeftProb += (++LastLeft)->Prob; 9028 else 9029 RightProb += (--FirstRight)->Prob; 9030 I++; 9031 } 9032 9033 for (;;) { 9034 // Our binary search tree differs from a typical BST in that ours can have up 9035 // to three values in each leaf. The pivot selection above doesn't take that 9036 // into account, which means the tree might require more nodes and be less 9037 // efficient. We compensate for this here. 9038 9039 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 9040 unsigned NumRight = W.LastCluster - FirstRight + 1; 9041 9042 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 9043 // If one side has less than 3 clusters, and the other has more than 3, 9044 // consider taking a cluster from the other side. 9045 9046 if (NumLeft < NumRight) { 9047 // Consider moving the first cluster on the right to the left side. 9048 CaseCluster &CC = *FirstRight; 9049 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 9050 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 9051 if (LeftSideRank <= RightSideRank) { 9052 // Moving the cluster to the left does not demote it. 9053 ++LastLeft; 9054 ++FirstRight; 9055 continue; 9056 } 9057 } else { 9058 assert(NumRight < NumLeft); 9059 // Consider moving the last element on the left to the right side. 9060 CaseCluster &CC = *LastLeft; 9061 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 9062 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 9063 if (RightSideRank <= LeftSideRank) { 9064 // Moving the cluster to the right does not demot it. 9065 --LastLeft; 9066 --FirstRight; 9067 continue; 9068 } 9069 } 9070 } 9071 break; 9072 } 9073 9074 assert(LastLeft + 1 == FirstRight); 9075 assert(LastLeft >= W.FirstCluster); 9076 assert(FirstRight <= W.LastCluster); 9077 9078 // Use the first element on the right as pivot since we will make less-than 9079 // comparisons against it. 9080 CaseClusterIt PivotCluster = FirstRight; 9081 assert(PivotCluster > W.FirstCluster); 9082 assert(PivotCluster <= W.LastCluster); 9083 9084 CaseClusterIt FirstLeft = W.FirstCluster; 9085 CaseClusterIt LastRight = W.LastCluster; 9086 9087 const ConstantInt *Pivot = PivotCluster->Low; 9088 9089 // New blocks will be inserted immediately after the current one. 9090 MachineFunction::iterator BBI(W.MBB); 9091 ++BBI; 9092 9093 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 9094 // we can branch to its destination directly if it's squeezed exactly in 9095 // between the known lower bound and Pivot - 1. 9096 MachineBasicBlock *LeftMBB; 9097 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 9098 FirstLeft->Low == W.GE && 9099 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 9100 LeftMBB = FirstLeft->MBB; 9101 } else { 9102 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 9103 FuncInfo.MF->insert(BBI, LeftMBB); 9104 WorkList.push_back( 9105 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 9106 // Put Cond in a virtual register to make it available from the new blocks. 9107 ExportFromCurrentBlock(Cond); 9108 } 9109 9110 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 9111 // single cluster, RHS.Low == Pivot, and we can branch to its destination 9112 // directly if RHS.High equals the current upper bound. 9113 MachineBasicBlock *RightMBB; 9114 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 9115 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 9116 RightMBB = FirstRight->MBB; 9117 } else { 9118 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 9119 FuncInfo.MF->insert(BBI, RightMBB); 9120 WorkList.push_back( 9121 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 9122 // Put Cond in a virtual register to make it available from the new blocks. 9123 ExportFromCurrentBlock(Cond); 9124 } 9125 9126 // Create the CaseBlock record that will be used to lower the branch. 9127 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 9128 LeftProb, RightProb); 9129 9130 if (W.MBB == SwitchMBB) 9131 visitSwitchCase(CB, SwitchMBB); 9132 else 9133 SwitchCases.push_back(CB); 9134 } 9135 9136 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 9137 // Extract cases from the switch. 9138 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9139 CaseClusterVector Clusters; 9140 Clusters.reserve(SI.getNumCases()); 9141 for (auto I : SI.cases()) { 9142 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 9143 const ConstantInt *CaseVal = I.getCaseValue(); 9144 BranchProbability Prob = 9145 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 9146 : BranchProbability(1, SI.getNumCases() + 1); 9147 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 9148 } 9149 9150 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 9151 9152 // Cluster adjacent cases with the same destination. We do this at all 9153 // optimization levels because it's cheap to do and will make codegen faster 9154 // if there are many clusters. 9155 sortAndRangeify(Clusters); 9156 9157 if (TM.getOptLevel() != CodeGenOpt::None) { 9158 // Replace an unreachable default with the most popular destination. 9159 // FIXME: Exploit unreachable default more aggressively. 9160 bool UnreachableDefault = 9161 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 9162 if (UnreachableDefault && !Clusters.empty()) { 9163 DenseMap<const BasicBlock *, unsigned> Popularity; 9164 unsigned MaxPop = 0; 9165 const BasicBlock *MaxBB = nullptr; 9166 for (auto I : SI.cases()) { 9167 const BasicBlock *BB = I.getCaseSuccessor(); 9168 if (++Popularity[BB] > MaxPop) { 9169 MaxPop = Popularity[BB]; 9170 MaxBB = BB; 9171 } 9172 } 9173 // Set new default. 9174 assert(MaxPop > 0 && MaxBB); 9175 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 9176 9177 // Remove cases that were pointing to the destination that is now the 9178 // default. 9179 CaseClusterVector New; 9180 New.reserve(Clusters.size()); 9181 for (CaseCluster &CC : Clusters) { 9182 if (CC.MBB != DefaultMBB) 9183 New.push_back(CC); 9184 } 9185 Clusters = std::move(New); 9186 } 9187 } 9188 9189 // If there is only the default destination, jump there directly. 9190 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 9191 if (Clusters.empty()) { 9192 SwitchMBB->addSuccessor(DefaultMBB); 9193 if (DefaultMBB != NextBlock(SwitchMBB)) { 9194 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 9195 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 9196 } 9197 return; 9198 } 9199 9200 findJumpTables(Clusters, &SI, DefaultMBB); 9201 findBitTestClusters(Clusters, &SI); 9202 9203 DEBUG({ 9204 dbgs() << "Case clusters: "; 9205 for (const CaseCluster &C : Clusters) { 9206 if (C.Kind == CC_JumpTable) dbgs() << "JT:"; 9207 if (C.Kind == CC_BitTests) dbgs() << "BT:"; 9208 9209 C.Low->getValue().print(dbgs(), true); 9210 if (C.Low != C.High) { 9211 dbgs() << '-'; 9212 C.High->getValue().print(dbgs(), true); 9213 } 9214 dbgs() << ' '; 9215 } 9216 dbgs() << '\n'; 9217 }); 9218 9219 assert(!Clusters.empty()); 9220 SwitchWorkList WorkList; 9221 CaseClusterIt First = Clusters.begin(); 9222 CaseClusterIt Last = Clusters.end() - 1; 9223 auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB); 9224 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 9225 9226 while (!WorkList.empty()) { 9227 SwitchWorkListItem W = WorkList.back(); 9228 WorkList.pop_back(); 9229 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 9230 9231 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) { 9232 // For optimized builds, lower large range as a balanced binary tree. 9233 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 9234 continue; 9235 } 9236 9237 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 9238 } 9239 } 9240