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