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