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