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