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