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