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