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