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