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