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