1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements routines for translating from LLVM IR into SelectionDAG IR. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SelectionDAGBuilder.h" 15 #include "SDNodeDbgValue.h" 16 #include "llvm/ADT/APFloat.h" 17 #include "llvm/ADT/APInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/None.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/Analysis/AliasAnalysis.h" 31 #include "llvm/Analysis/BranchProbabilityInfo.h" 32 #include "llvm/Analysis/ConstantFolding.h" 33 #include "llvm/Analysis/EHPersonalities.h" 34 #include "llvm/Analysis/Loads.h" 35 #include "llvm/Analysis/MemoryLocation.h" 36 #include "llvm/Analysis/TargetLibraryInfo.h" 37 #include "llvm/Analysis/ValueTracking.h" 38 #include "llvm/Analysis/VectorUtils.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/FunctionLoweringInfo.h" 41 #include "llvm/CodeGen/GCMetadata.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineJumpTableInfo.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/MachineValueType.h" 54 #include "llvm/CodeGen/RuntimeLibcalls.h" 55 #include "llvm/CodeGen/SelectionDAG.h" 56 #include "llvm/CodeGen/SelectionDAGNodes.h" 57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 58 #include "llvm/CodeGen/StackMaps.h" 59 #include "llvm/CodeGen/TargetFrameLowering.h" 60 #include "llvm/CodeGen/TargetInstrInfo.h" 61 #include "llvm/CodeGen/TargetLowering.h" 62 #include "llvm/CodeGen/TargetOpcodes.h" 63 #include "llvm/CodeGen/TargetRegisterInfo.h" 64 #include "llvm/CodeGen/TargetSubtargetInfo.h" 65 #include "llvm/CodeGen/ValueTypes.h" 66 #include "llvm/CodeGen/WinEHFuncInfo.h" 67 #include "llvm/IR/Argument.h" 68 #include "llvm/IR/Attributes.h" 69 #include "llvm/IR/BasicBlock.h" 70 #include "llvm/IR/CFG.h" 71 #include "llvm/IR/CallSite.h" 72 #include "llvm/IR/CallingConv.h" 73 #include "llvm/IR/Constant.h" 74 #include "llvm/IR/ConstantRange.h" 75 #include "llvm/IR/Constants.h" 76 #include "llvm/IR/DataLayout.h" 77 #include "llvm/IR/DebugInfoMetadata.h" 78 #include "llvm/IR/DebugLoc.h" 79 #include "llvm/IR/DerivedTypes.h" 80 #include "llvm/IR/Function.h" 81 #include "llvm/IR/GetElementPtrTypeIterator.h" 82 #include "llvm/IR/InlineAsm.h" 83 #include "llvm/IR/InstrTypes.h" 84 #include "llvm/IR/Instruction.h" 85 #include "llvm/IR/Instructions.h" 86 #include "llvm/IR/IntrinsicInst.h" 87 #include "llvm/IR/Intrinsics.h" 88 #include "llvm/IR/LLVMContext.h" 89 #include "llvm/IR/Metadata.h" 90 #include "llvm/IR/Module.h" 91 #include "llvm/IR/Operator.h" 92 #include "llvm/IR/Statepoint.h" 93 #include "llvm/IR/Type.h" 94 #include "llvm/IR/User.h" 95 #include "llvm/IR/Value.h" 96 #include "llvm/MC/MCContext.h" 97 #include "llvm/MC/MCSymbol.h" 98 #include "llvm/Support/AtomicOrdering.h" 99 #include "llvm/Support/BranchProbability.h" 100 #include "llvm/Support/Casting.h" 101 #include "llvm/Support/CodeGen.h" 102 #include "llvm/Support/CommandLine.h" 103 #include "llvm/Support/Compiler.h" 104 #include "llvm/Support/Debug.h" 105 #include "llvm/Support/ErrorHandling.h" 106 #include "llvm/Support/MathExtras.h" 107 #include "llvm/Support/raw_ostream.h" 108 #include "llvm/Target/TargetIntrinsicInfo.h" 109 #include "llvm/Target/TargetMachine.h" 110 #include "llvm/Target/TargetOptions.h" 111 #include <algorithm> 112 #include <cassert> 113 #include <cstddef> 114 #include <cstdint> 115 #include <cstring> 116 #include <iterator> 117 #include <limits> 118 #include <numeric> 119 #include <tuple> 120 #include <utility> 121 #include <vector> 122 123 using namespace llvm; 124 125 #define DEBUG_TYPE "isel" 126 127 /// LimitFloatPrecision - Generate low-precision inline sequences for 128 /// some float libcalls (6, 8 or 12 bits). 129 static unsigned LimitFloatPrecision; 130 131 static cl::opt<unsigned, true> 132 LimitFPPrecision("limit-float-precision", 133 cl::desc("Generate low-precision inline sequences " 134 "for some float libcalls"), 135 cl::location(LimitFloatPrecision), cl::Hidden, 136 cl::init(0)); 137 138 static cl::opt<unsigned> SwitchPeelThreshold( 139 "switch-peel-threshold", cl::Hidden, cl::init(66), 140 cl::desc("Set the case probability threshold for peeling the case from a " 141 "switch statement. A value greater than 100 will void this " 142 "optimization")); 143 144 // Limit the width of DAG chains. This is important in general to prevent 145 // DAG-based analysis from blowing up. For example, alias analysis and 146 // load clustering may not complete in reasonable time. It is difficult to 147 // recognize and avoid this situation within each individual analysis, and 148 // future analyses are likely to have the same behavior. Limiting DAG width is 149 // the safe approach and will be especially important with global DAGs. 150 // 151 // MaxParallelChains default is arbitrarily high to avoid affecting 152 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 153 // sequence over this should have been converted to llvm.memcpy by the 154 // frontend. It is easy to induce this behavior with .ll code such as: 155 // %buffer = alloca [4096 x i8] 156 // %data = load [4096 x i8]* %argPtr 157 // store [4096 x i8] %data, [4096 x i8]* %buffer 158 static const unsigned MaxParallelChains = 64; 159 160 // True if the Value passed requires ABI mangling as it is a parameter to a 161 // function or a return value from a function which is not an intrinsic. 162 static bool isABIRegCopy(const Value *V) { 163 const bool IsRetInst = V && isa<ReturnInst>(V); 164 const bool IsCallInst = V && isa<CallInst>(V); 165 const bool IsInLineAsm = 166 IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm(); 167 const bool IsIndirectFunctionCall = 168 IsCallInst && !IsInLineAsm && 169 !static_cast<const CallInst *>(V)->getCalledFunction(); 170 // It is possible that the call instruction is an inline asm statement or an 171 // indirect function call in which case the return value of 172 // getCalledFunction() would be nullptr. 173 const bool IsInstrinsicCall = 174 IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall && 175 static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() != 176 Intrinsic::not_intrinsic; 177 178 return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall)); 179 } 180 181 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 182 const SDValue *Parts, unsigned NumParts, 183 MVT PartVT, EVT ValueVT, const Value *V, 184 bool IsABIRegCopy); 185 186 /// getCopyFromParts - Create a value that contains the specified legal parts 187 /// combined into the value they represent. If the parts combine to a type 188 /// larger than ValueVT then AssertOp can be used to specify whether the extra 189 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 190 /// (ISD::AssertSext). 191 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 192 const SDValue *Parts, unsigned NumParts, 193 MVT PartVT, EVT ValueVT, const Value *V, 194 Optional<ISD::NodeType> AssertOp = None, 195 bool IsABIRegCopy = false) { 196 if (ValueVT.isVector()) 197 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, 198 PartVT, ValueVT, V, IsABIRegCopy); 199 200 assert(NumParts > 0 && "No parts to assemble!"); 201 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 202 SDValue Val = Parts[0]; 203 204 if (NumParts > 1) { 205 // Assemble the value from multiple parts. 206 if (ValueVT.isInteger()) { 207 unsigned PartBits = PartVT.getSizeInBits(); 208 unsigned ValueBits = ValueVT.getSizeInBits(); 209 210 // Assemble the power of 2 part. 211 unsigned RoundParts = NumParts & (NumParts - 1) ? 212 1 << Log2_32(NumParts) : NumParts; 213 unsigned RoundBits = PartBits * RoundParts; 214 EVT RoundVT = RoundBits == ValueBits ? 215 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 216 SDValue Lo, Hi; 217 218 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 219 220 if (RoundParts > 2) { 221 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 222 PartVT, HalfVT, V); 223 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 224 RoundParts / 2, PartVT, HalfVT, V); 225 } else { 226 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 227 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 228 } 229 230 if (DAG.getDataLayout().isBigEndian()) 231 std::swap(Lo, Hi); 232 233 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 234 235 if (RoundParts < NumParts) { 236 // Assemble the trailing non-power-of-2 part. 237 unsigned OddParts = NumParts - RoundParts; 238 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 239 Hi = getCopyFromParts(DAG, DL, 240 Parts + RoundParts, OddParts, PartVT, OddVT, V); 241 242 // Combine the round and odd parts. 243 Lo = Val; 244 if (DAG.getDataLayout().isBigEndian()) 245 std::swap(Lo, Hi); 246 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 247 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 248 Hi = 249 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 250 DAG.getConstant(Lo.getValueSizeInBits(), DL, 251 TLI.getPointerTy(DAG.getDataLayout()))); 252 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 253 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 254 } 255 } else if (PartVT.isFloatingPoint()) { 256 // FP split into multiple FP parts (for ppcf128) 257 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 258 "Unexpected split"); 259 SDValue Lo, Hi; 260 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 261 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 262 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 263 std::swap(Lo, Hi); 264 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 265 } else { 266 // FP split into integer parts (soft fp) 267 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 268 !PartVT.isVector() && "Unexpected split"); 269 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 270 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V); 271 } 272 } 273 274 // There is now one part, held in Val. Correct it to match ValueVT. 275 // PartEVT is the type of the register class that holds the value. 276 // ValueVT is the type of the inline asm operation. 277 EVT PartEVT = Val.getValueType(); 278 279 if (PartEVT == ValueVT) 280 return Val; 281 282 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 283 ValueVT.bitsLT(PartEVT)) { 284 // For an FP value in an integer part, we need to truncate to the right 285 // width first. 286 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 287 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 288 } 289 290 // Handle types that have the same size. 291 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 292 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 293 294 // Handle types with different sizes. 295 if (PartEVT.isInteger() && ValueVT.isInteger()) { 296 if (ValueVT.bitsLT(PartEVT)) { 297 // For a truncate, see if we have any information to 298 // indicate whether the truncated bits will always be 299 // zero or sign-extension. 300 if (AssertOp.hasValue()) 301 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 302 DAG.getValueType(ValueVT)); 303 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 304 } 305 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 306 } 307 308 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 309 // FP_ROUND's are always exact here. 310 if (ValueVT.bitsLT(Val.getValueType())) 311 return DAG.getNode( 312 ISD::FP_ROUND, DL, ValueVT, Val, 313 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 314 315 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 316 } 317 318 llvm_unreachable("Unknown mismatch!"); 319 } 320 321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 322 const Twine &ErrMsg) { 323 const Instruction *I = dyn_cast_or_null<Instruction>(V); 324 if (!V) 325 return Ctx.emitError(ErrMsg); 326 327 const char *AsmError = ", possible invalid constraint for vector type"; 328 if (const CallInst *CI = dyn_cast<CallInst>(I)) 329 if (isa<InlineAsm>(CI->getCalledValue())) 330 return Ctx.emitError(I, ErrMsg + AsmError); 331 332 return Ctx.emitError(I, ErrMsg); 333 } 334 335 /// getCopyFromPartsVector - Create a value that contains the specified legal 336 /// parts combined into the value they represent. If the parts combine to a 337 /// type larger than ValueVT then AssertOp can be used to specify whether the 338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 339 /// ValueVT (ISD::AssertSext). 340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 341 const SDValue *Parts, unsigned NumParts, 342 MVT PartVT, EVT ValueVT, const Value *V, 343 bool IsABIRegCopy) { 344 assert(ValueVT.isVector() && "Not a vector value"); 345 assert(NumParts > 0 && "No parts to assemble!"); 346 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 347 SDValue Val = Parts[0]; 348 349 // Handle a multi-element vector. 350 if (NumParts > 1) { 351 EVT IntermediateVT; 352 MVT RegisterVT; 353 unsigned NumIntermediates; 354 unsigned NumRegs; 355 356 if (IsABIRegCopy) { 357 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 358 *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates, 359 RegisterVT); 360 } else { 361 NumRegs = 362 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 363 NumIntermediates, RegisterVT); 364 } 365 366 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 367 NumParts = NumRegs; // Silence a compiler warning. 368 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 369 assert(RegisterVT.getSizeInBits() == 370 Parts[0].getSimpleValueType().getSizeInBits() && 371 "Part type sizes don't match!"); 372 373 // Assemble the parts into intermediate operands. 374 SmallVector<SDValue, 8> Ops(NumIntermediates); 375 if (NumIntermediates == NumParts) { 376 // If the register was not expanded, truncate or copy the value, 377 // as appropriate. 378 for (unsigned i = 0; i != NumParts; ++i) 379 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 380 PartVT, IntermediateVT, V); 381 } else if (NumParts > 0) { 382 // If the intermediate type was expanded, build the intermediate 383 // operands from the parts. 384 assert(NumParts % NumIntermediates == 0 && 385 "Must expand into a divisible number of parts!"); 386 unsigned Factor = NumParts / NumIntermediates; 387 for (unsigned i = 0; i != NumIntermediates; ++i) 388 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 389 PartVT, IntermediateVT, V); 390 } 391 392 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 393 // intermediate operands. 394 EVT BuiltVectorTy = 395 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 396 (IntermediateVT.isVector() 397 ? IntermediateVT.getVectorNumElements() * NumParts 398 : NumIntermediates)); 399 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 400 : ISD::BUILD_VECTOR, 401 DL, BuiltVectorTy, Ops); 402 } 403 404 // There is now one part, held in Val. Correct it to match ValueVT. 405 EVT PartEVT = Val.getValueType(); 406 407 if (PartEVT == ValueVT) 408 return Val; 409 410 if (PartEVT.isVector()) { 411 // If the element type of the source/dest vectors are the same, but the 412 // parts vector has more elements than the value vector, then we have a 413 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 414 // elements we want. 415 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 416 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 417 "Cannot narrow, it would be a lossy transformation"); 418 return DAG.getNode( 419 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 420 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 421 } 422 423 // Vector/Vector bitcast. 424 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 425 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 426 427 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 428 "Cannot handle this kind of promotion"); 429 // Promoted vector extract 430 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 431 432 } 433 434 // Trivial bitcast if the types are the same size and the destination 435 // vector type is legal. 436 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 437 TLI.isTypeLegal(ValueVT)) 438 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 439 440 if (ValueVT.getVectorNumElements() != 1) { 441 // Certain ABIs require that vectors are passed as integers. For vectors 442 // are the same size, this is an obvious bitcast. 443 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 444 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 445 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 446 // Bitcast Val back the original type and extract the corresponding 447 // vector we want. 448 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 449 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 450 ValueVT.getVectorElementType(), Elts); 451 Val = DAG.getBitcast(WiderVecType, Val); 452 return DAG.getNode( 453 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 454 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 455 } 456 457 diagnosePossiblyInvalidConstraint( 458 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 459 return DAG.getUNDEF(ValueVT); 460 } 461 462 // Handle cases such as i8 -> <1 x i1> 463 EVT ValueSVT = ValueVT.getVectorElementType(); 464 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 465 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 466 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 467 468 return DAG.getBuildVector(ValueVT, DL, Val); 469 } 470 471 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 472 SDValue Val, SDValue *Parts, unsigned NumParts, 473 MVT PartVT, const Value *V, bool IsABIRegCopy); 474 475 /// getCopyToParts - Create a series of nodes that contain the specified value 476 /// split into legal parts. If the parts contain more bits than Val, then, for 477 /// integers, ExtendKind can be used to specify how to generate the extra bits. 478 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 479 SDValue *Parts, unsigned NumParts, MVT PartVT, 480 const Value *V, 481 ISD::NodeType ExtendKind = ISD::ANY_EXTEND, 482 bool IsABIRegCopy = false) { 483 EVT ValueVT = Val.getValueType(); 484 485 // Handle the vector case separately. 486 if (ValueVT.isVector()) 487 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 488 IsABIRegCopy); 489 490 unsigned PartBits = PartVT.getSizeInBits(); 491 unsigned OrigNumParts = NumParts; 492 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 493 "Copying to an illegal type!"); 494 495 if (NumParts == 0) 496 return; 497 498 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 499 EVT PartEVT = PartVT; 500 if (PartEVT == ValueVT) { 501 assert(NumParts == 1 && "No-op copy with multiple parts!"); 502 Parts[0] = Val; 503 return; 504 } 505 506 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 507 // If the parts cover more bits than the value has, promote the value. 508 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 509 assert(NumParts == 1 && "Do not know what to promote to!"); 510 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 511 } else { 512 if (ValueVT.isFloatingPoint()) { 513 // FP values need to be bitcast, then extended if they are being put 514 // into a larger container. 515 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 516 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 517 } 518 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 519 ValueVT.isInteger() && 520 "Unknown mismatch!"); 521 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 522 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 523 if (PartVT == MVT::x86mmx) 524 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 525 } 526 } else if (PartBits == ValueVT.getSizeInBits()) { 527 // Different types of the same size. 528 assert(NumParts == 1 && PartEVT != ValueVT); 529 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 530 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 531 // If the parts cover less bits than value has, truncate the value. 532 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 533 ValueVT.isInteger() && 534 "Unknown mismatch!"); 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 536 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 537 if (PartVT == MVT::x86mmx) 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } 540 541 // The value may have changed - recompute ValueVT. 542 ValueVT = Val.getValueType(); 543 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 544 "Failed to tile the value with PartVT!"); 545 546 if (NumParts == 1) { 547 if (PartEVT != ValueVT) { 548 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 549 "scalar-to-vector conversion failed"); 550 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 551 } 552 553 Parts[0] = Val; 554 return; 555 } 556 557 // Expand the value into multiple parts. 558 if (NumParts & (NumParts - 1)) { 559 // The number of parts is not a power of 2. Split off and copy the tail. 560 assert(PartVT.isInteger() && ValueVT.isInteger() && 561 "Do not know what to expand to!"); 562 unsigned RoundParts = 1 << Log2_32(NumParts); 563 unsigned RoundBits = RoundParts * PartBits; 564 unsigned OddParts = NumParts - RoundParts; 565 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 566 DAG.getIntPtrConstant(RoundBits, DL)); 567 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V); 568 569 if (DAG.getDataLayout().isBigEndian()) 570 // The odd parts were reversed by getCopyToParts - unreverse them. 571 std::reverse(Parts + RoundParts, Parts + NumParts); 572 573 NumParts = RoundParts; 574 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 575 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 576 } 577 578 // The number of parts is a power of 2. Repeatedly bisect the value using 579 // EXTRACT_ELEMENT. 580 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 581 EVT::getIntegerVT(*DAG.getContext(), 582 ValueVT.getSizeInBits()), 583 Val); 584 585 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 586 for (unsigned i = 0; i < NumParts; i += StepSize) { 587 unsigned ThisBits = StepSize * PartBits / 2; 588 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 589 SDValue &Part0 = Parts[i]; 590 SDValue &Part1 = Parts[i+StepSize/2]; 591 592 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 593 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 594 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 595 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 596 597 if (ThisBits == PartBits && ThisVT != PartVT) { 598 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 599 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 600 } 601 } 602 } 603 604 if (DAG.getDataLayout().isBigEndian()) 605 std::reverse(Parts, Parts + OrigNumParts); 606 } 607 608 609 /// getCopyToPartsVector - Create a series of nodes that contain the specified 610 /// value split into legal parts. 611 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 612 SDValue Val, SDValue *Parts, unsigned NumParts, 613 MVT PartVT, const Value *V, 614 bool IsABIRegCopy) { 615 EVT ValueVT = Val.getValueType(); 616 assert(ValueVT.isVector() && "Not a vector"); 617 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 618 619 if (NumParts == 1) { 620 EVT PartEVT = PartVT; 621 if (PartEVT == ValueVT) { 622 // Nothing to do. 623 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 624 // Bitconvert vector->vector case. 625 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 626 } else if (PartVT.isVector() && 627 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() && 628 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { 629 EVT ElementVT = PartVT.getVectorElementType(); 630 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 631 // undef elements. 632 SmallVector<SDValue, 16> Ops; 633 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) 634 Ops.push_back(DAG.getNode( 635 ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val, 636 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())))); 637 638 for (unsigned i = ValueVT.getVectorNumElements(), 639 e = PartVT.getVectorNumElements(); i != e; ++i) 640 Ops.push_back(DAG.getUNDEF(ElementVT)); 641 642 Val = DAG.getBuildVector(PartVT, DL, Ops); 643 644 // FIXME: Use CONCAT for 2x -> 4x. 645 646 //SDValue UndefElts = DAG.getUNDEF(VectorTy); 647 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); 648 } else if (PartVT.isVector() && 649 PartEVT.getVectorElementType().bitsGE( 650 ValueVT.getVectorElementType()) && 651 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 652 653 // Promoted vector extract 654 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 655 } else { 656 if (ValueVT.getVectorNumElements() == 1) { 657 Val = DAG.getNode( 658 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 659 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 660 } else { 661 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 662 "lossy conversion of vector to scalar type"); 663 EVT IntermediateType = 664 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 665 Val = DAG.getBitcast(IntermediateType, Val); 666 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 667 } 668 } 669 670 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 671 Parts[0] = Val; 672 return; 673 } 674 675 // Handle a multi-element vector. 676 EVT IntermediateVT; 677 MVT RegisterVT; 678 unsigned NumIntermediates; 679 unsigned NumRegs; 680 if (IsABIRegCopy) { 681 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 682 *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates, 683 RegisterVT); 684 } else { 685 NumRegs = 686 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 687 NumIntermediates, RegisterVT); 688 } 689 unsigned NumElements = ValueVT.getVectorNumElements(); 690 691 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 692 NumParts = NumRegs; // Silence a compiler warning. 693 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 694 695 // Convert the vector to the appropiate type if necessary. 696 unsigned DestVectorNoElts = 697 NumIntermediates * 698 (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1); 699 EVT BuiltVectorTy = EVT::getVectorVT( 700 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 701 if (Val.getValueType() != BuiltVectorTy) 702 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 703 704 // Split the vector into intermediate operands. 705 SmallVector<SDValue, 8> Ops(NumIntermediates); 706 for (unsigned i = 0; i != NumIntermediates; ++i) { 707 if (IntermediateVT.isVector()) 708 Ops[i] = 709 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 710 DAG.getConstant(i * (NumElements / NumIntermediates), DL, 711 TLI.getVectorIdxTy(DAG.getDataLayout()))); 712 else 713 Ops[i] = DAG.getNode( 714 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 715 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 716 } 717 718 // Split the intermediate operands into legal parts. 719 if (NumParts == NumIntermediates) { 720 // If the register was not expanded, promote or copy the value, 721 // as appropriate. 722 for (unsigned i = 0; i != NumParts; ++i) 723 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V); 724 } else if (NumParts > 0) { 725 // If the intermediate type was expanded, split each the value into 726 // legal parts. 727 assert(NumIntermediates != 0 && "division by zero"); 728 assert(NumParts % NumIntermediates == 0 && 729 "Must expand into a divisible number of parts!"); 730 unsigned Factor = NumParts / NumIntermediates; 731 for (unsigned i = 0; i != NumIntermediates; ++i) 732 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V); 733 } 734 } 735 736 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 737 EVT valuevt, bool IsABIMangledValue) 738 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 739 RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {} 740 741 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 742 const DataLayout &DL, unsigned Reg, Type *Ty, 743 bool IsABIMangledValue) { 744 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 745 746 IsABIMangled = IsABIMangledValue; 747 748 for (EVT ValueVT : ValueVTs) { 749 unsigned NumRegs = IsABIMangledValue 750 ? TLI.getNumRegistersForCallingConv(Context, ValueVT) 751 : TLI.getNumRegisters(Context, ValueVT); 752 MVT RegisterVT = IsABIMangledValue 753 ? TLI.getRegisterTypeForCallingConv(Context, ValueVT) 754 : TLI.getRegisterType(Context, ValueVT); 755 for (unsigned i = 0; i != NumRegs; ++i) 756 Regs.push_back(Reg + i); 757 RegVTs.push_back(RegisterVT); 758 RegCount.push_back(NumRegs); 759 Reg += NumRegs; 760 } 761 } 762 763 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 764 FunctionLoweringInfo &FuncInfo, 765 const SDLoc &dl, SDValue &Chain, 766 SDValue *Flag, const Value *V) const { 767 // A Value with type {} or [0 x %t] needs no registers. 768 if (ValueVTs.empty()) 769 return SDValue(); 770 771 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 772 773 // Assemble the legal parts into the final values. 774 SmallVector<SDValue, 4> Values(ValueVTs.size()); 775 SmallVector<SDValue, 8> Parts; 776 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 777 // Copy the legal parts from the registers. 778 EVT ValueVT = ValueVTs[Value]; 779 unsigned NumRegs = RegCount[Value]; 780 MVT RegisterVT = IsABIMangled 781 ? TLI.getRegisterTypeForCallingConv(RegVTs[Value]) 782 : RegVTs[Value]; 783 784 Parts.resize(NumRegs); 785 for (unsigned i = 0; i != NumRegs; ++i) { 786 SDValue P; 787 if (!Flag) { 788 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 789 } else { 790 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 791 *Flag = P.getValue(2); 792 } 793 794 Chain = P.getValue(1); 795 Parts[i] = P; 796 797 // If the source register was virtual and if we know something about it, 798 // add an assert node. 799 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 800 !RegisterVT.isInteger() || RegisterVT.isVector()) 801 continue; 802 803 const FunctionLoweringInfo::LiveOutInfo *LOI = 804 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 805 if (!LOI) 806 continue; 807 808 unsigned RegSize = RegisterVT.getSizeInBits(); 809 unsigned NumSignBits = LOI->NumSignBits; 810 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 811 812 if (NumZeroBits == RegSize) { 813 // The current value is a zero. 814 // Explicitly express that as it would be easier for 815 // optimizations to kick in. 816 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 817 continue; 818 } 819 820 // FIXME: We capture more information than the dag can represent. For 821 // now, just use the tightest assertzext/assertsext possible. 822 bool isSExt = true; 823 EVT FromVT(MVT::Other); 824 if (NumSignBits == RegSize) { 825 isSExt = true; // ASSERT SEXT 1 826 FromVT = MVT::i1; 827 } else if (NumZeroBits >= RegSize - 1) { 828 isSExt = false; // ASSERT ZEXT 1 829 FromVT = MVT::i1; 830 } else if (NumSignBits > RegSize - 8) { 831 isSExt = true; // ASSERT SEXT 8 832 FromVT = MVT::i8; 833 } else if (NumZeroBits >= RegSize - 8) { 834 isSExt = false; // ASSERT ZEXT 8 835 FromVT = MVT::i8; 836 } else if (NumSignBits > RegSize - 16) { 837 isSExt = true; // ASSERT SEXT 16 838 FromVT = MVT::i16; 839 } else if (NumZeroBits >= RegSize - 16) { 840 isSExt = false; // ASSERT ZEXT 16 841 FromVT = MVT::i16; 842 } else if (NumSignBits > RegSize - 32) { 843 isSExt = true; // ASSERT SEXT 32 844 FromVT = MVT::i32; 845 } else if (NumZeroBits >= RegSize - 32) { 846 isSExt = false; // ASSERT ZEXT 32 847 FromVT = MVT::i32; 848 } else { 849 continue; 850 } 851 // Add an assertion node. 852 assert(FromVT != MVT::Other); 853 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 854 RegisterVT, P, DAG.getValueType(FromVT)); 855 } 856 857 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 858 NumRegs, RegisterVT, ValueVT, V); 859 Part += NumRegs; 860 Parts.clear(); 861 } 862 863 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 864 } 865 866 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 867 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 868 const Value *V, 869 ISD::NodeType PreferredExtendType) const { 870 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 871 ISD::NodeType ExtendKind = PreferredExtendType; 872 873 // Get the list of the values's legal parts. 874 unsigned NumRegs = Regs.size(); 875 SmallVector<SDValue, 8> Parts(NumRegs); 876 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 877 unsigned NumParts = RegCount[Value]; 878 879 MVT RegisterVT = IsABIMangled 880 ? TLI.getRegisterTypeForCallingConv(RegVTs[Value]) 881 : RegVTs[Value]; 882 883 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 884 ExtendKind = ISD::ZERO_EXTEND; 885 886 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), 887 &Parts[Part], NumParts, RegisterVT, V, ExtendKind); 888 Part += NumParts; 889 } 890 891 // Copy the parts into the registers. 892 SmallVector<SDValue, 8> Chains(NumRegs); 893 for (unsigned i = 0; i != NumRegs; ++i) { 894 SDValue Part; 895 if (!Flag) { 896 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 897 } else { 898 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 899 *Flag = Part.getValue(1); 900 } 901 902 Chains[i] = Part.getValue(0); 903 } 904 905 if (NumRegs == 1 || Flag) 906 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 907 // flagged to it. That is the CopyToReg nodes and the user are considered 908 // a single scheduling unit. If we create a TokenFactor and return it as 909 // chain, then the TokenFactor is both a predecessor (operand) of the 910 // user as well as a successor (the TF operands are flagged to the user). 911 // c1, f1 = CopyToReg 912 // c2, f2 = CopyToReg 913 // c3 = TokenFactor c1, c2 914 // ... 915 // = op c3, ..., f2 916 Chain = Chains[NumRegs-1]; 917 else 918 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 919 } 920 921 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 922 unsigned MatchingIdx, const SDLoc &dl, 923 SelectionDAG &DAG, 924 std::vector<SDValue> &Ops) const { 925 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 926 927 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 928 if (HasMatching) 929 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 930 else if (!Regs.empty() && 931 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 932 // Put the register class of the virtual registers in the flag word. That 933 // way, later passes can recompute register class constraints for inline 934 // assembly as well as normal instructions. 935 // Don't do this for tied operands that can use the regclass information 936 // from the def. 937 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 938 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 939 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 940 } 941 942 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 943 Ops.push_back(Res); 944 945 if (Code == InlineAsm::Kind_Clobber) { 946 // Clobbers should always have a 1:1 mapping with registers, and may 947 // reference registers that have illegal (e.g. vector) types. Hence, we 948 // shouldn't try to apply any sort of splitting logic to them. 949 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 950 "No 1:1 mapping from clobbers to regs?"); 951 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 952 (void)SP; 953 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 954 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 955 assert( 956 (Regs[I] != SP || 957 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 958 "If we clobbered the stack pointer, MFI should know about it."); 959 } 960 return; 961 } 962 963 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 964 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 965 MVT RegisterVT = RegVTs[Value]; 966 for (unsigned i = 0; i != NumRegs; ++i) { 967 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 968 unsigned TheReg = Regs[Reg++]; 969 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 970 } 971 } 972 } 973 974 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 975 const TargetLibraryInfo *li) { 976 AA = aa; 977 GFI = gfi; 978 LibInfo = li; 979 DL = &DAG.getDataLayout(); 980 Context = DAG.getContext(); 981 LPadToCallSiteMap.clear(); 982 } 983 984 void SelectionDAGBuilder::clear() { 985 NodeMap.clear(); 986 UnusedArgNodeMap.clear(); 987 PendingLoads.clear(); 988 PendingExports.clear(); 989 CurInst = nullptr; 990 HasTailCall = false; 991 SDNodeOrder = LowestSDNodeOrder; 992 StatepointLowering.clear(); 993 } 994 995 void SelectionDAGBuilder::clearDanglingDebugInfo() { 996 DanglingDebugInfoMap.clear(); 997 } 998 999 SDValue SelectionDAGBuilder::getRoot() { 1000 if (PendingLoads.empty()) 1001 return DAG.getRoot(); 1002 1003 if (PendingLoads.size() == 1) { 1004 SDValue Root = PendingLoads[0]; 1005 DAG.setRoot(Root); 1006 PendingLoads.clear(); 1007 return Root; 1008 } 1009 1010 // Otherwise, we have to make a token factor node. 1011 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1012 PendingLoads); 1013 PendingLoads.clear(); 1014 DAG.setRoot(Root); 1015 return Root; 1016 } 1017 1018 SDValue SelectionDAGBuilder::getControlRoot() { 1019 SDValue Root = DAG.getRoot(); 1020 1021 if (PendingExports.empty()) 1022 return Root; 1023 1024 // Turn all of the CopyToReg chains into one factored node. 1025 if (Root.getOpcode() != ISD::EntryToken) { 1026 unsigned i = 0, e = PendingExports.size(); 1027 for (; i != e; ++i) { 1028 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1029 if (PendingExports[i].getNode()->getOperand(0) == Root) 1030 break; // Don't add the root if we already indirectly depend on it. 1031 } 1032 1033 if (i == e) 1034 PendingExports.push_back(Root); 1035 } 1036 1037 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1038 PendingExports); 1039 PendingExports.clear(); 1040 DAG.setRoot(Root); 1041 return Root; 1042 } 1043 1044 void SelectionDAGBuilder::visit(const Instruction &I) { 1045 // Set up outgoing PHI node register values before emitting the terminator. 1046 if (isa<TerminatorInst>(&I)) { 1047 HandlePHINodesInSuccessorBlocks(I.getParent()); 1048 } 1049 1050 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1051 if (!isa<DbgInfoIntrinsic>(I)) 1052 ++SDNodeOrder; 1053 1054 CurInst = &I; 1055 1056 visit(I.getOpcode(), I); 1057 1058 if (!isa<TerminatorInst>(&I) && !HasTailCall && 1059 !isStatepoint(&I)) // statepoints handle their exports internally 1060 CopyToExportRegsIfNeeded(&I); 1061 1062 CurInst = nullptr; 1063 } 1064 1065 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1066 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1067 } 1068 1069 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1070 // Note: this doesn't use InstVisitor, because it has to work with 1071 // ConstantExpr's in addition to instructions. 1072 switch (Opcode) { 1073 default: llvm_unreachable("Unknown instruction type encountered!"); 1074 // Build the switch statement using the Instruction.def file. 1075 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1076 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1077 #include "llvm/IR/Instruction.def" 1078 } 1079 } 1080 1081 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1082 const DIExpression *Expr) { 1083 SmallVector<const Value *, 4> ToRemove; 1084 for (auto &DMI : DanglingDebugInfoMap) { 1085 DanglingDebugInfo &DDI = DMI.second; 1086 if (DDI.getDI()) { 1087 const DbgValueInst *DI = DDI.getDI(); 1088 DIVariable *DanglingVariable = DI->getVariable(); 1089 DIExpression *DanglingExpr = DI->getExpression(); 1090 if (DanglingVariable == Variable && 1091 Expr->fragmentsOverlap(DanglingExpr)) { 1092 DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1093 ToRemove.push_back(DMI.first); 1094 } 1095 } 1096 } 1097 1098 for (auto V : ToRemove) 1099 DanglingDebugInfoMap[V] = DanglingDebugInfo(); 1100 } 1101 1102 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1103 // generate the debug data structures now that we've seen its definition. 1104 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1105 SDValue Val) { 1106 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V]; 1107 if (!DDI.getDI()) 1108 return; 1109 const DbgValueInst *DI = DDI.getDI(); 1110 DebugLoc dl = DDI.getdl(); 1111 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1112 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1113 DILocalVariable *Variable = DI->getVariable(); 1114 DIExpression *Expr = DI->getExpression(); 1115 assert(Variable->isValidLocationForIntrinsic(dl) && 1116 "Expected inlined-at fields to agree"); 1117 SDDbgValue *SDV; 1118 if (Val.getNode()) { 1119 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1120 DEBUG(dbgs() << "Resolve dangling debug info [order=" << DbgSDNodeOrder 1121 << "] for:\n " << *DI << "\n"); 1122 DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1123 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1124 // inserted after the definition of Val when emitting the instructions 1125 // after ISel. An alternative could be to teach 1126 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1127 DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) 1128 dbgs() << "changing SDNodeOrder from " << DbgSDNodeOrder 1129 << " to " << ValSDNodeOrder << "\n"); 1130 SDV = getDbgValue(Val, Variable, Expr, dl, 1131 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1132 DAG.AddDbgValue(SDV, Val.getNode(), false); 1133 } else 1134 DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1135 << "in EmitFuncArgumentDbgValue\n"); 1136 } else 1137 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1138 DanglingDebugInfoMap[V] = DanglingDebugInfo(); 1139 } 1140 1141 /// getCopyFromRegs - If there was virtual register allocated for the value V 1142 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1143 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1144 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1145 SDValue Result; 1146 1147 if (It != FuncInfo.ValueMap.end()) { 1148 unsigned InReg = It->second; 1149 1150 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1151 DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V)); 1152 SDValue Chain = DAG.getEntryNode(); 1153 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1154 V); 1155 resolveDanglingDebugInfo(V, Result); 1156 } 1157 1158 return Result; 1159 } 1160 1161 /// getValue - Return an SDValue for the given Value. 1162 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1163 // If we already have an SDValue for this value, use it. It's important 1164 // to do this first, so that we don't create a CopyFromReg if we already 1165 // have a regular SDValue. 1166 SDValue &N = NodeMap[V]; 1167 if (N.getNode()) return N; 1168 1169 // If there's a virtual register allocated and initialized for this 1170 // value, use it. 1171 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1172 return copyFromReg; 1173 1174 // Otherwise create a new SDValue and remember it. 1175 SDValue Val = getValueImpl(V); 1176 NodeMap[V] = Val; 1177 resolveDanglingDebugInfo(V, Val); 1178 return Val; 1179 } 1180 1181 // Return true if SDValue exists for the given Value 1182 bool SelectionDAGBuilder::findValue(const Value *V) const { 1183 return (NodeMap.find(V) != NodeMap.end()) || 1184 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1185 } 1186 1187 /// getNonRegisterValue - Return an SDValue for the given Value, but 1188 /// don't look in FuncInfo.ValueMap for a virtual register. 1189 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1190 // If we already have an SDValue for this value, use it. 1191 SDValue &N = NodeMap[V]; 1192 if (N.getNode()) { 1193 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1194 // Remove the debug location from the node as the node is about to be used 1195 // in a location which may differ from the original debug location. This 1196 // is relevant to Constant and ConstantFP nodes because they can appear 1197 // as constant expressions inside PHI nodes. 1198 N->setDebugLoc(DebugLoc()); 1199 } 1200 return N; 1201 } 1202 1203 // Otherwise create a new SDValue and remember it. 1204 SDValue Val = getValueImpl(V); 1205 NodeMap[V] = Val; 1206 resolveDanglingDebugInfo(V, Val); 1207 return Val; 1208 } 1209 1210 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1211 /// Create an SDValue for the given value. 1212 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1213 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1214 1215 if (const Constant *C = dyn_cast<Constant>(V)) { 1216 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1217 1218 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1219 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1220 1221 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1222 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1223 1224 if (isa<ConstantPointerNull>(C)) { 1225 unsigned AS = V->getType()->getPointerAddressSpace(); 1226 return DAG.getConstant(0, getCurSDLoc(), 1227 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1228 } 1229 1230 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1231 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1232 1233 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1234 return DAG.getUNDEF(VT); 1235 1236 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1237 visit(CE->getOpcode(), *CE); 1238 SDValue N1 = NodeMap[V]; 1239 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1240 return N1; 1241 } 1242 1243 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1244 SmallVector<SDValue, 4> Constants; 1245 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1246 OI != OE; ++OI) { 1247 SDNode *Val = getValue(*OI).getNode(); 1248 // If the operand is an empty aggregate, there are no values. 1249 if (!Val) continue; 1250 // Add each leaf value from the operand to the Constants list 1251 // to form a flattened list of all the values. 1252 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1253 Constants.push_back(SDValue(Val, i)); 1254 } 1255 1256 return DAG.getMergeValues(Constants, getCurSDLoc()); 1257 } 1258 1259 if (const ConstantDataSequential *CDS = 1260 dyn_cast<ConstantDataSequential>(C)) { 1261 SmallVector<SDValue, 4> Ops; 1262 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1263 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1264 // Add each leaf value from the operand to the Constants list 1265 // to form a flattened list of all the values. 1266 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1267 Ops.push_back(SDValue(Val, i)); 1268 } 1269 1270 if (isa<ArrayType>(CDS->getType())) 1271 return DAG.getMergeValues(Ops, getCurSDLoc()); 1272 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1273 } 1274 1275 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1276 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1277 "Unknown struct or array constant!"); 1278 1279 SmallVector<EVT, 4> ValueVTs; 1280 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1281 unsigned NumElts = ValueVTs.size(); 1282 if (NumElts == 0) 1283 return SDValue(); // empty struct 1284 SmallVector<SDValue, 4> Constants(NumElts); 1285 for (unsigned i = 0; i != NumElts; ++i) { 1286 EVT EltVT = ValueVTs[i]; 1287 if (isa<UndefValue>(C)) 1288 Constants[i] = DAG.getUNDEF(EltVT); 1289 else if (EltVT.isFloatingPoint()) 1290 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1291 else 1292 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1293 } 1294 1295 return DAG.getMergeValues(Constants, getCurSDLoc()); 1296 } 1297 1298 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1299 return DAG.getBlockAddress(BA, VT); 1300 1301 VectorType *VecTy = cast<VectorType>(V->getType()); 1302 unsigned NumElements = VecTy->getNumElements(); 1303 1304 // Now that we know the number and type of the elements, get that number of 1305 // elements into the Ops array based on what kind of constant it is. 1306 SmallVector<SDValue, 16> Ops; 1307 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1308 for (unsigned i = 0; i != NumElements; ++i) 1309 Ops.push_back(getValue(CV->getOperand(i))); 1310 } else { 1311 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1312 EVT EltVT = 1313 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1314 1315 SDValue Op; 1316 if (EltVT.isFloatingPoint()) 1317 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1318 else 1319 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1320 Ops.assign(NumElements, Op); 1321 } 1322 1323 // Create a BUILD_VECTOR node. 1324 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1325 } 1326 1327 // If this is a static alloca, generate it as the frameindex instead of 1328 // computation. 1329 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1330 DenseMap<const AllocaInst*, int>::iterator SI = 1331 FuncInfo.StaticAllocaMap.find(AI); 1332 if (SI != FuncInfo.StaticAllocaMap.end()) 1333 return DAG.getFrameIndex(SI->second, 1334 TLI.getFrameIndexTy(DAG.getDataLayout())); 1335 } 1336 1337 // If this is an instruction which fast-isel has deferred, select it now. 1338 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1339 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1340 1341 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1342 Inst->getType(), isABIRegCopy(V)); 1343 SDValue Chain = DAG.getEntryNode(); 1344 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1345 } 1346 1347 llvm_unreachable("Can't get register for value!"); 1348 } 1349 1350 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1351 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1352 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1353 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1354 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1355 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1356 if (IsMSVCCXX || IsCoreCLR) 1357 CatchPadMBB->setIsEHFuncletEntry(); 1358 1359 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot())); 1360 } 1361 1362 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1363 // Update machine-CFG edge. 1364 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1365 FuncInfo.MBB->addSuccessor(TargetMBB); 1366 1367 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1368 bool IsSEH = isAsynchronousEHPersonality(Pers); 1369 if (IsSEH) { 1370 // If this is not a fall-through branch or optimizations are switched off, 1371 // emit the branch. 1372 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1373 TM.getOptLevel() == CodeGenOpt::None) 1374 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1375 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1376 return; 1377 } 1378 1379 // Figure out the funclet membership for the catchret's successor. 1380 // This will be used by the FuncletLayout pass to determine how to order the 1381 // BB's. 1382 // A 'catchret' returns to the outer scope's color. 1383 Value *ParentPad = I.getCatchSwitchParentPad(); 1384 const BasicBlock *SuccessorColor; 1385 if (isa<ConstantTokenNone>(ParentPad)) 1386 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1387 else 1388 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1389 assert(SuccessorColor && "No parent funclet for catchret!"); 1390 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1391 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1392 1393 // Create the terminator node. 1394 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1395 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1396 DAG.getBasicBlock(SuccessorColorMBB)); 1397 DAG.setRoot(Ret); 1398 } 1399 1400 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1401 // Don't emit any special code for the cleanuppad instruction. It just marks 1402 // the start of a funclet. 1403 FuncInfo.MBB->setIsEHFuncletEntry(); 1404 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1405 } 1406 1407 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1408 /// many places it could ultimately go. In the IR, we have a single unwind 1409 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1410 /// This function skips over imaginary basic blocks that hold catchswitch 1411 /// instructions, and finds all the "real" machine 1412 /// basic block destinations. As those destinations may not be successors of 1413 /// EHPadBB, here we also calculate the edge probability to those destinations. 1414 /// The passed-in Prob is the edge probability to EHPadBB. 1415 static void findUnwindDestinations( 1416 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1417 BranchProbability Prob, 1418 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1419 &UnwindDests) { 1420 EHPersonality Personality = 1421 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1422 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1423 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1424 1425 while (EHPadBB) { 1426 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1427 BasicBlock *NewEHPadBB = nullptr; 1428 if (isa<LandingPadInst>(Pad)) { 1429 // Stop on landingpads. They are not funclets. 1430 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1431 break; 1432 } else if (isa<CleanupPadInst>(Pad)) { 1433 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1434 // personalities. 1435 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1436 UnwindDests.back().first->setIsEHFuncletEntry(); 1437 break; 1438 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1439 // Add the catchpad handlers to the possible destinations. 1440 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1441 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1442 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1443 if (IsMSVCCXX || IsCoreCLR) 1444 UnwindDests.back().first->setIsEHFuncletEntry(); 1445 } 1446 NewEHPadBB = CatchSwitch->getUnwindDest(); 1447 } else { 1448 continue; 1449 } 1450 1451 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1452 if (BPI && NewEHPadBB) 1453 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1454 EHPadBB = NewEHPadBB; 1455 } 1456 } 1457 1458 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1459 // Update successor info. 1460 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1461 auto UnwindDest = I.getUnwindDest(); 1462 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1463 BranchProbability UnwindDestProb = 1464 (BPI && UnwindDest) 1465 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1466 : BranchProbability::getZero(); 1467 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1468 for (auto &UnwindDest : UnwindDests) { 1469 UnwindDest.first->setIsEHPad(); 1470 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1471 } 1472 FuncInfo.MBB->normalizeSuccProbs(); 1473 1474 // Create the terminator node. 1475 SDValue Ret = 1476 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1477 DAG.setRoot(Ret); 1478 } 1479 1480 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1481 report_fatal_error("visitCatchSwitch not yet implemented!"); 1482 } 1483 1484 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1485 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1486 auto &DL = DAG.getDataLayout(); 1487 SDValue Chain = getControlRoot(); 1488 SmallVector<ISD::OutputArg, 8> Outs; 1489 SmallVector<SDValue, 8> OutVals; 1490 1491 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1492 // lower 1493 // 1494 // %val = call <ty> @llvm.experimental.deoptimize() 1495 // ret <ty> %val 1496 // 1497 // differently. 1498 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1499 LowerDeoptimizingReturn(); 1500 return; 1501 } 1502 1503 if (!FuncInfo.CanLowerReturn) { 1504 unsigned DemoteReg = FuncInfo.DemoteRegister; 1505 const Function *F = I.getParent()->getParent(); 1506 1507 // Emit a store of the return value through the virtual register. 1508 // Leave Outs empty so that LowerReturn won't try to load return 1509 // registers the usual way. 1510 SmallVector<EVT, 1> PtrValueVTs; 1511 ComputeValueVTs(TLI, DL, 1512 F->getReturnType()->getPointerTo( 1513 DAG.getDataLayout().getAllocaAddrSpace()), 1514 PtrValueVTs); 1515 1516 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1517 DemoteReg, PtrValueVTs[0]); 1518 SDValue RetOp = getValue(I.getOperand(0)); 1519 1520 SmallVector<EVT, 4> ValueVTs; 1521 SmallVector<uint64_t, 4> Offsets; 1522 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1523 unsigned NumValues = ValueVTs.size(); 1524 1525 SmallVector<SDValue, 4> Chains(NumValues); 1526 for (unsigned i = 0; i != NumValues; ++i) { 1527 // An aggregate return value cannot wrap around the address space, so 1528 // offsets to its parts don't wrap either. 1529 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1530 Chains[i] = DAG.getStore( 1531 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1532 // FIXME: better loc info would be nice. 1533 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1534 } 1535 1536 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1537 MVT::Other, Chains); 1538 } else if (I.getNumOperands() != 0) { 1539 SmallVector<EVT, 4> ValueVTs; 1540 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1541 unsigned NumValues = ValueVTs.size(); 1542 if (NumValues) { 1543 SDValue RetOp = getValue(I.getOperand(0)); 1544 1545 const Function *F = I.getParent()->getParent(); 1546 1547 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1548 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1549 Attribute::SExt)) 1550 ExtendKind = ISD::SIGN_EXTEND; 1551 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1552 Attribute::ZExt)) 1553 ExtendKind = ISD::ZERO_EXTEND; 1554 1555 LLVMContext &Context = F->getContext(); 1556 bool RetInReg = F->getAttributes().hasAttribute( 1557 AttributeList::ReturnIndex, Attribute::InReg); 1558 1559 for (unsigned j = 0; j != NumValues; ++j) { 1560 EVT VT = ValueVTs[j]; 1561 1562 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1563 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1564 1565 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT); 1566 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT); 1567 SmallVector<SDValue, 4> Parts(NumParts); 1568 getCopyToParts(DAG, getCurSDLoc(), 1569 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1570 &Parts[0], NumParts, PartVT, &I, ExtendKind, true); 1571 1572 // 'inreg' on function refers to return value 1573 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1574 if (RetInReg) 1575 Flags.setInReg(); 1576 1577 // Propagate extension type if any 1578 if (ExtendKind == ISD::SIGN_EXTEND) 1579 Flags.setSExt(); 1580 else if (ExtendKind == ISD::ZERO_EXTEND) 1581 Flags.setZExt(); 1582 1583 for (unsigned i = 0; i < NumParts; ++i) { 1584 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1585 VT, /*isfixed=*/true, 0, 0)); 1586 OutVals.push_back(Parts[i]); 1587 } 1588 } 1589 } 1590 } 1591 1592 // Push in swifterror virtual register as the last element of Outs. This makes 1593 // sure swifterror virtual register will be returned in the swifterror 1594 // physical register. 1595 const Function *F = I.getParent()->getParent(); 1596 if (TLI.supportSwiftError() && 1597 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1598 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1599 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1600 Flags.setSwiftError(); 1601 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1602 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1603 true /*isfixed*/, 1 /*origidx*/, 1604 0 /*partOffs*/)); 1605 // Create SDNode for the swifterror virtual register. 1606 OutVals.push_back( 1607 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1608 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1609 EVT(TLI.getPointerTy(DL)))); 1610 } 1611 1612 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1613 CallingConv::ID CallConv = 1614 DAG.getMachineFunction().getFunction().getCallingConv(); 1615 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1616 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1617 1618 // Verify that the target's LowerReturn behaved as expected. 1619 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1620 "LowerReturn didn't return a valid chain!"); 1621 1622 // Update the DAG with the new chain value resulting from return lowering. 1623 DAG.setRoot(Chain); 1624 } 1625 1626 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1627 /// created for it, emit nodes to copy the value into the virtual 1628 /// registers. 1629 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1630 // Skip empty types 1631 if (V->getType()->isEmptyTy()) 1632 return; 1633 1634 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1635 if (VMI != FuncInfo.ValueMap.end()) { 1636 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1637 CopyValueToVirtualRegister(V, VMI->second); 1638 } 1639 } 1640 1641 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1642 /// the current basic block, add it to ValueMap now so that we'll get a 1643 /// CopyTo/FromReg. 1644 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1645 // No need to export constants. 1646 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1647 1648 // Already exported? 1649 if (FuncInfo.isExportedInst(V)) return; 1650 1651 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1652 CopyValueToVirtualRegister(V, Reg); 1653 } 1654 1655 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1656 const BasicBlock *FromBB) { 1657 // The operands of the setcc have to be in this block. We don't know 1658 // how to export them from some other block. 1659 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1660 // Can export from current BB. 1661 if (VI->getParent() == FromBB) 1662 return true; 1663 1664 // Is already exported, noop. 1665 return FuncInfo.isExportedInst(V); 1666 } 1667 1668 // If this is an argument, we can export it if the BB is the entry block or 1669 // if it is already exported. 1670 if (isa<Argument>(V)) { 1671 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1672 return true; 1673 1674 // Otherwise, can only export this if it is already exported. 1675 return FuncInfo.isExportedInst(V); 1676 } 1677 1678 // Otherwise, constants can always be exported. 1679 return true; 1680 } 1681 1682 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1683 BranchProbability 1684 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1685 const MachineBasicBlock *Dst) const { 1686 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1687 const BasicBlock *SrcBB = Src->getBasicBlock(); 1688 const BasicBlock *DstBB = Dst->getBasicBlock(); 1689 if (!BPI) { 1690 // If BPI is not available, set the default probability as 1 / N, where N is 1691 // the number of successors. 1692 auto SuccSize = std::max<uint32_t>( 1693 std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1); 1694 return BranchProbability(1, SuccSize); 1695 } 1696 return BPI->getEdgeProbability(SrcBB, DstBB); 1697 } 1698 1699 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1700 MachineBasicBlock *Dst, 1701 BranchProbability Prob) { 1702 if (!FuncInfo.BPI) 1703 Src->addSuccessorWithoutProb(Dst); 1704 else { 1705 if (Prob.isUnknown()) 1706 Prob = getEdgeProbability(Src, Dst); 1707 Src->addSuccessor(Dst, Prob); 1708 } 1709 } 1710 1711 static bool InBlock(const Value *V, const BasicBlock *BB) { 1712 if (const Instruction *I = dyn_cast<Instruction>(V)) 1713 return I->getParent() == BB; 1714 return true; 1715 } 1716 1717 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1718 /// This function emits a branch and is used at the leaves of an OR or an 1719 /// AND operator tree. 1720 void 1721 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1722 MachineBasicBlock *TBB, 1723 MachineBasicBlock *FBB, 1724 MachineBasicBlock *CurBB, 1725 MachineBasicBlock *SwitchBB, 1726 BranchProbability TProb, 1727 BranchProbability FProb, 1728 bool InvertCond) { 1729 const BasicBlock *BB = CurBB->getBasicBlock(); 1730 1731 // If the leaf of the tree is a comparison, merge the condition into 1732 // the caseblock. 1733 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1734 // The operands of the cmp have to be in this block. We don't know 1735 // how to export them from some other block. If this is the first block 1736 // of the sequence, no exporting is needed. 1737 if (CurBB == SwitchBB || 1738 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1739 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1740 ISD::CondCode Condition; 1741 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1742 ICmpInst::Predicate Pred = 1743 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 1744 Condition = getICmpCondCode(Pred); 1745 } else { 1746 const FCmpInst *FC = cast<FCmpInst>(Cond); 1747 FCmpInst::Predicate Pred = 1748 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 1749 Condition = getFCmpCondCode(Pred); 1750 if (TM.Options.NoNaNsFPMath) 1751 Condition = getFCmpCodeWithoutNaN(Condition); 1752 } 1753 1754 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1755 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1756 SwitchCases.push_back(CB); 1757 return; 1758 } 1759 } 1760 1761 // Create a CaseBlock record representing this branch. 1762 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 1763 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 1764 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1765 SwitchCases.push_back(CB); 1766 } 1767 1768 /// FindMergedConditions - If Cond is an expression like 1769 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1770 MachineBasicBlock *TBB, 1771 MachineBasicBlock *FBB, 1772 MachineBasicBlock *CurBB, 1773 MachineBasicBlock *SwitchBB, 1774 Instruction::BinaryOps Opc, 1775 BranchProbability TProb, 1776 BranchProbability FProb, 1777 bool InvertCond) { 1778 // Skip over not part of the tree and remember to invert op and operands at 1779 // next level. 1780 if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) { 1781 const Value *CondOp = BinaryOperator::getNotArgument(Cond); 1782 if (InBlock(CondOp, CurBB->getBasicBlock())) { 1783 FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 1784 !InvertCond); 1785 return; 1786 } 1787 } 1788 1789 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1790 // Compute the effective opcode for Cond, taking into account whether it needs 1791 // to be inverted, e.g. 1792 // and (not (or A, B)), C 1793 // gets lowered as 1794 // and (and (not A, not B), C) 1795 unsigned BOpc = 0; 1796 if (BOp) { 1797 BOpc = BOp->getOpcode(); 1798 if (InvertCond) { 1799 if (BOpc == Instruction::And) 1800 BOpc = Instruction::Or; 1801 else if (BOpc == Instruction::Or) 1802 BOpc = Instruction::And; 1803 } 1804 } 1805 1806 // If this node is not part of the or/and tree, emit it as a branch. 1807 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1808 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 1809 BOp->getParent() != CurBB->getBasicBlock() || 1810 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1811 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1812 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1813 TProb, FProb, InvertCond); 1814 return; 1815 } 1816 1817 // Create TmpBB after CurBB. 1818 MachineFunction::iterator BBI(CurBB); 1819 MachineFunction &MF = DAG.getMachineFunction(); 1820 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1821 CurBB->getParent()->insert(++BBI, TmpBB); 1822 1823 if (Opc == Instruction::Or) { 1824 // Codegen X | Y as: 1825 // BB1: 1826 // jmp_if_X TBB 1827 // jmp TmpBB 1828 // TmpBB: 1829 // jmp_if_Y TBB 1830 // jmp FBB 1831 // 1832 1833 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1834 // The requirement is that 1835 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1836 // = TrueProb for original BB. 1837 // Assuming the original probabilities are A and B, one choice is to set 1838 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1839 // A/(1+B) and 2B/(1+B). This choice assumes that 1840 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1841 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1842 // TmpBB, but the math is more complicated. 1843 1844 auto NewTrueProb = TProb / 2; 1845 auto NewFalseProb = TProb / 2 + FProb; 1846 // Emit the LHS condition. 1847 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1848 NewTrueProb, NewFalseProb, InvertCond); 1849 1850 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1851 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 1852 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1853 // Emit the RHS condition into TmpBB. 1854 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1855 Probs[0], Probs[1], InvertCond); 1856 } else { 1857 assert(Opc == Instruction::And && "Unknown merge op!"); 1858 // Codegen X & Y as: 1859 // BB1: 1860 // jmp_if_X TmpBB 1861 // jmp FBB 1862 // TmpBB: 1863 // jmp_if_Y TBB 1864 // jmp FBB 1865 // 1866 // This requires creation of TmpBB after CurBB. 1867 1868 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1869 // The requirement is that 1870 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1871 // = FalseProb for original BB. 1872 // Assuming the original probabilities are A and B, one choice is to set 1873 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1874 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1875 // TrueProb for BB1 * FalseProb for TmpBB. 1876 1877 auto NewTrueProb = TProb + FProb / 2; 1878 auto NewFalseProb = FProb / 2; 1879 // Emit the LHS condition. 1880 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1881 NewTrueProb, NewFalseProb, InvertCond); 1882 1883 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1884 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 1885 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1886 // Emit the RHS condition into TmpBB. 1887 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1888 Probs[0], Probs[1], InvertCond); 1889 } 1890 } 1891 1892 /// If the set of cases should be emitted as a series of branches, return true. 1893 /// If we should emit this as a bunch of and/or'd together conditions, return 1894 /// false. 1895 bool 1896 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1897 if (Cases.size() != 2) return true; 1898 1899 // If this is two comparisons of the same values or'd or and'd together, they 1900 // will get folded into a single comparison, so don't emit two blocks. 1901 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1902 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1903 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1904 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1905 return false; 1906 } 1907 1908 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1909 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1910 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1911 Cases[0].CC == Cases[1].CC && 1912 isa<Constant>(Cases[0].CmpRHS) && 1913 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1914 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1915 return false; 1916 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1917 return false; 1918 } 1919 1920 return true; 1921 } 1922 1923 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1924 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1925 1926 // Update machine-CFG edges. 1927 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1928 1929 if (I.isUnconditional()) { 1930 // Update machine-CFG edges. 1931 BrMBB->addSuccessor(Succ0MBB); 1932 1933 // If this is not a fall-through branch or optimizations are switched off, 1934 // emit the branch. 1935 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1936 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1937 MVT::Other, getControlRoot(), 1938 DAG.getBasicBlock(Succ0MBB))); 1939 1940 return; 1941 } 1942 1943 // If this condition is one of the special cases we handle, do special stuff 1944 // now. 1945 const Value *CondVal = I.getCondition(); 1946 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1947 1948 // If this is a series of conditions that are or'd or and'd together, emit 1949 // this as a sequence of branches instead of setcc's with and/or operations. 1950 // As long as jumps are not expensive, this should improve performance. 1951 // For example, instead of something like: 1952 // cmp A, B 1953 // C = seteq 1954 // cmp D, E 1955 // F = setle 1956 // or C, F 1957 // jnz foo 1958 // Emit: 1959 // cmp A, B 1960 // je foo 1961 // cmp D, E 1962 // jle foo 1963 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1964 Instruction::BinaryOps Opcode = BOp->getOpcode(); 1965 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 1966 !I.getMetadata(LLVMContext::MD_unpredictable) && 1967 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 1968 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 1969 Opcode, 1970 getEdgeProbability(BrMBB, Succ0MBB), 1971 getEdgeProbability(BrMBB, Succ1MBB), 1972 /*InvertCond=*/false); 1973 // If the compares in later blocks need to use values not currently 1974 // exported from this block, export them now. This block should always 1975 // be the first entry. 1976 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 1977 1978 // Allow some cases to be rejected. 1979 if (ShouldEmitAsBranches(SwitchCases)) { 1980 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1981 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1982 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1983 } 1984 1985 // Emit the branch for this block. 1986 visitSwitchCase(SwitchCases[0], BrMBB); 1987 SwitchCases.erase(SwitchCases.begin()); 1988 return; 1989 } 1990 1991 // Okay, we decided not to do this, remove any inserted MBB's and clear 1992 // SwitchCases. 1993 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1994 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 1995 1996 SwitchCases.clear(); 1997 } 1998 } 1999 2000 // Create a CaseBlock record representing this branch. 2001 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2002 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2003 2004 // Use visitSwitchCase to actually insert the fast branch sequence for this 2005 // cond branch. 2006 visitSwitchCase(CB, BrMBB); 2007 } 2008 2009 /// visitSwitchCase - Emits the necessary code to represent a single node in 2010 /// the binary search tree resulting from lowering a switch instruction. 2011 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2012 MachineBasicBlock *SwitchBB) { 2013 SDValue Cond; 2014 SDValue CondLHS = getValue(CB.CmpLHS); 2015 SDLoc dl = CB.DL; 2016 2017 // Build the setcc now. 2018 if (!CB.CmpMHS) { 2019 // Fold "(X == true)" to X and "(X == false)" to !X to 2020 // handle common cases produced by branch lowering. 2021 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2022 CB.CC == ISD::SETEQ) 2023 Cond = CondLHS; 2024 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2025 CB.CC == ISD::SETEQ) { 2026 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2027 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2028 } else 2029 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2030 } else { 2031 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2032 2033 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2034 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2035 2036 SDValue CmpOp = getValue(CB.CmpMHS); 2037 EVT VT = CmpOp.getValueType(); 2038 2039 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2040 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2041 ISD::SETLE); 2042 } else { 2043 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2044 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2045 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2046 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2047 } 2048 } 2049 2050 // Update successor info 2051 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2052 // TrueBB and FalseBB are always different unless the incoming IR is 2053 // degenerate. This only happens when running llc on weird IR. 2054 if (CB.TrueBB != CB.FalseBB) 2055 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2056 SwitchBB->normalizeSuccProbs(); 2057 2058 // If the lhs block is the next block, invert the condition so that we can 2059 // fall through to the lhs instead of the rhs block. 2060 if (CB.TrueBB == NextBlock(SwitchBB)) { 2061 std::swap(CB.TrueBB, CB.FalseBB); 2062 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2063 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2064 } 2065 2066 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2067 MVT::Other, getControlRoot(), Cond, 2068 DAG.getBasicBlock(CB.TrueBB)); 2069 2070 // Insert the false branch. Do this even if it's a fall through branch, 2071 // this makes it easier to do DAG optimizations which require inverting 2072 // the branch condition. 2073 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2074 DAG.getBasicBlock(CB.FalseBB)); 2075 2076 DAG.setRoot(BrCond); 2077 } 2078 2079 /// visitJumpTable - Emit JumpTable node in the current MBB 2080 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2081 // Emit the code for the jump table 2082 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2083 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2084 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2085 JT.Reg, PTy); 2086 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2087 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2088 MVT::Other, Index.getValue(1), 2089 Table, Index); 2090 DAG.setRoot(BrJumpTable); 2091 } 2092 2093 /// visitJumpTableHeader - This function emits necessary code to produce index 2094 /// in the JumpTable from switch case. 2095 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2096 JumpTableHeader &JTH, 2097 MachineBasicBlock *SwitchBB) { 2098 SDLoc dl = getCurSDLoc(); 2099 2100 // Subtract the lowest switch case value from the value being switched on and 2101 // conditional branch to default mbb if the result is greater than the 2102 // difference between smallest and largest cases. 2103 SDValue SwitchOp = getValue(JTH.SValue); 2104 EVT VT = SwitchOp.getValueType(); 2105 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2106 DAG.getConstant(JTH.First, dl, VT)); 2107 2108 // The SDNode we just created, which holds the value being switched on minus 2109 // the smallest case value, needs to be copied to a virtual register so it 2110 // can be used as an index into the jump table in a subsequent basic block. 2111 // This value may be smaller or larger than the target's pointer type, and 2112 // therefore require extension or truncating. 2113 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2114 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2115 2116 unsigned JumpTableReg = 2117 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2118 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2119 JumpTableReg, SwitchOp); 2120 JT.Reg = JumpTableReg; 2121 2122 // Emit the range check for the jump table, and branch to the default block 2123 // for the switch statement if the value being switched on exceeds the largest 2124 // case in the switch. 2125 SDValue CMP = DAG.getSetCC( 2126 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2127 Sub.getValueType()), 2128 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2129 2130 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2131 MVT::Other, CopyTo, CMP, 2132 DAG.getBasicBlock(JT.Default)); 2133 2134 // Avoid emitting unnecessary branches to the next block. 2135 if (JT.MBB != NextBlock(SwitchBB)) 2136 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2137 DAG.getBasicBlock(JT.MBB)); 2138 2139 DAG.setRoot(BrCond); 2140 } 2141 2142 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2143 /// variable if there exists one. 2144 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2145 SDValue &Chain) { 2146 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2147 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2148 MachineFunction &MF = DAG.getMachineFunction(); 2149 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2150 MachineSDNode *Node = 2151 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2152 if (Global) { 2153 MachinePointerInfo MPInfo(Global); 2154 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1); 2155 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2156 MachineMemOperand::MODereferenceable; 2157 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8, 2158 DAG.getEVTAlignment(PtrTy)); 2159 Node->setMemRefs(MemRefs, MemRefs + 1); 2160 } 2161 return SDValue(Node, 0); 2162 } 2163 2164 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2165 /// tail spliced into a stack protector check success bb. 2166 /// 2167 /// For a high level explanation of how this fits into the stack protector 2168 /// generation see the comment on the declaration of class 2169 /// StackProtectorDescriptor. 2170 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2171 MachineBasicBlock *ParentBB) { 2172 2173 // First create the loads to the guard/stack slot for the comparison. 2174 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2175 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2176 2177 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2178 int FI = MFI.getStackProtectorIndex(); 2179 2180 SDValue Guard; 2181 SDLoc dl = getCurSDLoc(); 2182 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2183 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2184 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2185 2186 // Generate code to load the content of the guard slot. 2187 SDValue GuardVal = DAG.getLoad( 2188 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2189 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2190 MachineMemOperand::MOVolatile); 2191 2192 if (TLI.useStackGuardXorFP()) 2193 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2194 2195 // Retrieve guard check function, nullptr if instrumentation is inlined. 2196 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2197 // The target provides a guard check function to validate the guard value. 2198 // Generate a call to that function with the content of the guard slot as 2199 // argument. 2200 auto *Fn = cast<Function>(GuardCheck); 2201 FunctionType *FnTy = Fn->getFunctionType(); 2202 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2203 2204 TargetLowering::ArgListTy Args; 2205 TargetLowering::ArgListEntry Entry; 2206 Entry.Node = GuardVal; 2207 Entry.Ty = FnTy->getParamType(0); 2208 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2209 Entry.IsInReg = true; 2210 Args.push_back(Entry); 2211 2212 TargetLowering::CallLoweringInfo CLI(DAG); 2213 CLI.setDebugLoc(getCurSDLoc()) 2214 .setChain(DAG.getEntryNode()) 2215 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2216 getValue(GuardCheck), std::move(Args)); 2217 2218 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2219 DAG.setRoot(Result.second); 2220 return; 2221 } 2222 2223 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2224 // Otherwise, emit a volatile load to retrieve the stack guard value. 2225 SDValue Chain = DAG.getEntryNode(); 2226 if (TLI.useLoadStackGuardNode()) { 2227 Guard = getLoadStackGuard(DAG, dl, Chain); 2228 } else { 2229 const Value *IRGuard = TLI.getSDagStackGuard(M); 2230 SDValue GuardPtr = getValue(IRGuard); 2231 2232 Guard = 2233 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2234 Align, MachineMemOperand::MOVolatile); 2235 } 2236 2237 // Perform the comparison via a subtract/getsetcc. 2238 EVT VT = Guard.getValueType(); 2239 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2240 2241 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2242 *DAG.getContext(), 2243 Sub.getValueType()), 2244 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2245 2246 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2247 // branch to failure MBB. 2248 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2249 MVT::Other, GuardVal.getOperand(0), 2250 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2251 // Otherwise branch to success MBB. 2252 SDValue Br = DAG.getNode(ISD::BR, dl, 2253 MVT::Other, BrCond, 2254 DAG.getBasicBlock(SPD.getSuccessMBB())); 2255 2256 DAG.setRoot(Br); 2257 } 2258 2259 /// Codegen the failure basic block for a stack protector check. 2260 /// 2261 /// A failure stack protector machine basic block consists simply of a call to 2262 /// __stack_chk_fail(). 2263 /// 2264 /// For a high level explanation of how this fits into the stack protector 2265 /// generation see the comment on the declaration of class 2266 /// StackProtectorDescriptor. 2267 void 2268 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2269 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2270 SDValue Chain = 2271 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2272 None, false, getCurSDLoc(), false, false).second; 2273 DAG.setRoot(Chain); 2274 } 2275 2276 /// visitBitTestHeader - This function emits necessary code to produce value 2277 /// suitable for "bit tests" 2278 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2279 MachineBasicBlock *SwitchBB) { 2280 SDLoc dl = getCurSDLoc(); 2281 2282 // Subtract the minimum value 2283 SDValue SwitchOp = getValue(B.SValue); 2284 EVT VT = SwitchOp.getValueType(); 2285 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2286 DAG.getConstant(B.First, dl, VT)); 2287 2288 // Check range 2289 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2290 SDValue RangeCmp = DAG.getSetCC( 2291 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2292 Sub.getValueType()), 2293 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2294 2295 // Determine the type of the test operands. 2296 bool UsePtrType = false; 2297 if (!TLI.isTypeLegal(VT)) 2298 UsePtrType = true; 2299 else { 2300 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2301 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2302 // Switch table case range are encoded into series of masks. 2303 // Just use pointer type, it's guaranteed to fit. 2304 UsePtrType = true; 2305 break; 2306 } 2307 } 2308 if (UsePtrType) { 2309 VT = TLI.getPointerTy(DAG.getDataLayout()); 2310 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2311 } 2312 2313 B.RegVT = VT.getSimpleVT(); 2314 B.Reg = FuncInfo.CreateReg(B.RegVT); 2315 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2316 2317 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2318 2319 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2320 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2321 SwitchBB->normalizeSuccProbs(); 2322 2323 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2324 MVT::Other, CopyTo, RangeCmp, 2325 DAG.getBasicBlock(B.Default)); 2326 2327 // Avoid emitting unnecessary branches to the next block. 2328 if (MBB != NextBlock(SwitchBB)) 2329 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2330 DAG.getBasicBlock(MBB)); 2331 2332 DAG.setRoot(BrRange); 2333 } 2334 2335 /// visitBitTestCase - this function produces one "bit test" 2336 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2337 MachineBasicBlock* NextMBB, 2338 BranchProbability BranchProbToNext, 2339 unsigned Reg, 2340 BitTestCase &B, 2341 MachineBasicBlock *SwitchBB) { 2342 SDLoc dl = getCurSDLoc(); 2343 MVT VT = BB.RegVT; 2344 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2345 SDValue Cmp; 2346 unsigned PopCount = countPopulation(B.Mask); 2347 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2348 if (PopCount == 1) { 2349 // Testing for a single bit; just compare the shift count with what it 2350 // would need to be to shift a 1 bit in that position. 2351 Cmp = DAG.getSetCC( 2352 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2353 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2354 ISD::SETEQ); 2355 } else if (PopCount == BB.Range) { 2356 // There is only one zero bit in the range, test for it directly. 2357 Cmp = DAG.getSetCC( 2358 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2359 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2360 ISD::SETNE); 2361 } else { 2362 // Make desired shift 2363 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2364 DAG.getConstant(1, dl, VT), ShiftOp); 2365 2366 // Emit bit tests and jumps 2367 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2368 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2369 Cmp = DAG.getSetCC( 2370 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2371 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2372 } 2373 2374 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2375 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2376 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2377 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2378 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2379 // one as they are relative probabilities (and thus work more like weights), 2380 // and hence we need to normalize them to let the sum of them become one. 2381 SwitchBB->normalizeSuccProbs(); 2382 2383 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2384 MVT::Other, getControlRoot(), 2385 Cmp, DAG.getBasicBlock(B.TargetBB)); 2386 2387 // Avoid emitting unnecessary branches to the next block. 2388 if (NextMBB != NextBlock(SwitchBB)) 2389 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2390 DAG.getBasicBlock(NextMBB)); 2391 2392 DAG.setRoot(BrAnd); 2393 } 2394 2395 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2396 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2397 2398 // Retrieve successors. Look through artificial IR level blocks like 2399 // catchswitch for successors. 2400 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2401 const BasicBlock *EHPadBB = I.getSuccessor(1); 2402 2403 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2404 // have to do anything here to lower funclet bundles. 2405 assert(!I.hasOperandBundlesOtherThan( 2406 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2407 "Cannot lower invokes with arbitrary operand bundles yet!"); 2408 2409 const Value *Callee(I.getCalledValue()); 2410 const Function *Fn = dyn_cast<Function>(Callee); 2411 if (isa<InlineAsm>(Callee)) 2412 visitInlineAsm(&I); 2413 else if (Fn && Fn->isIntrinsic()) { 2414 switch (Fn->getIntrinsicID()) { 2415 default: 2416 llvm_unreachable("Cannot invoke this intrinsic"); 2417 case Intrinsic::donothing: 2418 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2419 break; 2420 case Intrinsic::experimental_patchpoint_void: 2421 case Intrinsic::experimental_patchpoint_i64: 2422 visitPatchpoint(&I, EHPadBB); 2423 break; 2424 case Intrinsic::experimental_gc_statepoint: 2425 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2426 break; 2427 } 2428 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2429 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2430 // Eventually we will support lowering the @llvm.experimental.deoptimize 2431 // intrinsic, and right now there are no plans to support other intrinsics 2432 // with deopt state. 2433 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2434 } else { 2435 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2436 } 2437 2438 // If the value of the invoke is used outside of its defining block, make it 2439 // available as a virtual register. 2440 // We already took care of the exported value for the statepoint instruction 2441 // during call to the LowerStatepoint. 2442 if (!isStatepoint(I)) { 2443 CopyToExportRegsIfNeeded(&I); 2444 } 2445 2446 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2447 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2448 BranchProbability EHPadBBProb = 2449 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2450 : BranchProbability::getZero(); 2451 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2452 2453 // Update successor info. 2454 addSuccessorWithProb(InvokeMBB, Return); 2455 for (auto &UnwindDest : UnwindDests) { 2456 UnwindDest.first->setIsEHPad(); 2457 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2458 } 2459 InvokeMBB->normalizeSuccProbs(); 2460 2461 // Drop into normal successor. 2462 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2463 MVT::Other, getControlRoot(), 2464 DAG.getBasicBlock(Return))); 2465 } 2466 2467 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2468 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2469 } 2470 2471 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2472 assert(FuncInfo.MBB->isEHPad() && 2473 "Call to landingpad not in landing pad!"); 2474 2475 MachineBasicBlock *MBB = FuncInfo.MBB; 2476 addLandingPadInfo(LP, *MBB); 2477 2478 // If there aren't registers to copy the values into (e.g., during SjLj 2479 // exceptions), then don't bother to create these DAG nodes. 2480 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2481 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2482 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2483 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2484 return; 2485 2486 // If landingpad's return type is token type, we don't create DAG nodes 2487 // for its exception pointer and selector value. The extraction of exception 2488 // pointer or selector value from token type landingpads is not currently 2489 // supported. 2490 if (LP.getType()->isTokenTy()) 2491 return; 2492 2493 SmallVector<EVT, 2> ValueVTs; 2494 SDLoc dl = getCurSDLoc(); 2495 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2496 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2497 2498 // Get the two live-in registers as SDValues. The physregs have already been 2499 // copied into virtual registers. 2500 SDValue Ops[2]; 2501 if (FuncInfo.ExceptionPointerVirtReg) { 2502 Ops[0] = DAG.getZExtOrTrunc( 2503 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2504 FuncInfo.ExceptionPointerVirtReg, 2505 TLI.getPointerTy(DAG.getDataLayout())), 2506 dl, ValueVTs[0]); 2507 } else { 2508 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2509 } 2510 Ops[1] = DAG.getZExtOrTrunc( 2511 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2512 FuncInfo.ExceptionSelectorVirtReg, 2513 TLI.getPointerTy(DAG.getDataLayout())), 2514 dl, ValueVTs[1]); 2515 2516 // Merge into one. 2517 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2518 DAG.getVTList(ValueVTs), Ops); 2519 setValue(&LP, Res); 2520 } 2521 2522 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2523 #ifndef NDEBUG 2524 for (const CaseCluster &CC : Clusters) 2525 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2526 #endif 2527 2528 std::sort(Clusters.begin(), Clusters.end(), 2529 [](const CaseCluster &a, const CaseCluster &b) { 2530 return a.Low->getValue().slt(b.Low->getValue()); 2531 }); 2532 2533 // Merge adjacent clusters with the same destination. 2534 const unsigned N = Clusters.size(); 2535 unsigned DstIndex = 0; 2536 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2537 CaseCluster &CC = Clusters[SrcIndex]; 2538 const ConstantInt *CaseVal = CC.Low; 2539 MachineBasicBlock *Succ = CC.MBB; 2540 2541 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2542 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2543 // If this case has the same successor and is a neighbour, merge it into 2544 // the previous cluster. 2545 Clusters[DstIndex - 1].High = CaseVal; 2546 Clusters[DstIndex - 1].Prob += CC.Prob; 2547 } else { 2548 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2549 sizeof(Clusters[SrcIndex])); 2550 } 2551 } 2552 Clusters.resize(DstIndex); 2553 } 2554 2555 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2556 MachineBasicBlock *Last) { 2557 // Update JTCases. 2558 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2559 if (JTCases[i].first.HeaderBB == First) 2560 JTCases[i].first.HeaderBB = Last; 2561 2562 // Update BitTestCases. 2563 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2564 if (BitTestCases[i].Parent == First) 2565 BitTestCases[i].Parent = Last; 2566 } 2567 2568 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2569 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2570 2571 // Update machine-CFG edges with unique successors. 2572 SmallSet<BasicBlock*, 32> Done; 2573 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2574 BasicBlock *BB = I.getSuccessor(i); 2575 bool Inserted = Done.insert(BB).second; 2576 if (!Inserted) 2577 continue; 2578 2579 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2580 addSuccessorWithProb(IndirectBrMBB, Succ); 2581 } 2582 IndirectBrMBB->normalizeSuccProbs(); 2583 2584 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2585 MVT::Other, getControlRoot(), 2586 getValue(I.getAddress()))); 2587 } 2588 2589 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2590 if (DAG.getTarget().Options.TrapUnreachable) 2591 DAG.setRoot( 2592 DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2593 } 2594 2595 void SelectionDAGBuilder::visitFSub(const User &I) { 2596 // -0.0 - X --> fneg 2597 Type *Ty = I.getType(); 2598 if (isa<Constant>(I.getOperand(0)) && 2599 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2600 SDValue Op2 = getValue(I.getOperand(1)); 2601 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2602 Op2.getValueType(), Op2)); 2603 return; 2604 } 2605 2606 visitBinary(I, ISD::FSUB); 2607 } 2608 2609 /// Checks if the given instruction performs a vector reduction, in which case 2610 /// we have the freedom to alter the elements in the result as long as the 2611 /// reduction of them stays unchanged. 2612 static bool isVectorReductionOp(const User *I) { 2613 const Instruction *Inst = dyn_cast<Instruction>(I); 2614 if (!Inst || !Inst->getType()->isVectorTy()) 2615 return false; 2616 2617 auto OpCode = Inst->getOpcode(); 2618 switch (OpCode) { 2619 case Instruction::Add: 2620 case Instruction::Mul: 2621 case Instruction::And: 2622 case Instruction::Or: 2623 case Instruction::Xor: 2624 break; 2625 case Instruction::FAdd: 2626 case Instruction::FMul: 2627 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2628 if (FPOp->getFastMathFlags().isFast()) 2629 break; 2630 LLVM_FALLTHROUGH; 2631 default: 2632 return false; 2633 } 2634 2635 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2636 unsigned ElemNumToReduce = ElemNum; 2637 2638 // Do DFS search on the def-use chain from the given instruction. We only 2639 // allow four kinds of operations during the search until we reach the 2640 // instruction that extracts the first element from the vector: 2641 // 2642 // 1. The reduction operation of the same opcode as the given instruction. 2643 // 2644 // 2. PHI node. 2645 // 2646 // 3. ShuffleVector instruction together with a reduction operation that 2647 // does a partial reduction. 2648 // 2649 // 4. ExtractElement that extracts the first element from the vector, and we 2650 // stop searching the def-use chain here. 2651 // 2652 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2653 // from 1-3 to the stack to continue the DFS. The given instruction is not 2654 // a reduction operation if we meet any other instructions other than those 2655 // listed above. 2656 2657 SmallVector<const User *, 16> UsersToVisit{Inst}; 2658 SmallPtrSet<const User *, 16> Visited; 2659 bool ReduxExtracted = false; 2660 2661 while (!UsersToVisit.empty()) { 2662 auto User = UsersToVisit.back(); 2663 UsersToVisit.pop_back(); 2664 if (!Visited.insert(User).second) 2665 continue; 2666 2667 for (const auto &U : User->users()) { 2668 auto Inst = dyn_cast<Instruction>(U); 2669 if (!Inst) 2670 return false; 2671 2672 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2673 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2674 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2675 return false; 2676 UsersToVisit.push_back(U); 2677 } else if (const ShuffleVectorInst *ShufInst = 2678 dyn_cast<ShuffleVectorInst>(U)) { 2679 // Detect the following pattern: A ShuffleVector instruction together 2680 // with a reduction that do partial reduction on the first and second 2681 // ElemNumToReduce / 2 elements, and store the result in 2682 // ElemNumToReduce / 2 elements in another vector. 2683 2684 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2685 if (ResultElements < ElemNum) 2686 return false; 2687 2688 if (ElemNumToReduce == 1) 2689 return false; 2690 if (!isa<UndefValue>(U->getOperand(1))) 2691 return false; 2692 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2693 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2694 return false; 2695 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2696 if (ShufInst->getMaskValue(i) != -1) 2697 return false; 2698 2699 // There is only one user of this ShuffleVector instruction, which 2700 // must be a reduction operation. 2701 if (!U->hasOneUse()) 2702 return false; 2703 2704 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2705 if (!U2 || U2->getOpcode() != OpCode) 2706 return false; 2707 2708 // Check operands of the reduction operation. 2709 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2710 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2711 UsersToVisit.push_back(U2); 2712 ElemNumToReduce /= 2; 2713 } else 2714 return false; 2715 } else if (isa<ExtractElementInst>(U)) { 2716 // At this moment we should have reduced all elements in the vector. 2717 if (ElemNumToReduce != 1) 2718 return false; 2719 2720 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2721 if (!Val || Val->getZExtValue() != 0) 2722 return false; 2723 2724 ReduxExtracted = true; 2725 } else 2726 return false; 2727 } 2728 } 2729 return ReduxExtracted; 2730 } 2731 2732 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) { 2733 SDValue Op1 = getValue(I.getOperand(0)); 2734 SDValue Op2 = getValue(I.getOperand(1)); 2735 2736 bool nuw = false; 2737 bool nsw = false; 2738 bool exact = false; 2739 bool vec_redux = false; 2740 FastMathFlags FMF; 2741 2742 if (const OverflowingBinaryOperator *OFBinOp = 2743 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2744 nuw = OFBinOp->hasNoUnsignedWrap(); 2745 nsw = OFBinOp->hasNoSignedWrap(); 2746 } 2747 if (const PossiblyExactOperator *ExactOp = 2748 dyn_cast<const PossiblyExactOperator>(&I)) 2749 exact = ExactOp->isExact(); 2750 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I)) 2751 FMF = FPOp->getFastMathFlags(); 2752 2753 if (isVectorReductionOp(&I)) { 2754 vec_redux = true; 2755 DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2756 } 2757 2758 SDNodeFlags Flags; 2759 Flags.setExact(exact); 2760 Flags.setNoSignedWrap(nsw); 2761 Flags.setNoUnsignedWrap(nuw); 2762 Flags.setVectorReduction(vec_redux); 2763 Flags.setAllowReciprocal(FMF.allowReciprocal()); 2764 Flags.setAllowContract(FMF.allowContract()); 2765 Flags.setNoInfs(FMF.noInfs()); 2766 Flags.setNoNaNs(FMF.noNaNs()); 2767 Flags.setNoSignedZeros(FMF.noSignedZeros()); 2768 Flags.setUnsafeAlgebra(FMF.isFast()); 2769 2770 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(), 2771 Op1, Op2, Flags); 2772 setValue(&I, BinNodeValue); 2773 } 2774 2775 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2776 SDValue Op1 = getValue(I.getOperand(0)); 2777 SDValue Op2 = getValue(I.getOperand(1)); 2778 2779 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2780 Op2.getValueType(), DAG.getDataLayout()); 2781 2782 // Coerce the shift amount to the right type if we can. 2783 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2784 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2785 unsigned Op2Size = Op2.getValueSizeInBits(); 2786 SDLoc DL = getCurSDLoc(); 2787 2788 // If the operand is smaller than the shift count type, promote it. 2789 if (ShiftSize > Op2Size) 2790 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2791 2792 // If the operand is larger than the shift count type but the shift 2793 // count type has enough bits to represent any shift value, truncate 2794 // it now. This is a common case and it exposes the truncate to 2795 // optimization early. 2796 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2797 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2798 // Otherwise we'll need to temporarily settle for some other convenient 2799 // type. Type legalization will make adjustments once the shiftee is split. 2800 else 2801 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2802 } 2803 2804 bool nuw = false; 2805 bool nsw = false; 2806 bool exact = false; 2807 2808 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2809 2810 if (const OverflowingBinaryOperator *OFBinOp = 2811 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2812 nuw = OFBinOp->hasNoUnsignedWrap(); 2813 nsw = OFBinOp->hasNoSignedWrap(); 2814 } 2815 if (const PossiblyExactOperator *ExactOp = 2816 dyn_cast<const PossiblyExactOperator>(&I)) 2817 exact = ExactOp->isExact(); 2818 } 2819 SDNodeFlags Flags; 2820 Flags.setExact(exact); 2821 Flags.setNoSignedWrap(nsw); 2822 Flags.setNoUnsignedWrap(nuw); 2823 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2824 Flags); 2825 setValue(&I, Res); 2826 } 2827 2828 void SelectionDAGBuilder::visitSDiv(const User &I) { 2829 SDValue Op1 = getValue(I.getOperand(0)); 2830 SDValue Op2 = getValue(I.getOperand(1)); 2831 2832 SDNodeFlags Flags; 2833 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2834 cast<PossiblyExactOperator>(&I)->isExact()); 2835 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2836 Op2, Flags)); 2837 } 2838 2839 void SelectionDAGBuilder::visitICmp(const User &I) { 2840 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2841 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2842 predicate = IC->getPredicate(); 2843 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2844 predicate = ICmpInst::Predicate(IC->getPredicate()); 2845 SDValue Op1 = getValue(I.getOperand(0)); 2846 SDValue Op2 = getValue(I.getOperand(1)); 2847 ISD::CondCode Opcode = getICmpCondCode(predicate); 2848 2849 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2850 I.getType()); 2851 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2852 } 2853 2854 void SelectionDAGBuilder::visitFCmp(const User &I) { 2855 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2856 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2857 predicate = FC->getPredicate(); 2858 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2859 predicate = FCmpInst::Predicate(FC->getPredicate()); 2860 SDValue Op1 = getValue(I.getOperand(0)); 2861 SDValue Op2 = getValue(I.getOperand(1)); 2862 ISD::CondCode Condition = getFCmpCondCode(predicate); 2863 2864 // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them. 2865 // FIXME: We should propagate the fast-math-flags to the DAG node itself for 2866 // further optimization, but currently FMF is only applicable to binary nodes. 2867 if (TM.Options.NoNaNsFPMath) 2868 Condition = getFCmpCodeWithoutNaN(Condition); 2869 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2870 I.getType()); 2871 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2872 } 2873 2874 // Check if the condition of the select has one use or two users that are both 2875 // selects with the same condition. 2876 static bool hasOnlySelectUsers(const Value *Cond) { 2877 return llvm::all_of(Cond->users(), [](const Value *V) { 2878 return isa<SelectInst>(V); 2879 }); 2880 } 2881 2882 void SelectionDAGBuilder::visitSelect(const User &I) { 2883 SmallVector<EVT, 4> ValueVTs; 2884 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2885 ValueVTs); 2886 unsigned NumValues = ValueVTs.size(); 2887 if (NumValues == 0) return; 2888 2889 SmallVector<SDValue, 4> Values(NumValues); 2890 SDValue Cond = getValue(I.getOperand(0)); 2891 SDValue LHSVal = getValue(I.getOperand(1)); 2892 SDValue RHSVal = getValue(I.getOperand(2)); 2893 auto BaseOps = {Cond}; 2894 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2895 ISD::VSELECT : ISD::SELECT; 2896 2897 // Min/max matching is only viable if all output VTs are the same. 2898 if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) { 2899 EVT VT = ValueVTs[0]; 2900 LLVMContext &Ctx = *DAG.getContext(); 2901 auto &TLI = DAG.getTargetLoweringInfo(); 2902 2903 // We care about the legality of the operation after it has been type 2904 // legalized. 2905 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2906 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2907 VT = TLI.getTypeToTransformTo(Ctx, VT); 2908 2909 // If the vselect is legal, assume we want to leave this as a vector setcc + 2910 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2911 // min/max is legal on the scalar type. 2912 bool UseScalarMinMax = VT.isVector() && 2913 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2914 2915 Value *LHS, *RHS; 2916 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2917 ISD::NodeType Opc = ISD::DELETED_NODE; 2918 switch (SPR.Flavor) { 2919 case SPF_UMAX: Opc = ISD::UMAX; break; 2920 case SPF_UMIN: Opc = ISD::UMIN; break; 2921 case SPF_SMAX: Opc = ISD::SMAX; break; 2922 case SPF_SMIN: Opc = ISD::SMIN; break; 2923 case SPF_FMINNUM: 2924 switch (SPR.NaNBehavior) { 2925 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2926 case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break; 2927 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2928 case SPNB_RETURNS_ANY: { 2929 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2930 Opc = ISD::FMINNUM; 2931 else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)) 2932 Opc = ISD::FMINNAN; 2933 else if (UseScalarMinMax) 2934 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2935 ISD::FMINNUM : ISD::FMINNAN; 2936 break; 2937 } 2938 } 2939 break; 2940 case SPF_FMAXNUM: 2941 switch (SPR.NaNBehavior) { 2942 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2943 case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break; 2944 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 2945 case SPNB_RETURNS_ANY: 2946 2947 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 2948 Opc = ISD::FMAXNUM; 2949 else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)) 2950 Opc = ISD::FMAXNAN; 2951 else if (UseScalarMinMax) 2952 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 2953 ISD::FMAXNUM : ISD::FMAXNAN; 2954 break; 2955 } 2956 break; 2957 default: break; 2958 } 2959 2960 if (Opc != ISD::DELETED_NODE && 2961 (TLI.isOperationLegalOrCustom(Opc, VT) || 2962 (UseScalarMinMax && 2963 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 2964 // If the underlying comparison instruction is used by any other 2965 // instruction, the consumed instructions won't be destroyed, so it is 2966 // not profitable to convert to a min/max. 2967 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 2968 OpCode = Opc; 2969 LHSVal = getValue(LHS); 2970 RHSVal = getValue(RHS); 2971 BaseOps = {}; 2972 } 2973 } 2974 2975 for (unsigned i = 0; i != NumValues; ++i) { 2976 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 2977 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 2978 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 2979 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 2980 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 2981 Ops); 2982 } 2983 2984 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2985 DAG.getVTList(ValueVTs), Values)); 2986 } 2987 2988 void SelectionDAGBuilder::visitTrunc(const User &I) { 2989 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2990 SDValue N = getValue(I.getOperand(0)); 2991 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2992 I.getType()); 2993 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 2994 } 2995 2996 void SelectionDAGBuilder::visitZExt(const User &I) { 2997 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2998 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2999 SDValue N = getValue(I.getOperand(0)); 3000 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3001 I.getType()); 3002 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3003 } 3004 3005 void SelectionDAGBuilder::visitSExt(const User &I) { 3006 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3007 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3008 SDValue N = getValue(I.getOperand(0)); 3009 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3010 I.getType()); 3011 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3012 } 3013 3014 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3015 // FPTrunc is never a no-op cast, no need to check 3016 SDValue N = getValue(I.getOperand(0)); 3017 SDLoc dl = getCurSDLoc(); 3018 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3019 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3020 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3021 DAG.getTargetConstant( 3022 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3023 } 3024 3025 void SelectionDAGBuilder::visitFPExt(const User &I) { 3026 // FPExt is never a no-op cast, no need to check 3027 SDValue N = getValue(I.getOperand(0)); 3028 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3029 I.getType()); 3030 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3031 } 3032 3033 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3034 // FPToUI is never a no-op cast, no need to check 3035 SDValue N = getValue(I.getOperand(0)); 3036 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3037 I.getType()); 3038 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3039 } 3040 3041 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3042 // FPToSI is never a no-op cast, no need to check 3043 SDValue N = getValue(I.getOperand(0)); 3044 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3045 I.getType()); 3046 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3047 } 3048 3049 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3050 // UIToFP is never a no-op cast, no need to check 3051 SDValue N = getValue(I.getOperand(0)); 3052 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3053 I.getType()); 3054 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3055 } 3056 3057 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3058 // SIToFP is never a no-op cast, no need to check 3059 SDValue N = getValue(I.getOperand(0)); 3060 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3061 I.getType()); 3062 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3063 } 3064 3065 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3066 // What to do depends on the size of the integer and the size of the pointer. 3067 // We can either truncate, zero extend, or no-op, accordingly. 3068 SDValue N = getValue(I.getOperand(0)); 3069 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3070 I.getType()); 3071 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3072 } 3073 3074 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3075 // What to do depends on the size of the integer and the size of the pointer. 3076 // We can either truncate, zero extend, or no-op, accordingly. 3077 SDValue N = getValue(I.getOperand(0)); 3078 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3079 I.getType()); 3080 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3081 } 3082 3083 void SelectionDAGBuilder::visitBitCast(const User &I) { 3084 SDValue N = getValue(I.getOperand(0)); 3085 SDLoc dl = getCurSDLoc(); 3086 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3087 I.getType()); 3088 3089 // BitCast assures us that source and destination are the same size so this is 3090 // either a BITCAST or a no-op. 3091 if (DestVT != N.getValueType()) 3092 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3093 DestVT, N)); // convert types. 3094 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3095 // might fold any kind of constant expression to an integer constant and that 3096 // is not what we are looking for. Only recognize a bitcast of a genuine 3097 // constant integer as an opaque constant. 3098 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3099 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3100 /*isOpaque*/true)); 3101 else 3102 setValue(&I, N); // noop cast. 3103 } 3104 3105 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3106 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3107 const Value *SV = I.getOperand(0); 3108 SDValue N = getValue(SV); 3109 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3110 3111 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3112 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3113 3114 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3115 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3116 3117 setValue(&I, N); 3118 } 3119 3120 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3121 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3122 SDValue InVec = getValue(I.getOperand(0)); 3123 SDValue InVal = getValue(I.getOperand(1)); 3124 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3125 TLI.getVectorIdxTy(DAG.getDataLayout())); 3126 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3127 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3128 InVec, InVal, InIdx)); 3129 } 3130 3131 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3132 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3133 SDValue InVec = getValue(I.getOperand(0)); 3134 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3135 TLI.getVectorIdxTy(DAG.getDataLayout())); 3136 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3137 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3138 InVec, InIdx)); 3139 } 3140 3141 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3142 SDValue Src1 = getValue(I.getOperand(0)); 3143 SDValue Src2 = getValue(I.getOperand(1)); 3144 SDLoc DL = getCurSDLoc(); 3145 3146 SmallVector<int, 8> Mask; 3147 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3148 unsigned MaskNumElts = Mask.size(); 3149 3150 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3151 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3152 EVT SrcVT = Src1.getValueType(); 3153 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3154 3155 if (SrcNumElts == MaskNumElts) { 3156 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3157 return; 3158 } 3159 3160 // Normalize the shuffle vector since mask and vector length don't match. 3161 if (SrcNumElts < MaskNumElts) { 3162 // Mask is longer than the source vectors. We can use concatenate vector to 3163 // make the mask and vectors lengths match. 3164 3165 if (MaskNumElts % SrcNumElts == 0) { 3166 // Mask length is a multiple of the source vector length. 3167 // Check if the shuffle is some kind of concatenation of the input 3168 // vectors. 3169 unsigned NumConcat = MaskNumElts / SrcNumElts; 3170 bool IsConcat = true; 3171 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3172 for (unsigned i = 0; i != MaskNumElts; ++i) { 3173 int Idx = Mask[i]; 3174 if (Idx < 0) 3175 continue; 3176 // Ensure the indices in each SrcVT sized piece are sequential and that 3177 // the same source is used for the whole piece. 3178 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3179 (ConcatSrcs[i / SrcNumElts] >= 0 && 3180 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3181 IsConcat = false; 3182 break; 3183 } 3184 // Remember which source this index came from. 3185 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3186 } 3187 3188 // The shuffle is concatenating multiple vectors together. Just emit 3189 // a CONCAT_VECTORS operation. 3190 if (IsConcat) { 3191 SmallVector<SDValue, 8> ConcatOps; 3192 for (auto Src : ConcatSrcs) { 3193 if (Src < 0) 3194 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3195 else if (Src == 0) 3196 ConcatOps.push_back(Src1); 3197 else 3198 ConcatOps.push_back(Src2); 3199 } 3200 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3201 return; 3202 } 3203 } 3204 3205 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3206 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3207 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3208 PaddedMaskNumElts); 3209 3210 // Pad both vectors with undefs to make them the same length as the mask. 3211 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3212 3213 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3214 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3215 MOps1[0] = Src1; 3216 MOps2[0] = Src2; 3217 3218 Src1 = Src1.isUndef() 3219 ? DAG.getUNDEF(PaddedVT) 3220 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3221 Src2 = Src2.isUndef() 3222 ? DAG.getUNDEF(PaddedVT) 3223 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3224 3225 // Readjust mask for new input vector length. 3226 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3227 for (unsigned i = 0; i != MaskNumElts; ++i) { 3228 int Idx = Mask[i]; 3229 if (Idx >= (int)SrcNumElts) 3230 Idx -= SrcNumElts - PaddedMaskNumElts; 3231 MappedOps[i] = Idx; 3232 } 3233 3234 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3235 3236 // If the concatenated vector was padded, extract a subvector with the 3237 // correct number of elements. 3238 if (MaskNumElts != PaddedMaskNumElts) 3239 Result = DAG.getNode( 3240 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3241 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3242 3243 setValue(&I, Result); 3244 return; 3245 } 3246 3247 if (SrcNumElts > MaskNumElts) { 3248 // Analyze the access pattern of the vector to see if we can extract 3249 // two subvectors and do the shuffle. 3250 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3251 bool CanExtract = true; 3252 for (int Idx : Mask) { 3253 unsigned Input = 0; 3254 if (Idx < 0) 3255 continue; 3256 3257 if (Idx >= (int)SrcNumElts) { 3258 Input = 1; 3259 Idx -= SrcNumElts; 3260 } 3261 3262 // If all the indices come from the same MaskNumElts sized portion of 3263 // the sources we can use extract. Also make sure the extract wouldn't 3264 // extract past the end of the source. 3265 int NewStartIdx = alignDown(Idx, MaskNumElts); 3266 if (NewStartIdx + MaskNumElts > SrcNumElts || 3267 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3268 CanExtract = false; 3269 // Make sure we always update StartIdx as we use it to track if all 3270 // elements are undef. 3271 StartIdx[Input] = NewStartIdx; 3272 } 3273 3274 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3275 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3276 return; 3277 } 3278 if (CanExtract) { 3279 // Extract appropriate subvector and generate a vector shuffle 3280 for (unsigned Input = 0; Input < 2; ++Input) { 3281 SDValue &Src = Input == 0 ? Src1 : Src2; 3282 if (StartIdx[Input] < 0) 3283 Src = DAG.getUNDEF(VT); 3284 else { 3285 Src = DAG.getNode( 3286 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3287 DAG.getConstant(StartIdx[Input], DL, 3288 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3289 } 3290 } 3291 3292 // Calculate new mask. 3293 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3294 for (int &Idx : MappedOps) { 3295 if (Idx >= (int)SrcNumElts) 3296 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3297 else if (Idx >= 0) 3298 Idx -= StartIdx[0]; 3299 } 3300 3301 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3302 return; 3303 } 3304 } 3305 3306 // We can't use either concat vectors or extract subvectors so fall back to 3307 // replacing the shuffle with extract and build vector. 3308 // to insert and build vector. 3309 EVT EltVT = VT.getVectorElementType(); 3310 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3311 SmallVector<SDValue,8> Ops; 3312 for (int Idx : Mask) { 3313 SDValue Res; 3314 3315 if (Idx < 0) { 3316 Res = DAG.getUNDEF(EltVT); 3317 } else { 3318 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3319 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3320 3321 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3322 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3323 } 3324 3325 Ops.push_back(Res); 3326 } 3327 3328 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3329 } 3330 3331 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3332 ArrayRef<unsigned> Indices; 3333 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3334 Indices = IV->getIndices(); 3335 else 3336 Indices = cast<ConstantExpr>(&I)->getIndices(); 3337 3338 const Value *Op0 = I.getOperand(0); 3339 const Value *Op1 = I.getOperand(1); 3340 Type *AggTy = I.getType(); 3341 Type *ValTy = Op1->getType(); 3342 bool IntoUndef = isa<UndefValue>(Op0); 3343 bool FromUndef = isa<UndefValue>(Op1); 3344 3345 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3346 3347 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3348 SmallVector<EVT, 4> AggValueVTs; 3349 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3350 SmallVector<EVT, 4> ValValueVTs; 3351 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3352 3353 unsigned NumAggValues = AggValueVTs.size(); 3354 unsigned NumValValues = ValValueVTs.size(); 3355 SmallVector<SDValue, 4> Values(NumAggValues); 3356 3357 // Ignore an insertvalue that produces an empty object 3358 if (!NumAggValues) { 3359 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3360 return; 3361 } 3362 3363 SDValue Agg = getValue(Op0); 3364 unsigned i = 0; 3365 // Copy the beginning value(s) from the original aggregate. 3366 for (; i != LinearIndex; ++i) 3367 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3368 SDValue(Agg.getNode(), Agg.getResNo() + i); 3369 // Copy values from the inserted value(s). 3370 if (NumValValues) { 3371 SDValue Val = getValue(Op1); 3372 for (; i != LinearIndex + NumValValues; ++i) 3373 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3374 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3375 } 3376 // Copy remaining value(s) from the original aggregate. 3377 for (; i != NumAggValues; ++i) 3378 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3379 SDValue(Agg.getNode(), Agg.getResNo() + i); 3380 3381 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3382 DAG.getVTList(AggValueVTs), Values)); 3383 } 3384 3385 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3386 ArrayRef<unsigned> Indices; 3387 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3388 Indices = EV->getIndices(); 3389 else 3390 Indices = cast<ConstantExpr>(&I)->getIndices(); 3391 3392 const Value *Op0 = I.getOperand(0); 3393 Type *AggTy = Op0->getType(); 3394 Type *ValTy = I.getType(); 3395 bool OutOfUndef = isa<UndefValue>(Op0); 3396 3397 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3398 3399 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3400 SmallVector<EVT, 4> ValValueVTs; 3401 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3402 3403 unsigned NumValValues = ValValueVTs.size(); 3404 3405 // Ignore a extractvalue that produces an empty object 3406 if (!NumValValues) { 3407 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3408 return; 3409 } 3410 3411 SmallVector<SDValue, 4> Values(NumValValues); 3412 3413 SDValue Agg = getValue(Op0); 3414 // Copy out the selected value(s). 3415 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3416 Values[i - LinearIndex] = 3417 OutOfUndef ? 3418 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3419 SDValue(Agg.getNode(), Agg.getResNo() + i); 3420 3421 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3422 DAG.getVTList(ValValueVTs), Values)); 3423 } 3424 3425 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3426 Value *Op0 = I.getOperand(0); 3427 // Note that the pointer operand may be a vector of pointers. Take the scalar 3428 // element which holds a pointer. 3429 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3430 SDValue N = getValue(Op0); 3431 SDLoc dl = getCurSDLoc(); 3432 3433 // Normalize Vector GEP - all scalar operands should be converted to the 3434 // splat vector. 3435 unsigned VectorWidth = I.getType()->isVectorTy() ? 3436 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3437 3438 if (VectorWidth && !N.getValueType().isVector()) { 3439 LLVMContext &Context = *DAG.getContext(); 3440 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3441 N = DAG.getSplatBuildVector(VT, dl, N); 3442 } 3443 3444 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3445 GTI != E; ++GTI) { 3446 const Value *Idx = GTI.getOperand(); 3447 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3448 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3449 if (Field) { 3450 // N = N + Offset 3451 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3452 3453 // In an inbounds GEP with an offset that is nonnegative even when 3454 // interpreted as signed, assume there is no unsigned overflow. 3455 SDNodeFlags Flags; 3456 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3457 Flags.setNoUnsignedWrap(true); 3458 3459 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3460 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3461 } 3462 } else { 3463 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3464 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3465 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3466 3467 // If this is a scalar constant or a splat vector of constants, 3468 // handle it quickly. 3469 const auto *CI = dyn_cast<ConstantInt>(Idx); 3470 if (!CI && isa<ConstantDataVector>(Idx) && 3471 cast<ConstantDataVector>(Idx)->getSplatValue()) 3472 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3473 3474 if (CI) { 3475 if (CI->isZero()) 3476 continue; 3477 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3478 LLVMContext &Context = *DAG.getContext(); 3479 SDValue OffsVal = VectorWidth ? 3480 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3481 DAG.getConstant(Offs, dl, IdxTy); 3482 3483 // In an inbouds GEP with an offset that is nonnegative even when 3484 // interpreted as signed, assume there is no unsigned overflow. 3485 SDNodeFlags Flags; 3486 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3487 Flags.setNoUnsignedWrap(true); 3488 3489 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3490 continue; 3491 } 3492 3493 // N = N + Idx * ElementSize; 3494 SDValue IdxN = getValue(Idx); 3495 3496 if (!IdxN.getValueType().isVector() && VectorWidth) { 3497 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3498 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3499 } 3500 3501 // If the index is smaller or larger than intptr_t, truncate or extend 3502 // it. 3503 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3504 3505 // If this is a multiply by a power of two, turn it into a shl 3506 // immediately. This is a very common case. 3507 if (ElementSize != 1) { 3508 if (ElementSize.isPowerOf2()) { 3509 unsigned Amt = ElementSize.logBase2(); 3510 IdxN = DAG.getNode(ISD::SHL, dl, 3511 N.getValueType(), IdxN, 3512 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3513 } else { 3514 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3515 IdxN = DAG.getNode(ISD::MUL, dl, 3516 N.getValueType(), IdxN, Scale); 3517 } 3518 } 3519 3520 N = DAG.getNode(ISD::ADD, dl, 3521 N.getValueType(), N, IdxN); 3522 } 3523 } 3524 3525 setValue(&I, N); 3526 } 3527 3528 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3529 // If this is a fixed sized alloca in the entry block of the function, 3530 // allocate it statically on the stack. 3531 if (FuncInfo.StaticAllocaMap.count(&I)) 3532 return; // getValue will auto-populate this. 3533 3534 SDLoc dl = getCurSDLoc(); 3535 Type *Ty = I.getAllocatedType(); 3536 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3537 auto &DL = DAG.getDataLayout(); 3538 uint64_t TySize = DL.getTypeAllocSize(Ty); 3539 unsigned Align = 3540 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3541 3542 SDValue AllocSize = getValue(I.getArraySize()); 3543 3544 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3545 if (AllocSize.getValueType() != IntPtr) 3546 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3547 3548 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3549 AllocSize, 3550 DAG.getConstant(TySize, dl, IntPtr)); 3551 3552 // Handle alignment. If the requested alignment is less than or equal to 3553 // the stack alignment, ignore it. If the size is greater than or equal to 3554 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3555 unsigned StackAlign = 3556 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3557 if (Align <= StackAlign) 3558 Align = 0; 3559 3560 // Round the size of the allocation up to the stack alignment size 3561 // by add SA-1 to the size. This doesn't overflow because we're computing 3562 // an address inside an alloca. 3563 SDNodeFlags Flags; 3564 Flags.setNoUnsignedWrap(true); 3565 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3566 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3567 3568 // Mask out the low bits for alignment purposes. 3569 AllocSize = 3570 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3571 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3572 3573 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3574 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3575 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3576 setValue(&I, DSA); 3577 DAG.setRoot(DSA.getValue(1)); 3578 3579 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3580 } 3581 3582 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3583 if (I.isAtomic()) 3584 return visitAtomicLoad(I); 3585 3586 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3587 const Value *SV = I.getOperand(0); 3588 if (TLI.supportSwiftError()) { 3589 // Swifterror values can come from either a function parameter with 3590 // swifterror attribute or an alloca with swifterror attribute. 3591 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3592 if (Arg->hasSwiftErrorAttr()) 3593 return visitLoadFromSwiftError(I); 3594 } 3595 3596 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3597 if (Alloca->isSwiftError()) 3598 return visitLoadFromSwiftError(I); 3599 } 3600 } 3601 3602 SDValue Ptr = getValue(SV); 3603 3604 Type *Ty = I.getType(); 3605 3606 bool isVolatile = I.isVolatile(); 3607 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3608 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3609 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3610 unsigned Alignment = I.getAlignment(); 3611 3612 AAMDNodes AAInfo; 3613 I.getAAMetadata(AAInfo); 3614 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3615 3616 SmallVector<EVT, 4> ValueVTs; 3617 SmallVector<uint64_t, 4> Offsets; 3618 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3619 unsigned NumValues = ValueVTs.size(); 3620 if (NumValues == 0) 3621 return; 3622 3623 SDValue Root; 3624 bool ConstantMemory = false; 3625 if (isVolatile || NumValues > MaxParallelChains) 3626 // Serialize volatile loads with other side effects. 3627 Root = getRoot(); 3628 else if (AA && AA->pointsToConstantMemory(MemoryLocation( 3629 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) { 3630 // Do not serialize (non-volatile) loads of constant memory with anything. 3631 Root = DAG.getEntryNode(); 3632 ConstantMemory = true; 3633 } else { 3634 // Do not serialize non-volatile loads against each other. 3635 Root = DAG.getRoot(); 3636 } 3637 3638 SDLoc dl = getCurSDLoc(); 3639 3640 if (isVolatile) 3641 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3642 3643 // An aggregate load cannot wrap around the address space, so offsets to its 3644 // parts don't wrap either. 3645 SDNodeFlags Flags; 3646 Flags.setNoUnsignedWrap(true); 3647 3648 SmallVector<SDValue, 4> Values(NumValues); 3649 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3650 EVT PtrVT = Ptr.getValueType(); 3651 unsigned ChainI = 0; 3652 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3653 // Serializing loads here may result in excessive register pressure, and 3654 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3655 // could recover a bit by hoisting nodes upward in the chain by recognizing 3656 // they are side-effect free or do not alias. The optimizer should really 3657 // avoid this case by converting large object/array copies to llvm.memcpy 3658 // (MaxParallelChains should always remain as failsafe). 3659 if (ChainI == MaxParallelChains) { 3660 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3661 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3662 makeArrayRef(Chains.data(), ChainI)); 3663 Root = Chain; 3664 ChainI = 0; 3665 } 3666 SDValue A = DAG.getNode(ISD::ADD, dl, 3667 PtrVT, Ptr, 3668 DAG.getConstant(Offsets[i], dl, PtrVT), 3669 Flags); 3670 auto MMOFlags = MachineMemOperand::MONone; 3671 if (isVolatile) 3672 MMOFlags |= MachineMemOperand::MOVolatile; 3673 if (isNonTemporal) 3674 MMOFlags |= MachineMemOperand::MONonTemporal; 3675 if (isInvariant) 3676 MMOFlags |= MachineMemOperand::MOInvariant; 3677 if (isDereferenceable) 3678 MMOFlags |= MachineMemOperand::MODereferenceable; 3679 MMOFlags |= TLI.getMMOFlags(I); 3680 3681 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3682 MachinePointerInfo(SV, Offsets[i]), Alignment, 3683 MMOFlags, AAInfo, Ranges); 3684 3685 Values[i] = L; 3686 Chains[ChainI] = L.getValue(1); 3687 } 3688 3689 if (!ConstantMemory) { 3690 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3691 makeArrayRef(Chains.data(), ChainI)); 3692 if (isVolatile) 3693 DAG.setRoot(Chain); 3694 else 3695 PendingLoads.push_back(Chain); 3696 } 3697 3698 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3699 DAG.getVTList(ValueVTs), Values)); 3700 } 3701 3702 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3703 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3704 "call visitStoreToSwiftError when backend supports swifterror"); 3705 3706 SmallVector<EVT, 4> ValueVTs; 3707 SmallVector<uint64_t, 4> Offsets; 3708 const Value *SrcV = I.getOperand(0); 3709 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3710 SrcV->getType(), ValueVTs, &Offsets); 3711 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3712 "expect a single EVT for swifterror"); 3713 3714 SDValue Src = getValue(SrcV); 3715 // Create a virtual register, then update the virtual register. 3716 unsigned VReg; bool CreatedVReg; 3717 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3718 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3719 // Chain can be getRoot or getControlRoot. 3720 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3721 SDValue(Src.getNode(), Src.getResNo())); 3722 DAG.setRoot(CopyNode); 3723 if (CreatedVReg) 3724 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3725 } 3726 3727 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3728 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3729 "call visitLoadFromSwiftError when backend supports swifterror"); 3730 3731 assert(!I.isVolatile() && 3732 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3733 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3734 "Support volatile, non temporal, invariant for load_from_swift_error"); 3735 3736 const Value *SV = I.getOperand(0); 3737 Type *Ty = I.getType(); 3738 AAMDNodes AAInfo; 3739 I.getAAMetadata(AAInfo); 3740 assert((!AA || !AA->pointsToConstantMemory(MemoryLocation( 3741 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) && 3742 "load_from_swift_error should not be constant memory"); 3743 3744 SmallVector<EVT, 4> ValueVTs; 3745 SmallVector<uint64_t, 4> Offsets; 3746 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3747 ValueVTs, &Offsets); 3748 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3749 "expect a single EVT for swifterror"); 3750 3751 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3752 SDValue L = DAG.getCopyFromReg( 3753 getRoot(), getCurSDLoc(), 3754 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3755 ValueVTs[0]); 3756 3757 setValue(&I, L); 3758 } 3759 3760 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3761 if (I.isAtomic()) 3762 return visitAtomicStore(I); 3763 3764 const Value *SrcV = I.getOperand(0); 3765 const Value *PtrV = I.getOperand(1); 3766 3767 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3768 if (TLI.supportSwiftError()) { 3769 // Swifterror values can come from either a function parameter with 3770 // swifterror attribute or an alloca with swifterror attribute. 3771 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3772 if (Arg->hasSwiftErrorAttr()) 3773 return visitStoreToSwiftError(I); 3774 } 3775 3776 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3777 if (Alloca->isSwiftError()) 3778 return visitStoreToSwiftError(I); 3779 } 3780 } 3781 3782 SmallVector<EVT, 4> ValueVTs; 3783 SmallVector<uint64_t, 4> Offsets; 3784 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3785 SrcV->getType(), ValueVTs, &Offsets); 3786 unsigned NumValues = ValueVTs.size(); 3787 if (NumValues == 0) 3788 return; 3789 3790 // Get the lowered operands. Note that we do this after 3791 // checking if NumResults is zero, because with zero results 3792 // the operands won't have values in the map. 3793 SDValue Src = getValue(SrcV); 3794 SDValue Ptr = getValue(PtrV); 3795 3796 SDValue Root = getRoot(); 3797 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3798 SDLoc dl = getCurSDLoc(); 3799 EVT PtrVT = Ptr.getValueType(); 3800 unsigned Alignment = I.getAlignment(); 3801 AAMDNodes AAInfo; 3802 I.getAAMetadata(AAInfo); 3803 3804 auto MMOFlags = MachineMemOperand::MONone; 3805 if (I.isVolatile()) 3806 MMOFlags |= MachineMemOperand::MOVolatile; 3807 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3808 MMOFlags |= MachineMemOperand::MONonTemporal; 3809 MMOFlags |= TLI.getMMOFlags(I); 3810 3811 // An aggregate load cannot wrap around the address space, so offsets to its 3812 // parts don't wrap either. 3813 SDNodeFlags Flags; 3814 Flags.setNoUnsignedWrap(true); 3815 3816 unsigned ChainI = 0; 3817 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3818 // See visitLoad comments. 3819 if (ChainI == MaxParallelChains) { 3820 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3821 makeArrayRef(Chains.data(), ChainI)); 3822 Root = Chain; 3823 ChainI = 0; 3824 } 3825 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3826 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3827 SDValue St = DAG.getStore( 3828 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3829 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3830 Chains[ChainI] = St; 3831 } 3832 3833 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3834 makeArrayRef(Chains.data(), ChainI)); 3835 DAG.setRoot(StoreNode); 3836 } 3837 3838 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3839 bool IsCompressing) { 3840 SDLoc sdl = getCurSDLoc(); 3841 3842 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3843 unsigned& Alignment) { 3844 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3845 Src0 = I.getArgOperand(0); 3846 Ptr = I.getArgOperand(1); 3847 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3848 Mask = I.getArgOperand(3); 3849 }; 3850 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3851 unsigned& Alignment) { 3852 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3853 Src0 = I.getArgOperand(0); 3854 Ptr = I.getArgOperand(1); 3855 Mask = I.getArgOperand(2); 3856 Alignment = 0; 3857 }; 3858 3859 Value *PtrOperand, *MaskOperand, *Src0Operand; 3860 unsigned Alignment; 3861 if (IsCompressing) 3862 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3863 else 3864 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3865 3866 SDValue Ptr = getValue(PtrOperand); 3867 SDValue Src0 = getValue(Src0Operand); 3868 SDValue Mask = getValue(MaskOperand); 3869 3870 EVT VT = Src0.getValueType(); 3871 if (!Alignment) 3872 Alignment = DAG.getEVTAlignment(VT); 3873 3874 AAMDNodes AAInfo; 3875 I.getAAMetadata(AAInfo); 3876 3877 MachineMemOperand *MMO = 3878 DAG.getMachineFunction(). 3879 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3880 MachineMemOperand::MOStore, VT.getStoreSize(), 3881 Alignment, AAInfo); 3882 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3883 MMO, false /* Truncating */, 3884 IsCompressing); 3885 DAG.setRoot(StoreNode); 3886 setValue(&I, StoreNode); 3887 } 3888 3889 // Get a uniform base for the Gather/Scatter intrinsic. 3890 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3891 // We try to represent it as a base pointer + vector of indices. 3892 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3893 // The first operand of the GEP may be a single pointer or a vector of pointers 3894 // Example: 3895 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3896 // or 3897 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3898 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3899 // 3900 // When the first GEP operand is a single pointer - it is the uniform base we 3901 // are looking for. If first operand of the GEP is a splat vector - we 3902 // extract the splat value and use it as a uniform base. 3903 // In all other cases the function returns 'false'. 3904 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3905 SDValue &Scale, SelectionDAGBuilder* SDB) { 3906 SelectionDAG& DAG = SDB->DAG; 3907 LLVMContext &Context = *DAG.getContext(); 3908 3909 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3910 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3911 if (!GEP) 3912 return false; 3913 3914 const Value *GEPPtr = GEP->getPointerOperand(); 3915 if (!GEPPtr->getType()->isVectorTy()) 3916 Ptr = GEPPtr; 3917 else if (!(Ptr = getSplatValue(GEPPtr))) 3918 return false; 3919 3920 unsigned FinalIndex = GEP->getNumOperands() - 1; 3921 Value *IndexVal = GEP->getOperand(FinalIndex); 3922 3923 // Ensure all the other indices are 0. 3924 for (unsigned i = 1; i < FinalIndex; ++i) { 3925 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 3926 if (!C || !C->isZero()) 3927 return false; 3928 } 3929 3930 // The operands of the GEP may be defined in another basic block. 3931 // In this case we'll not find nodes for the operands. 3932 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 3933 return false; 3934 3935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3936 const DataLayout &DL = DAG.getDataLayout(); 3937 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 3938 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 3939 Base = SDB->getValue(Ptr); 3940 Index = SDB->getValue(IndexVal); 3941 3942 if (!Index.getValueType().isVector()) { 3943 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 3944 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 3945 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 3946 } 3947 return true; 3948 } 3949 3950 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 3951 SDLoc sdl = getCurSDLoc(); 3952 3953 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 3954 const Value *Ptr = I.getArgOperand(1); 3955 SDValue Src0 = getValue(I.getArgOperand(0)); 3956 SDValue Mask = getValue(I.getArgOperand(3)); 3957 EVT VT = Src0.getValueType(); 3958 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3959 if (!Alignment) 3960 Alignment = DAG.getEVTAlignment(VT); 3961 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3962 3963 AAMDNodes AAInfo; 3964 I.getAAMetadata(AAInfo); 3965 3966 SDValue Base; 3967 SDValue Index; 3968 SDValue Scale; 3969 const Value *BasePtr = Ptr; 3970 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 3971 3972 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 3973 MachineMemOperand *MMO = DAG.getMachineFunction(). 3974 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 3975 MachineMemOperand::MOStore, VT.getStoreSize(), 3976 Alignment, AAInfo); 3977 if (!UniformBase) { 3978 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 3979 Index = getValue(Ptr); 3980 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 3981 } 3982 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 3983 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 3984 Ops, MMO); 3985 DAG.setRoot(Scatter); 3986 setValue(&I, Scatter); 3987 } 3988 3989 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 3990 SDLoc sdl = getCurSDLoc(); 3991 3992 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3993 unsigned& Alignment) { 3994 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 3995 Ptr = I.getArgOperand(0); 3996 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 3997 Mask = I.getArgOperand(2); 3998 Src0 = I.getArgOperand(3); 3999 }; 4000 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4001 unsigned& Alignment) { 4002 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4003 Ptr = I.getArgOperand(0); 4004 Alignment = 0; 4005 Mask = I.getArgOperand(1); 4006 Src0 = I.getArgOperand(2); 4007 }; 4008 4009 Value *PtrOperand, *MaskOperand, *Src0Operand; 4010 unsigned Alignment; 4011 if (IsExpanding) 4012 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4013 else 4014 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4015 4016 SDValue Ptr = getValue(PtrOperand); 4017 SDValue Src0 = getValue(Src0Operand); 4018 SDValue Mask = getValue(MaskOperand); 4019 4020 EVT VT = Src0.getValueType(); 4021 if (!Alignment) 4022 Alignment = DAG.getEVTAlignment(VT); 4023 4024 AAMDNodes AAInfo; 4025 I.getAAMetadata(AAInfo); 4026 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4027 4028 // Do not serialize masked loads of constant memory with anything. 4029 bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation( 4030 PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo)); 4031 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4032 4033 MachineMemOperand *MMO = 4034 DAG.getMachineFunction(). 4035 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4036 MachineMemOperand::MOLoad, VT.getStoreSize(), 4037 Alignment, AAInfo, Ranges); 4038 4039 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4040 ISD::NON_EXTLOAD, IsExpanding); 4041 if (AddToChain) { 4042 SDValue OutChain = Load.getValue(1); 4043 DAG.setRoot(OutChain); 4044 } 4045 setValue(&I, Load); 4046 } 4047 4048 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4049 SDLoc sdl = getCurSDLoc(); 4050 4051 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4052 const Value *Ptr = I.getArgOperand(0); 4053 SDValue Src0 = getValue(I.getArgOperand(3)); 4054 SDValue Mask = getValue(I.getArgOperand(2)); 4055 4056 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4057 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4058 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4059 if (!Alignment) 4060 Alignment = DAG.getEVTAlignment(VT); 4061 4062 AAMDNodes AAInfo; 4063 I.getAAMetadata(AAInfo); 4064 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4065 4066 SDValue Root = DAG.getRoot(); 4067 SDValue Base; 4068 SDValue Index; 4069 SDValue Scale; 4070 const Value *BasePtr = Ptr; 4071 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4072 bool ConstantMemory = false; 4073 if (UniformBase && 4074 AA && AA->pointsToConstantMemory(MemoryLocation( 4075 BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()), 4076 AAInfo))) { 4077 // Do not serialize (non-volatile) loads of constant memory with anything. 4078 Root = DAG.getEntryNode(); 4079 ConstantMemory = true; 4080 } 4081 4082 MachineMemOperand *MMO = 4083 DAG.getMachineFunction(). 4084 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4085 MachineMemOperand::MOLoad, VT.getStoreSize(), 4086 Alignment, AAInfo, Ranges); 4087 4088 if (!UniformBase) { 4089 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4090 Index = getValue(Ptr); 4091 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4092 } 4093 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4094 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4095 Ops, MMO); 4096 4097 SDValue OutChain = Gather.getValue(1); 4098 if (!ConstantMemory) 4099 PendingLoads.push_back(OutChain); 4100 setValue(&I, Gather); 4101 } 4102 4103 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4104 SDLoc dl = getCurSDLoc(); 4105 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4106 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4107 SyncScope::ID SSID = I.getSyncScopeID(); 4108 4109 SDValue InChain = getRoot(); 4110 4111 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4112 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4113 SDValue L = DAG.getAtomicCmpSwap( 4114 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4115 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4116 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4117 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4118 4119 SDValue OutChain = L.getValue(2); 4120 4121 setValue(&I, L); 4122 DAG.setRoot(OutChain); 4123 } 4124 4125 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4126 SDLoc dl = getCurSDLoc(); 4127 ISD::NodeType NT; 4128 switch (I.getOperation()) { 4129 default: llvm_unreachable("Unknown atomicrmw operation"); 4130 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4131 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4132 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4133 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4134 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4135 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4136 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4137 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4138 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4139 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4140 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4141 } 4142 AtomicOrdering Order = I.getOrdering(); 4143 SyncScope::ID SSID = I.getSyncScopeID(); 4144 4145 SDValue InChain = getRoot(); 4146 4147 SDValue L = 4148 DAG.getAtomic(NT, dl, 4149 getValue(I.getValOperand()).getSimpleValueType(), 4150 InChain, 4151 getValue(I.getPointerOperand()), 4152 getValue(I.getValOperand()), 4153 I.getPointerOperand(), 4154 /* Alignment=*/ 0, Order, SSID); 4155 4156 SDValue OutChain = L.getValue(1); 4157 4158 setValue(&I, L); 4159 DAG.setRoot(OutChain); 4160 } 4161 4162 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4163 SDLoc dl = getCurSDLoc(); 4164 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4165 SDValue Ops[3]; 4166 Ops[0] = getRoot(); 4167 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4168 TLI.getFenceOperandTy(DAG.getDataLayout())); 4169 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4170 TLI.getFenceOperandTy(DAG.getDataLayout())); 4171 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4172 } 4173 4174 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4175 SDLoc dl = getCurSDLoc(); 4176 AtomicOrdering Order = I.getOrdering(); 4177 SyncScope::ID SSID = I.getSyncScopeID(); 4178 4179 SDValue InChain = getRoot(); 4180 4181 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4182 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4183 4184 if (!TLI.supportsUnalignedAtomics() && 4185 I.getAlignment() < VT.getStoreSize()) 4186 report_fatal_error("Cannot generate unaligned atomic load"); 4187 4188 MachineMemOperand *MMO = 4189 DAG.getMachineFunction(). 4190 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4191 MachineMemOperand::MOVolatile | 4192 MachineMemOperand::MOLoad, 4193 VT.getStoreSize(), 4194 I.getAlignment() ? I.getAlignment() : 4195 DAG.getEVTAlignment(VT), 4196 AAMDNodes(), nullptr, SSID, Order); 4197 4198 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4199 SDValue L = 4200 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4201 getValue(I.getPointerOperand()), MMO); 4202 4203 SDValue OutChain = L.getValue(1); 4204 4205 setValue(&I, L); 4206 DAG.setRoot(OutChain); 4207 } 4208 4209 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4210 SDLoc dl = getCurSDLoc(); 4211 4212 AtomicOrdering Order = I.getOrdering(); 4213 SyncScope::ID SSID = I.getSyncScopeID(); 4214 4215 SDValue InChain = getRoot(); 4216 4217 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4218 EVT VT = 4219 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4220 4221 if (I.getAlignment() < VT.getStoreSize()) 4222 report_fatal_error("Cannot generate unaligned atomic store"); 4223 4224 SDValue OutChain = 4225 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4226 InChain, 4227 getValue(I.getPointerOperand()), 4228 getValue(I.getValueOperand()), 4229 I.getPointerOperand(), I.getAlignment(), 4230 Order, SSID); 4231 4232 DAG.setRoot(OutChain); 4233 } 4234 4235 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4236 /// node. 4237 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4238 unsigned Intrinsic) { 4239 // Ignore the callsite's attributes. A specific call site may be marked with 4240 // readnone, but the lowering code will expect the chain based on the 4241 // definition. 4242 const Function *F = I.getCalledFunction(); 4243 bool HasChain = !F->doesNotAccessMemory(); 4244 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4245 4246 // Build the operand list. 4247 SmallVector<SDValue, 8> Ops; 4248 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4249 if (OnlyLoad) { 4250 // We don't need to serialize loads against other loads. 4251 Ops.push_back(DAG.getRoot()); 4252 } else { 4253 Ops.push_back(getRoot()); 4254 } 4255 } 4256 4257 // Info is set by getTgtMemInstrinsic 4258 TargetLowering::IntrinsicInfo Info; 4259 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4260 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4261 DAG.getMachineFunction(), 4262 Intrinsic); 4263 4264 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4265 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4266 Info.opc == ISD::INTRINSIC_W_CHAIN) 4267 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4268 TLI.getPointerTy(DAG.getDataLayout()))); 4269 4270 // Add all operands of the call to the operand list. 4271 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4272 SDValue Op = getValue(I.getArgOperand(i)); 4273 Ops.push_back(Op); 4274 } 4275 4276 SmallVector<EVT, 4> ValueVTs; 4277 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4278 4279 if (HasChain) 4280 ValueVTs.push_back(MVT::Other); 4281 4282 SDVTList VTs = DAG.getVTList(ValueVTs); 4283 4284 // Create the node. 4285 SDValue Result; 4286 if (IsTgtIntrinsic) { 4287 // This is target intrinsic that touches memory 4288 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4289 Ops, Info.memVT, 4290 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4291 Info.flags, Info.size); 4292 } else if (!HasChain) { 4293 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4294 } else if (!I.getType()->isVoidTy()) { 4295 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4296 } else { 4297 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4298 } 4299 4300 if (HasChain) { 4301 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4302 if (OnlyLoad) 4303 PendingLoads.push_back(Chain); 4304 else 4305 DAG.setRoot(Chain); 4306 } 4307 4308 if (!I.getType()->isVoidTy()) { 4309 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4310 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4311 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4312 } else 4313 Result = lowerRangeToAssertZExt(DAG, I, Result); 4314 4315 setValue(&I, Result); 4316 } 4317 } 4318 4319 /// GetSignificand - Get the significand and build it into a floating-point 4320 /// number with exponent of 1: 4321 /// 4322 /// Op = (Op & 0x007fffff) | 0x3f800000; 4323 /// 4324 /// where Op is the hexadecimal representation of floating point value. 4325 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4326 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4327 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4328 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4329 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4330 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4331 } 4332 4333 /// GetExponent - Get the exponent: 4334 /// 4335 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4336 /// 4337 /// where Op is the hexadecimal representation of floating point value. 4338 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4339 const TargetLowering &TLI, const SDLoc &dl) { 4340 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4341 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4342 SDValue t1 = DAG.getNode( 4343 ISD::SRL, dl, MVT::i32, t0, 4344 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4345 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4346 DAG.getConstant(127, dl, MVT::i32)); 4347 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4348 } 4349 4350 /// getF32Constant - Get 32-bit floating point constant. 4351 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4352 const SDLoc &dl) { 4353 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4354 MVT::f32); 4355 } 4356 4357 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4358 SelectionDAG &DAG) { 4359 // TODO: What fast-math-flags should be set on the floating-point nodes? 4360 4361 // IntegerPartOfX = ((int32_t)(t0); 4362 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4363 4364 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4365 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4366 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4367 4368 // IntegerPartOfX <<= 23; 4369 IntegerPartOfX = DAG.getNode( 4370 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4371 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4372 DAG.getDataLayout()))); 4373 4374 SDValue TwoToFractionalPartOfX; 4375 if (LimitFloatPrecision <= 6) { 4376 // For floating-point precision of 6: 4377 // 4378 // TwoToFractionalPartOfX = 4379 // 0.997535578f + 4380 // (0.735607626f + 0.252464424f * x) * x; 4381 // 4382 // error 0.0144103317, which is 6 bits 4383 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4384 getF32Constant(DAG, 0x3e814304, dl)); 4385 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4386 getF32Constant(DAG, 0x3f3c50c8, dl)); 4387 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4388 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4389 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4390 } else if (LimitFloatPrecision <= 12) { 4391 // For floating-point precision of 12: 4392 // 4393 // TwoToFractionalPartOfX = 4394 // 0.999892986f + 4395 // (0.696457318f + 4396 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4397 // 4398 // error 0.000107046256, which is 13 to 14 bits 4399 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4400 getF32Constant(DAG, 0x3da235e3, dl)); 4401 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4402 getF32Constant(DAG, 0x3e65b8f3, dl)); 4403 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4404 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4405 getF32Constant(DAG, 0x3f324b07, dl)); 4406 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4407 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4408 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4409 } else { // LimitFloatPrecision <= 18 4410 // For floating-point precision of 18: 4411 // 4412 // TwoToFractionalPartOfX = 4413 // 0.999999982f + 4414 // (0.693148872f + 4415 // (0.240227044f + 4416 // (0.554906021e-1f + 4417 // (0.961591928e-2f + 4418 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4419 // error 2.47208000*10^(-7), which is better than 18 bits 4420 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4421 getF32Constant(DAG, 0x3924b03e, dl)); 4422 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4423 getF32Constant(DAG, 0x3ab24b87, dl)); 4424 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4425 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4426 getF32Constant(DAG, 0x3c1d8c17, dl)); 4427 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4428 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4429 getF32Constant(DAG, 0x3d634a1d, dl)); 4430 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4431 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4432 getF32Constant(DAG, 0x3e75fe14, dl)); 4433 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4434 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4435 getF32Constant(DAG, 0x3f317234, dl)); 4436 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4437 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4438 getF32Constant(DAG, 0x3f800000, dl)); 4439 } 4440 4441 // Add the exponent into the result in integer domain. 4442 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4443 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4444 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4445 } 4446 4447 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4448 /// limited-precision mode. 4449 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4450 const TargetLowering &TLI) { 4451 if (Op.getValueType() == MVT::f32 && 4452 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4453 4454 // Put the exponent in the right bit position for later addition to the 4455 // final result: 4456 // 4457 // #define LOG2OFe 1.4426950f 4458 // t0 = Op * LOG2OFe 4459 4460 // TODO: What fast-math-flags should be set here? 4461 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4462 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4463 return getLimitedPrecisionExp2(t0, dl, DAG); 4464 } 4465 4466 // No special expansion. 4467 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4468 } 4469 4470 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4471 /// limited-precision mode. 4472 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4473 const TargetLowering &TLI) { 4474 // TODO: What fast-math-flags should be set on the floating-point nodes? 4475 4476 if (Op.getValueType() == MVT::f32 && 4477 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4478 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4479 4480 // Scale the exponent by log(2) [0.69314718f]. 4481 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4482 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4483 getF32Constant(DAG, 0x3f317218, dl)); 4484 4485 // Get the significand and build it into a floating-point number with 4486 // exponent of 1. 4487 SDValue X = GetSignificand(DAG, Op1, dl); 4488 4489 SDValue LogOfMantissa; 4490 if (LimitFloatPrecision <= 6) { 4491 // For floating-point precision of 6: 4492 // 4493 // LogofMantissa = 4494 // -1.1609546f + 4495 // (1.4034025f - 0.23903021f * x) * x; 4496 // 4497 // error 0.0034276066, which is better than 8 bits 4498 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4499 getF32Constant(DAG, 0xbe74c456, dl)); 4500 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4501 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4502 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4503 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4504 getF32Constant(DAG, 0x3f949a29, dl)); 4505 } else if (LimitFloatPrecision <= 12) { 4506 // For floating-point precision of 12: 4507 // 4508 // LogOfMantissa = 4509 // -1.7417939f + 4510 // (2.8212026f + 4511 // (-1.4699568f + 4512 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4513 // 4514 // error 0.000061011436, which is 14 bits 4515 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4516 getF32Constant(DAG, 0xbd67b6d6, dl)); 4517 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4518 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4519 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4520 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4521 getF32Constant(DAG, 0x3fbc278b, dl)); 4522 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4523 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4524 getF32Constant(DAG, 0x40348e95, dl)); 4525 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4526 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4527 getF32Constant(DAG, 0x3fdef31a, dl)); 4528 } else { // LimitFloatPrecision <= 18 4529 // For floating-point precision of 18: 4530 // 4531 // LogOfMantissa = 4532 // -2.1072184f + 4533 // (4.2372794f + 4534 // (-3.7029485f + 4535 // (2.2781945f + 4536 // (-0.87823314f + 4537 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4538 // 4539 // error 0.0000023660568, which is better than 18 bits 4540 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4541 getF32Constant(DAG, 0xbc91e5ac, dl)); 4542 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4543 getF32Constant(DAG, 0x3e4350aa, dl)); 4544 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4545 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4546 getF32Constant(DAG, 0x3f60d3e3, dl)); 4547 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4548 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4549 getF32Constant(DAG, 0x4011cdf0, dl)); 4550 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4551 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4552 getF32Constant(DAG, 0x406cfd1c, dl)); 4553 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4554 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4555 getF32Constant(DAG, 0x408797cb, dl)); 4556 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4557 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4558 getF32Constant(DAG, 0x4006dcab, dl)); 4559 } 4560 4561 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4562 } 4563 4564 // No special expansion. 4565 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4566 } 4567 4568 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4569 /// limited-precision mode. 4570 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4571 const TargetLowering &TLI) { 4572 // TODO: What fast-math-flags should be set on the floating-point nodes? 4573 4574 if (Op.getValueType() == MVT::f32 && 4575 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4576 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4577 4578 // Get the exponent. 4579 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4580 4581 // Get the significand and build it into a floating-point number with 4582 // exponent of 1. 4583 SDValue X = GetSignificand(DAG, Op1, dl); 4584 4585 // Different possible minimax approximations of significand in 4586 // floating-point for various degrees of accuracy over [1,2]. 4587 SDValue Log2ofMantissa; 4588 if (LimitFloatPrecision <= 6) { 4589 // For floating-point precision of 6: 4590 // 4591 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4592 // 4593 // error 0.0049451742, which is more than 7 bits 4594 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4595 getF32Constant(DAG, 0xbeb08fe0, dl)); 4596 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4597 getF32Constant(DAG, 0x40019463, dl)); 4598 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4599 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4600 getF32Constant(DAG, 0x3fd6633d, dl)); 4601 } else if (LimitFloatPrecision <= 12) { 4602 // For floating-point precision of 12: 4603 // 4604 // Log2ofMantissa = 4605 // -2.51285454f + 4606 // (4.07009056f + 4607 // (-2.12067489f + 4608 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4609 // 4610 // error 0.0000876136000, which is better than 13 bits 4611 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4612 getF32Constant(DAG, 0xbda7262e, dl)); 4613 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4614 getF32Constant(DAG, 0x3f25280b, dl)); 4615 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4616 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4617 getF32Constant(DAG, 0x4007b923, dl)); 4618 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4619 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4620 getF32Constant(DAG, 0x40823e2f, dl)); 4621 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4622 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4623 getF32Constant(DAG, 0x4020d29c, dl)); 4624 } else { // LimitFloatPrecision <= 18 4625 // For floating-point precision of 18: 4626 // 4627 // Log2ofMantissa = 4628 // -3.0400495f + 4629 // (6.1129976f + 4630 // (-5.3420409f + 4631 // (3.2865683f + 4632 // (-1.2669343f + 4633 // (0.27515199f - 4634 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4635 // 4636 // error 0.0000018516, which is better than 18 bits 4637 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4638 getF32Constant(DAG, 0xbcd2769e, dl)); 4639 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4640 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4641 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4642 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4643 getF32Constant(DAG, 0x3fa22ae7, dl)); 4644 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4645 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4646 getF32Constant(DAG, 0x40525723, dl)); 4647 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4648 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4649 getF32Constant(DAG, 0x40aaf200, dl)); 4650 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4651 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4652 getF32Constant(DAG, 0x40c39dad, dl)); 4653 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4654 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4655 getF32Constant(DAG, 0x4042902c, dl)); 4656 } 4657 4658 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4659 } 4660 4661 // No special expansion. 4662 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4663 } 4664 4665 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4666 /// limited-precision mode. 4667 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4668 const TargetLowering &TLI) { 4669 // TODO: What fast-math-flags should be set on the floating-point nodes? 4670 4671 if (Op.getValueType() == MVT::f32 && 4672 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4673 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4674 4675 // Scale the exponent by log10(2) [0.30102999f]. 4676 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4677 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4678 getF32Constant(DAG, 0x3e9a209a, dl)); 4679 4680 // Get the significand and build it into a floating-point number with 4681 // exponent of 1. 4682 SDValue X = GetSignificand(DAG, Op1, dl); 4683 4684 SDValue Log10ofMantissa; 4685 if (LimitFloatPrecision <= 6) { 4686 // For floating-point precision of 6: 4687 // 4688 // Log10ofMantissa = 4689 // -0.50419619f + 4690 // (0.60948995f - 0.10380950f * x) * x; 4691 // 4692 // error 0.0014886165, which is 6 bits 4693 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4694 getF32Constant(DAG, 0xbdd49a13, dl)); 4695 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4696 getF32Constant(DAG, 0x3f1c0789, dl)); 4697 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4698 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4699 getF32Constant(DAG, 0x3f011300, dl)); 4700 } else if (LimitFloatPrecision <= 12) { 4701 // For floating-point precision of 12: 4702 // 4703 // Log10ofMantissa = 4704 // -0.64831180f + 4705 // (0.91751397f + 4706 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4707 // 4708 // error 0.00019228036, which is better than 12 bits 4709 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4710 getF32Constant(DAG, 0x3d431f31, dl)); 4711 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4712 getF32Constant(DAG, 0x3ea21fb2, dl)); 4713 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4714 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4715 getF32Constant(DAG, 0x3f6ae232, dl)); 4716 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4717 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4718 getF32Constant(DAG, 0x3f25f7c3, dl)); 4719 } else { // LimitFloatPrecision <= 18 4720 // For floating-point precision of 18: 4721 // 4722 // Log10ofMantissa = 4723 // -0.84299375f + 4724 // (1.5327582f + 4725 // (-1.0688956f + 4726 // (0.49102474f + 4727 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4728 // 4729 // error 0.0000037995730, which is better than 18 bits 4730 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4731 getF32Constant(DAG, 0x3c5d51ce, dl)); 4732 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4733 getF32Constant(DAG, 0x3e00685a, dl)); 4734 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4735 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4736 getF32Constant(DAG, 0x3efb6798, dl)); 4737 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4738 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4739 getF32Constant(DAG, 0x3f88d192, dl)); 4740 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4741 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4742 getF32Constant(DAG, 0x3fc4316c, dl)); 4743 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4744 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4745 getF32Constant(DAG, 0x3f57ce70, dl)); 4746 } 4747 4748 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4749 } 4750 4751 // No special expansion. 4752 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4753 } 4754 4755 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4756 /// limited-precision mode. 4757 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4758 const TargetLowering &TLI) { 4759 if (Op.getValueType() == MVT::f32 && 4760 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4761 return getLimitedPrecisionExp2(Op, dl, DAG); 4762 4763 // No special expansion. 4764 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4765 } 4766 4767 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4768 /// limited-precision mode with x == 10.0f. 4769 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4770 SelectionDAG &DAG, const TargetLowering &TLI) { 4771 bool IsExp10 = false; 4772 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4773 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4774 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4775 APFloat Ten(10.0f); 4776 IsExp10 = LHSC->isExactlyValue(Ten); 4777 } 4778 } 4779 4780 // TODO: What fast-math-flags should be set on the FMUL node? 4781 if (IsExp10) { 4782 // Put the exponent in the right bit position for later addition to the 4783 // final result: 4784 // 4785 // #define LOG2OF10 3.3219281f 4786 // t0 = Op * LOG2OF10; 4787 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4788 getF32Constant(DAG, 0x40549a78, dl)); 4789 return getLimitedPrecisionExp2(t0, dl, DAG); 4790 } 4791 4792 // No special expansion. 4793 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4794 } 4795 4796 /// ExpandPowI - Expand a llvm.powi intrinsic. 4797 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4798 SelectionDAG &DAG) { 4799 // If RHS is a constant, we can expand this out to a multiplication tree, 4800 // otherwise we end up lowering to a call to __powidf2 (for example). When 4801 // optimizing for size, we only want to do this if the expansion would produce 4802 // a small number of multiplies, otherwise we do the full expansion. 4803 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4804 // Get the exponent as a positive value. 4805 unsigned Val = RHSC->getSExtValue(); 4806 if ((int)Val < 0) Val = -Val; 4807 4808 // powi(x, 0) -> 1.0 4809 if (Val == 0) 4810 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4811 4812 const Function &F = DAG.getMachineFunction().getFunction(); 4813 if (!F.optForSize() || 4814 // If optimizing for size, don't insert too many multiplies. 4815 // This inserts up to 5 multiplies. 4816 countPopulation(Val) + Log2_32(Val) < 7) { 4817 // We use the simple binary decomposition method to generate the multiply 4818 // sequence. There are more optimal ways to do this (for example, 4819 // powi(x,15) generates one more multiply than it should), but this has 4820 // the benefit of being both really simple and much better than a libcall. 4821 SDValue Res; // Logically starts equal to 1.0 4822 SDValue CurSquare = LHS; 4823 // TODO: Intrinsics should have fast-math-flags that propagate to these 4824 // nodes. 4825 while (Val) { 4826 if (Val & 1) { 4827 if (Res.getNode()) 4828 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4829 else 4830 Res = CurSquare; // 1.0*CurSquare. 4831 } 4832 4833 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4834 CurSquare, CurSquare); 4835 Val >>= 1; 4836 } 4837 4838 // If the original was negative, invert the result, producing 1/(x*x*x). 4839 if (RHSC->getSExtValue() < 0) 4840 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4841 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4842 return Res; 4843 } 4844 } 4845 4846 // Otherwise, expand to a libcall. 4847 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4848 } 4849 4850 // getUnderlyingArgReg - Find underlying register used for a truncated or 4851 // bitcasted argument. 4852 static unsigned getUnderlyingArgReg(const SDValue &N) { 4853 switch (N.getOpcode()) { 4854 case ISD::CopyFromReg: 4855 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4856 case ISD::BITCAST: 4857 case ISD::AssertZext: 4858 case ISD::AssertSext: 4859 case ISD::TRUNCATE: 4860 return getUnderlyingArgReg(N.getOperand(0)); 4861 default: 4862 return 0; 4863 } 4864 } 4865 4866 /// If the DbgValueInst is a dbg_value of a function argument, create the 4867 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4868 /// instruction selection, they will be inserted to the entry BB. 4869 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4870 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4871 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4872 const Argument *Arg = dyn_cast<Argument>(V); 4873 if (!Arg) 4874 return false; 4875 4876 MachineFunction &MF = DAG.getMachineFunction(); 4877 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4878 4879 bool IsIndirect = false; 4880 Optional<MachineOperand> Op; 4881 // Some arguments' frame index is recorded during argument lowering. 4882 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4883 if (FI != std::numeric_limits<int>::max()) 4884 Op = MachineOperand::CreateFI(FI); 4885 4886 if (!Op && N.getNode()) { 4887 unsigned Reg = getUnderlyingArgReg(N); 4888 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4889 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4890 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4891 if (PR) 4892 Reg = PR; 4893 } 4894 if (Reg) { 4895 Op = MachineOperand::CreateReg(Reg, false); 4896 IsIndirect = IsDbgDeclare; 4897 } 4898 } 4899 4900 if (!Op && N.getNode()) 4901 // Check if frame index is available. 4902 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4903 if (FrameIndexSDNode *FINode = 4904 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4905 Op = MachineOperand::CreateFI(FINode->getIndex()); 4906 4907 if (!Op) { 4908 // Check if ValueMap has reg number. 4909 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4910 if (VMI != FuncInfo.ValueMap.end()) { 4911 const auto &TLI = DAG.getTargetLoweringInfo(); 4912 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4913 V->getType(), isABIRegCopy(V)); 4914 unsigned NumRegs = 4915 std::accumulate(RFV.RegCount.begin(), RFV.RegCount.end(), 0); 4916 if (NumRegs > 1) { 4917 unsigned I = 0; 4918 unsigned Offset = 0; 4919 auto RegisterVT = RFV.RegVTs.begin(); 4920 for (auto RegCount : RFV.RegCount) { 4921 unsigned RegisterSize = (RegisterVT++)->getSizeInBits(); 4922 for (unsigned E = I + RegCount; I != E; ++I) { 4923 // The vregs are guaranteed to be allocated in sequence. 4924 Op = MachineOperand::CreateReg(VMI->second + I, false); 4925 auto FragmentExpr = DIExpression::createFragmentExpression( 4926 Expr, Offset, RegisterSize); 4927 if (!FragmentExpr) 4928 continue; 4929 FuncInfo.ArgDbgValues.push_back( 4930 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 4931 Op->getReg(), Variable, *FragmentExpr)); 4932 Offset += RegisterSize; 4933 } 4934 } 4935 return true; 4936 } 4937 Op = MachineOperand::CreateReg(VMI->second, false); 4938 IsIndirect = IsDbgDeclare; 4939 } 4940 } 4941 4942 if (!Op) 4943 return false; 4944 4945 assert(Variable->isValidLocationForIntrinsic(DL) && 4946 "Expected inlined-at fields to agree"); 4947 if (Op->isReg()) 4948 FuncInfo.ArgDbgValues.push_back( 4949 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 4950 Op->getReg(), Variable, Expr)); 4951 else 4952 FuncInfo.ArgDbgValues.push_back( 4953 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)) 4954 .add(*Op) 4955 .addImm(0) 4956 .addMetadata(Variable) 4957 .addMetadata(Expr)); 4958 4959 return true; 4960 } 4961 4962 /// Return the appropriate SDDbgValue based on N. 4963 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 4964 DILocalVariable *Variable, 4965 DIExpression *Expr, 4966 const DebugLoc &dl, 4967 unsigned DbgSDNodeOrder) { 4968 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 4969 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 4970 // stack slot locations as such instead of as indirectly addressed 4971 // locations. 4972 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl, 4973 DbgSDNodeOrder); 4974 } 4975 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl, 4976 DbgSDNodeOrder); 4977 } 4978 4979 // VisualStudio defines setjmp as _setjmp 4980 #if defined(_MSC_VER) && defined(setjmp) && \ 4981 !defined(setjmp_undefined_for_msvc) 4982 # pragma push_macro("setjmp") 4983 # undef setjmp 4984 # define setjmp_undefined_for_msvc 4985 #endif 4986 4987 /// Lower the call to the specified intrinsic function. If we want to emit this 4988 /// as a call to a named external function, return the name. Otherwise, lower it 4989 /// and return null. 4990 const char * 4991 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 4992 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4993 SDLoc sdl = getCurSDLoc(); 4994 DebugLoc dl = getCurDebugLoc(); 4995 SDValue Res; 4996 4997 switch (Intrinsic) { 4998 default: 4999 // By default, turn this into a target intrinsic node. 5000 visitTargetIntrinsic(I, Intrinsic); 5001 return nullptr; 5002 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5003 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5004 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5005 case Intrinsic::returnaddress: 5006 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5007 TLI.getPointerTy(DAG.getDataLayout()), 5008 getValue(I.getArgOperand(0)))); 5009 return nullptr; 5010 case Intrinsic::addressofreturnaddress: 5011 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5012 TLI.getPointerTy(DAG.getDataLayout()))); 5013 return nullptr; 5014 case Intrinsic::frameaddress: 5015 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5016 TLI.getPointerTy(DAG.getDataLayout()), 5017 getValue(I.getArgOperand(0)))); 5018 return nullptr; 5019 case Intrinsic::read_register: { 5020 Value *Reg = I.getArgOperand(0); 5021 SDValue Chain = getRoot(); 5022 SDValue RegName = 5023 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5024 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5025 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5026 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5027 setValue(&I, Res); 5028 DAG.setRoot(Res.getValue(1)); 5029 return nullptr; 5030 } 5031 case Intrinsic::write_register: { 5032 Value *Reg = I.getArgOperand(0); 5033 Value *RegValue = I.getArgOperand(1); 5034 SDValue Chain = getRoot(); 5035 SDValue RegName = 5036 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5037 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5038 RegName, getValue(RegValue))); 5039 return nullptr; 5040 } 5041 case Intrinsic::setjmp: 5042 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5043 case Intrinsic::longjmp: 5044 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5045 case Intrinsic::memcpy: { 5046 const auto &MCI = cast<MemCpyInst>(I); 5047 SDValue Op1 = getValue(I.getArgOperand(0)); 5048 SDValue Op2 = getValue(I.getArgOperand(1)); 5049 SDValue Op3 = getValue(I.getArgOperand(2)); 5050 unsigned Align = MCI.getAlignment(); 5051 if (!Align) 5052 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5053 bool isVol = MCI.isVolatile(); 5054 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5055 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5056 // node. 5057 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5058 false, isTC, 5059 MachinePointerInfo(I.getArgOperand(0)), 5060 MachinePointerInfo(I.getArgOperand(1))); 5061 updateDAGForMaybeTailCall(MC); 5062 return nullptr; 5063 } 5064 case Intrinsic::memset: { 5065 const auto &MSI = cast<MemSetInst>(I); 5066 SDValue Op1 = getValue(I.getArgOperand(0)); 5067 SDValue Op2 = getValue(I.getArgOperand(1)); 5068 SDValue Op3 = getValue(I.getArgOperand(2)); 5069 unsigned Align = MSI.getAlignment(); 5070 if (!Align) 5071 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment. 5072 bool isVol = MSI.isVolatile(); 5073 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5074 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5075 isTC, MachinePointerInfo(I.getArgOperand(0))); 5076 updateDAGForMaybeTailCall(MS); 5077 return nullptr; 5078 } 5079 case Intrinsic::memmove: { 5080 const auto &MMI = cast<MemMoveInst>(I); 5081 SDValue Op1 = getValue(I.getArgOperand(0)); 5082 SDValue Op2 = getValue(I.getArgOperand(1)); 5083 SDValue Op3 = getValue(I.getArgOperand(2)); 5084 unsigned Align = MMI.getAlignment(); 5085 if (!Align) 5086 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment. 5087 bool isVol = MMI.isVolatile(); 5088 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5089 // FIXME: Support passing different dest/src alignments to the memmove DAG 5090 // node. 5091 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5092 isTC, MachinePointerInfo(I.getArgOperand(0)), 5093 MachinePointerInfo(I.getArgOperand(1))); 5094 updateDAGForMaybeTailCall(MM); 5095 return nullptr; 5096 } 5097 case Intrinsic::memcpy_element_unordered_atomic: { 5098 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5099 SDValue Dst = getValue(MI.getRawDest()); 5100 SDValue Src = getValue(MI.getRawSource()); 5101 SDValue Length = getValue(MI.getLength()); 5102 5103 // Emit a library call. 5104 TargetLowering::ArgListTy Args; 5105 TargetLowering::ArgListEntry Entry; 5106 Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 5107 Entry.Node = Dst; 5108 Args.push_back(Entry); 5109 5110 Entry.Node = Src; 5111 Args.push_back(Entry); 5112 5113 Entry.Ty = MI.getLength()->getType(); 5114 Entry.Node = Length; 5115 Args.push_back(Entry); 5116 5117 uint64_t ElementSizeConstant = MI.getElementSizeInBytes(); 5118 RTLIB::Libcall LibraryCall = 5119 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant); 5120 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 5121 report_fatal_error("Unsupported element size"); 5122 5123 TargetLowering::CallLoweringInfo CLI(DAG); 5124 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5125 TLI.getLibcallCallingConv(LibraryCall), 5126 Type::getVoidTy(*DAG.getContext()), 5127 DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall), 5128 TLI.getPointerTy(DAG.getDataLayout())), 5129 std::move(Args)); 5130 5131 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 5132 DAG.setRoot(CallResult.second); 5133 return nullptr; 5134 } 5135 case Intrinsic::memmove_element_unordered_atomic: { 5136 auto &MI = cast<AtomicMemMoveInst>(I); 5137 SDValue Dst = getValue(MI.getRawDest()); 5138 SDValue Src = getValue(MI.getRawSource()); 5139 SDValue Length = getValue(MI.getLength()); 5140 5141 // Emit a library call. 5142 TargetLowering::ArgListTy Args; 5143 TargetLowering::ArgListEntry Entry; 5144 Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 5145 Entry.Node = Dst; 5146 Args.push_back(Entry); 5147 5148 Entry.Node = Src; 5149 Args.push_back(Entry); 5150 5151 Entry.Ty = MI.getLength()->getType(); 5152 Entry.Node = Length; 5153 Args.push_back(Entry); 5154 5155 uint64_t ElementSizeConstant = MI.getElementSizeInBytes(); 5156 RTLIB::Libcall LibraryCall = 5157 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant); 5158 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 5159 report_fatal_error("Unsupported element size"); 5160 5161 TargetLowering::CallLoweringInfo CLI(DAG); 5162 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5163 TLI.getLibcallCallingConv(LibraryCall), 5164 Type::getVoidTy(*DAG.getContext()), 5165 DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall), 5166 TLI.getPointerTy(DAG.getDataLayout())), 5167 std::move(Args)); 5168 5169 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 5170 DAG.setRoot(CallResult.second); 5171 return nullptr; 5172 } 5173 case Intrinsic::memset_element_unordered_atomic: { 5174 auto &MI = cast<AtomicMemSetInst>(I); 5175 SDValue Dst = getValue(MI.getRawDest()); 5176 SDValue Val = getValue(MI.getValue()); 5177 SDValue Length = getValue(MI.getLength()); 5178 5179 // Emit a library call. 5180 TargetLowering::ArgListTy Args; 5181 TargetLowering::ArgListEntry Entry; 5182 Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 5183 Entry.Node = Dst; 5184 Args.push_back(Entry); 5185 5186 Entry.Ty = Type::getInt8Ty(*DAG.getContext()); 5187 Entry.Node = Val; 5188 Args.push_back(Entry); 5189 5190 Entry.Ty = MI.getLength()->getType(); 5191 Entry.Node = Length; 5192 Args.push_back(Entry); 5193 5194 uint64_t ElementSizeConstant = MI.getElementSizeInBytes(); 5195 RTLIB::Libcall LibraryCall = 5196 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant); 5197 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 5198 report_fatal_error("Unsupported element size"); 5199 5200 TargetLowering::CallLoweringInfo CLI(DAG); 5201 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5202 TLI.getLibcallCallingConv(LibraryCall), 5203 Type::getVoidTy(*DAG.getContext()), 5204 DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall), 5205 TLI.getPointerTy(DAG.getDataLayout())), 5206 std::move(Args)); 5207 5208 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 5209 DAG.setRoot(CallResult.second); 5210 return nullptr; 5211 } 5212 case Intrinsic::dbg_addr: 5213 case Intrinsic::dbg_declare: { 5214 const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I); 5215 DILocalVariable *Variable = DI.getVariable(); 5216 DIExpression *Expression = DI.getExpression(); 5217 dropDanglingDebugInfo(Variable, Expression); 5218 assert(Variable && "Missing variable"); 5219 5220 // Check if address has undef value. 5221 const Value *Address = DI.getVariableLocation(); 5222 if (!Address || isa<UndefValue>(Address) || 5223 (Address->use_empty() && !isa<Argument>(Address))) { 5224 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5225 return nullptr; 5226 } 5227 5228 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5229 5230 // Check if this variable can be described by a frame index, typically 5231 // either as a static alloca or a byval parameter. 5232 int FI = std::numeric_limits<int>::max(); 5233 if (const auto *AI = 5234 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5235 if (AI->isStaticAlloca()) { 5236 auto I = FuncInfo.StaticAllocaMap.find(AI); 5237 if (I != FuncInfo.StaticAllocaMap.end()) 5238 FI = I->second; 5239 } 5240 } else if (const auto *Arg = dyn_cast<Argument>( 5241 Address->stripInBoundsConstantOffsets())) { 5242 FI = FuncInfo.getArgumentFrameIndex(Arg); 5243 } 5244 5245 // llvm.dbg.addr is control dependent and always generates indirect 5246 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5247 // the MachineFunction variable table. 5248 if (FI != std::numeric_limits<int>::max()) { 5249 if (Intrinsic == Intrinsic::dbg_addr) { 5250 SDDbgValue *SDV = DAG.getFrameIndexDbgValue(Variable, Expression, 5251 FI, dl, SDNodeOrder); 5252 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5253 } 5254 return nullptr; 5255 } 5256 5257 SDValue &N = NodeMap[Address]; 5258 if (!N.getNode() && isa<Argument>(Address)) 5259 // Check unused arguments map. 5260 N = UnusedArgNodeMap[Address]; 5261 SDDbgValue *SDV; 5262 if (N.getNode()) { 5263 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5264 Address = BCI->getOperand(0); 5265 // Parameters are handled specially. 5266 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5267 if (isParameter && FINode) { 5268 // Byval parameter. We have a frame index at this point. 5269 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, 5270 FINode->getIndex(), dl, SDNodeOrder); 5271 } else if (isa<Argument>(Address)) { 5272 // Address is an argument, so try to emit its dbg value using 5273 // virtual register info from the FuncInfo.ValueMap. 5274 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5275 return nullptr; 5276 } else { 5277 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5278 true, dl, SDNodeOrder); 5279 } 5280 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5281 } else { 5282 // If Address is an argument then try to emit its dbg value using 5283 // virtual register info from the FuncInfo.ValueMap. 5284 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5285 N)) { 5286 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5287 } 5288 } 5289 return nullptr; 5290 } 5291 case Intrinsic::dbg_value: { 5292 const DbgValueInst &DI = cast<DbgValueInst>(I); 5293 assert(DI.getVariable() && "Missing variable"); 5294 5295 DILocalVariable *Variable = DI.getVariable(); 5296 DIExpression *Expression = DI.getExpression(); 5297 dropDanglingDebugInfo(Variable, Expression); 5298 const Value *V = DI.getValue(); 5299 if (!V) 5300 return nullptr; 5301 5302 SDDbgValue *SDV; 5303 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 5304 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5305 DAG.AddDbgValue(SDV, nullptr, false); 5306 return nullptr; 5307 } 5308 5309 // Do not use getValue() in here; we don't want to generate code at 5310 // this point if it hasn't been done yet. 5311 SDValue N = NodeMap[V]; 5312 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5313 N = UnusedArgNodeMap[V]; 5314 if (N.getNode()) { 5315 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5316 return nullptr; 5317 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5318 DAG.AddDbgValue(SDV, N.getNode(), false); 5319 return nullptr; 5320 } 5321 5322 // TODO: When we get here we will either drop the dbg.value completely, or 5323 // we try to move it forward by letting it dangle for awhile. So we should 5324 // probably add an extra DbgValue to the DAG here, with a reference to 5325 // "noreg", to indicate that we have lost the debug location for the 5326 // variable. 5327 5328 if (!V->use_empty() ) { 5329 // Do not call getValue(V) yet, as we don't want to generate code. 5330 // Remember it for later. 5331 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder); 5332 DanglingDebugInfoMap[V] = DDI; 5333 return nullptr; 5334 } 5335 5336 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5337 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5338 return nullptr; 5339 } 5340 5341 case Intrinsic::eh_typeid_for: { 5342 // Find the type id for the given typeinfo. 5343 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5344 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5345 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5346 setValue(&I, Res); 5347 return nullptr; 5348 } 5349 5350 case Intrinsic::eh_return_i32: 5351 case Intrinsic::eh_return_i64: 5352 DAG.getMachineFunction().setCallsEHReturn(true); 5353 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5354 MVT::Other, 5355 getControlRoot(), 5356 getValue(I.getArgOperand(0)), 5357 getValue(I.getArgOperand(1)))); 5358 return nullptr; 5359 case Intrinsic::eh_unwind_init: 5360 DAG.getMachineFunction().setCallsUnwindInit(true); 5361 return nullptr; 5362 case Intrinsic::eh_dwarf_cfa: 5363 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5364 TLI.getPointerTy(DAG.getDataLayout()), 5365 getValue(I.getArgOperand(0)))); 5366 return nullptr; 5367 case Intrinsic::eh_sjlj_callsite: { 5368 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5369 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5370 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5371 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5372 5373 MMI.setCurrentCallSite(CI->getZExtValue()); 5374 return nullptr; 5375 } 5376 case Intrinsic::eh_sjlj_functioncontext: { 5377 // Get and store the index of the function context. 5378 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5379 AllocaInst *FnCtx = 5380 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5381 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5382 MFI.setFunctionContextIndex(FI); 5383 return nullptr; 5384 } 5385 case Intrinsic::eh_sjlj_setjmp: { 5386 SDValue Ops[2]; 5387 Ops[0] = getRoot(); 5388 Ops[1] = getValue(I.getArgOperand(0)); 5389 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5390 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5391 setValue(&I, Op.getValue(0)); 5392 DAG.setRoot(Op.getValue(1)); 5393 return nullptr; 5394 } 5395 case Intrinsic::eh_sjlj_longjmp: 5396 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5397 getRoot(), getValue(I.getArgOperand(0)))); 5398 return nullptr; 5399 case Intrinsic::eh_sjlj_setup_dispatch: 5400 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5401 getRoot())); 5402 return nullptr; 5403 case Intrinsic::masked_gather: 5404 visitMaskedGather(I); 5405 return nullptr; 5406 case Intrinsic::masked_load: 5407 visitMaskedLoad(I); 5408 return nullptr; 5409 case Intrinsic::masked_scatter: 5410 visitMaskedScatter(I); 5411 return nullptr; 5412 case Intrinsic::masked_store: 5413 visitMaskedStore(I); 5414 return nullptr; 5415 case Intrinsic::masked_expandload: 5416 visitMaskedLoad(I, true /* IsExpanding */); 5417 return nullptr; 5418 case Intrinsic::masked_compressstore: 5419 visitMaskedStore(I, true /* IsCompressing */); 5420 return nullptr; 5421 case Intrinsic::x86_mmx_pslli_w: 5422 case Intrinsic::x86_mmx_pslli_d: 5423 case Intrinsic::x86_mmx_pslli_q: 5424 case Intrinsic::x86_mmx_psrli_w: 5425 case Intrinsic::x86_mmx_psrli_d: 5426 case Intrinsic::x86_mmx_psrli_q: 5427 case Intrinsic::x86_mmx_psrai_w: 5428 case Intrinsic::x86_mmx_psrai_d: { 5429 SDValue ShAmt = getValue(I.getArgOperand(1)); 5430 if (isa<ConstantSDNode>(ShAmt)) { 5431 visitTargetIntrinsic(I, Intrinsic); 5432 return nullptr; 5433 } 5434 unsigned NewIntrinsic = 0; 5435 EVT ShAmtVT = MVT::v2i32; 5436 switch (Intrinsic) { 5437 case Intrinsic::x86_mmx_pslli_w: 5438 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5439 break; 5440 case Intrinsic::x86_mmx_pslli_d: 5441 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5442 break; 5443 case Intrinsic::x86_mmx_pslli_q: 5444 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5445 break; 5446 case Intrinsic::x86_mmx_psrli_w: 5447 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5448 break; 5449 case Intrinsic::x86_mmx_psrli_d: 5450 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5451 break; 5452 case Intrinsic::x86_mmx_psrli_q: 5453 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5454 break; 5455 case Intrinsic::x86_mmx_psrai_w: 5456 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5457 break; 5458 case Intrinsic::x86_mmx_psrai_d: 5459 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5460 break; 5461 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5462 } 5463 5464 // The vector shift intrinsics with scalars uses 32b shift amounts but 5465 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5466 // to be zero. 5467 // We must do this early because v2i32 is not a legal type. 5468 SDValue ShOps[2]; 5469 ShOps[0] = ShAmt; 5470 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5471 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5472 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5473 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5474 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5475 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5476 getValue(I.getArgOperand(0)), ShAmt); 5477 setValue(&I, Res); 5478 return nullptr; 5479 } 5480 case Intrinsic::powi: 5481 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5482 getValue(I.getArgOperand(1)), DAG)); 5483 return nullptr; 5484 case Intrinsic::log: 5485 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5486 return nullptr; 5487 case Intrinsic::log2: 5488 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5489 return nullptr; 5490 case Intrinsic::log10: 5491 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5492 return nullptr; 5493 case Intrinsic::exp: 5494 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5495 return nullptr; 5496 case Intrinsic::exp2: 5497 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5498 return nullptr; 5499 case Intrinsic::pow: 5500 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5501 getValue(I.getArgOperand(1)), DAG, TLI)); 5502 return nullptr; 5503 case Intrinsic::sqrt: 5504 case Intrinsic::fabs: 5505 case Intrinsic::sin: 5506 case Intrinsic::cos: 5507 case Intrinsic::floor: 5508 case Intrinsic::ceil: 5509 case Intrinsic::trunc: 5510 case Intrinsic::rint: 5511 case Intrinsic::nearbyint: 5512 case Intrinsic::round: 5513 case Intrinsic::canonicalize: { 5514 unsigned Opcode; 5515 switch (Intrinsic) { 5516 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5517 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5518 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5519 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5520 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5521 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5522 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5523 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5524 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5525 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5526 case Intrinsic::round: Opcode = ISD::FROUND; break; 5527 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5528 } 5529 5530 setValue(&I, DAG.getNode(Opcode, sdl, 5531 getValue(I.getArgOperand(0)).getValueType(), 5532 getValue(I.getArgOperand(0)))); 5533 return nullptr; 5534 } 5535 case Intrinsic::minnum: { 5536 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5537 unsigned Opc = 5538 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT) 5539 ? ISD::FMINNAN 5540 : ISD::FMINNUM; 5541 setValue(&I, DAG.getNode(Opc, sdl, VT, 5542 getValue(I.getArgOperand(0)), 5543 getValue(I.getArgOperand(1)))); 5544 return nullptr; 5545 } 5546 case Intrinsic::maxnum: { 5547 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5548 unsigned Opc = 5549 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT) 5550 ? ISD::FMAXNAN 5551 : ISD::FMAXNUM; 5552 setValue(&I, DAG.getNode(Opc, sdl, VT, 5553 getValue(I.getArgOperand(0)), 5554 getValue(I.getArgOperand(1)))); 5555 return nullptr; 5556 } 5557 case Intrinsic::copysign: 5558 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5559 getValue(I.getArgOperand(0)).getValueType(), 5560 getValue(I.getArgOperand(0)), 5561 getValue(I.getArgOperand(1)))); 5562 return nullptr; 5563 case Intrinsic::fma: 5564 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5565 getValue(I.getArgOperand(0)).getValueType(), 5566 getValue(I.getArgOperand(0)), 5567 getValue(I.getArgOperand(1)), 5568 getValue(I.getArgOperand(2)))); 5569 return nullptr; 5570 case Intrinsic::experimental_constrained_fadd: 5571 case Intrinsic::experimental_constrained_fsub: 5572 case Intrinsic::experimental_constrained_fmul: 5573 case Intrinsic::experimental_constrained_fdiv: 5574 case Intrinsic::experimental_constrained_frem: 5575 case Intrinsic::experimental_constrained_fma: 5576 case Intrinsic::experimental_constrained_sqrt: 5577 case Intrinsic::experimental_constrained_pow: 5578 case Intrinsic::experimental_constrained_powi: 5579 case Intrinsic::experimental_constrained_sin: 5580 case Intrinsic::experimental_constrained_cos: 5581 case Intrinsic::experimental_constrained_exp: 5582 case Intrinsic::experimental_constrained_exp2: 5583 case Intrinsic::experimental_constrained_log: 5584 case Intrinsic::experimental_constrained_log10: 5585 case Intrinsic::experimental_constrained_log2: 5586 case Intrinsic::experimental_constrained_rint: 5587 case Intrinsic::experimental_constrained_nearbyint: 5588 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5589 return nullptr; 5590 case Intrinsic::fmuladd: { 5591 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5592 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5593 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5594 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5595 getValue(I.getArgOperand(0)).getValueType(), 5596 getValue(I.getArgOperand(0)), 5597 getValue(I.getArgOperand(1)), 5598 getValue(I.getArgOperand(2)))); 5599 } else { 5600 // TODO: Intrinsic calls should have fast-math-flags. 5601 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5602 getValue(I.getArgOperand(0)).getValueType(), 5603 getValue(I.getArgOperand(0)), 5604 getValue(I.getArgOperand(1))); 5605 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5606 getValue(I.getArgOperand(0)).getValueType(), 5607 Mul, 5608 getValue(I.getArgOperand(2))); 5609 setValue(&I, Add); 5610 } 5611 return nullptr; 5612 } 5613 case Intrinsic::convert_to_fp16: 5614 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5615 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5616 getValue(I.getArgOperand(0)), 5617 DAG.getTargetConstant(0, sdl, 5618 MVT::i32)))); 5619 return nullptr; 5620 case Intrinsic::convert_from_fp16: 5621 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5622 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5623 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5624 getValue(I.getArgOperand(0))))); 5625 return nullptr; 5626 case Intrinsic::pcmarker: { 5627 SDValue Tmp = getValue(I.getArgOperand(0)); 5628 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5629 return nullptr; 5630 } 5631 case Intrinsic::readcyclecounter: { 5632 SDValue Op = getRoot(); 5633 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5634 DAG.getVTList(MVT::i64, MVT::Other), Op); 5635 setValue(&I, Res); 5636 DAG.setRoot(Res.getValue(1)); 5637 return nullptr; 5638 } 5639 case Intrinsic::bitreverse: 5640 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5641 getValue(I.getArgOperand(0)).getValueType(), 5642 getValue(I.getArgOperand(0)))); 5643 return nullptr; 5644 case Intrinsic::bswap: 5645 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5646 getValue(I.getArgOperand(0)).getValueType(), 5647 getValue(I.getArgOperand(0)))); 5648 return nullptr; 5649 case Intrinsic::cttz: { 5650 SDValue Arg = getValue(I.getArgOperand(0)); 5651 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5652 EVT Ty = Arg.getValueType(); 5653 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5654 sdl, Ty, Arg)); 5655 return nullptr; 5656 } 5657 case Intrinsic::ctlz: { 5658 SDValue Arg = getValue(I.getArgOperand(0)); 5659 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5660 EVT Ty = Arg.getValueType(); 5661 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5662 sdl, Ty, Arg)); 5663 return nullptr; 5664 } 5665 case Intrinsic::ctpop: { 5666 SDValue Arg = getValue(I.getArgOperand(0)); 5667 EVT Ty = Arg.getValueType(); 5668 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5669 return nullptr; 5670 } 5671 case Intrinsic::stacksave: { 5672 SDValue Op = getRoot(); 5673 Res = DAG.getNode( 5674 ISD::STACKSAVE, sdl, 5675 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5676 setValue(&I, Res); 5677 DAG.setRoot(Res.getValue(1)); 5678 return nullptr; 5679 } 5680 case Intrinsic::stackrestore: 5681 Res = getValue(I.getArgOperand(0)); 5682 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5683 return nullptr; 5684 case Intrinsic::get_dynamic_area_offset: { 5685 SDValue Op = getRoot(); 5686 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5687 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5688 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5689 // target. 5690 if (PtrTy != ResTy) 5691 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5692 " intrinsic!"); 5693 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5694 Op); 5695 DAG.setRoot(Op); 5696 setValue(&I, Res); 5697 return nullptr; 5698 } 5699 case Intrinsic::stackguard: { 5700 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5701 MachineFunction &MF = DAG.getMachineFunction(); 5702 const Module &M = *MF.getFunction().getParent(); 5703 SDValue Chain = getRoot(); 5704 if (TLI.useLoadStackGuardNode()) { 5705 Res = getLoadStackGuard(DAG, sdl, Chain); 5706 } else { 5707 const Value *Global = TLI.getSDagStackGuard(M); 5708 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5709 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5710 MachinePointerInfo(Global, 0), Align, 5711 MachineMemOperand::MOVolatile); 5712 } 5713 if (TLI.useStackGuardXorFP()) 5714 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5715 DAG.setRoot(Chain); 5716 setValue(&I, Res); 5717 return nullptr; 5718 } 5719 case Intrinsic::stackprotector: { 5720 // Emit code into the DAG to store the stack guard onto the stack. 5721 MachineFunction &MF = DAG.getMachineFunction(); 5722 MachineFrameInfo &MFI = MF.getFrameInfo(); 5723 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5724 SDValue Src, Chain = getRoot(); 5725 5726 if (TLI.useLoadStackGuardNode()) 5727 Src = getLoadStackGuard(DAG, sdl, Chain); 5728 else 5729 Src = getValue(I.getArgOperand(0)); // The guard's value. 5730 5731 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5732 5733 int FI = FuncInfo.StaticAllocaMap[Slot]; 5734 MFI.setStackProtectorIndex(FI); 5735 5736 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5737 5738 // Store the stack protector onto the stack. 5739 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5740 DAG.getMachineFunction(), FI), 5741 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5742 setValue(&I, Res); 5743 DAG.setRoot(Res); 5744 return nullptr; 5745 } 5746 case Intrinsic::objectsize: { 5747 // If we don't know by now, we're never going to know. 5748 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5749 5750 assert(CI && "Non-constant type in __builtin_object_size?"); 5751 5752 SDValue Arg = getValue(I.getCalledValue()); 5753 EVT Ty = Arg.getValueType(); 5754 5755 if (CI->isZero()) 5756 Res = DAG.getConstant(-1ULL, sdl, Ty); 5757 else 5758 Res = DAG.getConstant(0, sdl, Ty); 5759 5760 setValue(&I, Res); 5761 return nullptr; 5762 } 5763 case Intrinsic::annotation: 5764 case Intrinsic::ptr_annotation: 5765 case Intrinsic::invariant_group_barrier: 5766 // Drop the intrinsic, but forward the value 5767 setValue(&I, getValue(I.getOperand(0))); 5768 return nullptr; 5769 case Intrinsic::assume: 5770 case Intrinsic::var_annotation: 5771 case Intrinsic::sideeffect: 5772 // Discard annotate attributes, assumptions, and artificial side-effects. 5773 return nullptr; 5774 5775 case Intrinsic::codeview_annotation: { 5776 // Emit a label associated with this metadata. 5777 MachineFunction &MF = DAG.getMachineFunction(); 5778 MCSymbol *Label = 5779 MF.getMMI().getContext().createTempSymbol("annotation", true); 5780 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5781 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5782 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5783 DAG.setRoot(Res); 5784 return nullptr; 5785 } 5786 5787 case Intrinsic::init_trampoline: { 5788 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5789 5790 SDValue Ops[6]; 5791 Ops[0] = getRoot(); 5792 Ops[1] = getValue(I.getArgOperand(0)); 5793 Ops[2] = getValue(I.getArgOperand(1)); 5794 Ops[3] = getValue(I.getArgOperand(2)); 5795 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5796 Ops[5] = DAG.getSrcValue(F); 5797 5798 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5799 5800 DAG.setRoot(Res); 5801 return nullptr; 5802 } 5803 case Intrinsic::adjust_trampoline: 5804 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5805 TLI.getPointerTy(DAG.getDataLayout()), 5806 getValue(I.getArgOperand(0)))); 5807 return nullptr; 5808 case Intrinsic::gcroot: { 5809 assert(DAG.getMachineFunction().getFunction().hasGC() && 5810 "only valid in functions with gc specified, enforced by Verifier"); 5811 assert(GFI && "implied by previous"); 5812 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5813 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5814 5815 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5816 GFI->addStackRoot(FI->getIndex(), TypeMap); 5817 return nullptr; 5818 } 5819 case Intrinsic::gcread: 5820 case Intrinsic::gcwrite: 5821 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 5822 case Intrinsic::flt_rounds: 5823 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 5824 return nullptr; 5825 5826 case Intrinsic::expect: 5827 // Just replace __builtin_expect(exp, c) with EXP. 5828 setValue(&I, getValue(I.getArgOperand(0))); 5829 return nullptr; 5830 5831 case Intrinsic::debugtrap: 5832 case Intrinsic::trap: { 5833 StringRef TrapFuncName = 5834 I.getAttributes() 5835 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 5836 .getValueAsString(); 5837 if (TrapFuncName.empty()) { 5838 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 5839 ISD::TRAP : ISD::DEBUGTRAP; 5840 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 5841 return nullptr; 5842 } 5843 TargetLowering::ArgListTy Args; 5844 5845 TargetLowering::CallLoweringInfo CLI(DAG); 5846 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5847 CallingConv::C, I.getType(), 5848 DAG.getExternalSymbol(TrapFuncName.data(), 5849 TLI.getPointerTy(DAG.getDataLayout())), 5850 std::move(Args)); 5851 5852 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5853 DAG.setRoot(Result.second); 5854 return nullptr; 5855 } 5856 5857 case Intrinsic::uadd_with_overflow: 5858 case Intrinsic::sadd_with_overflow: 5859 case Intrinsic::usub_with_overflow: 5860 case Intrinsic::ssub_with_overflow: 5861 case Intrinsic::umul_with_overflow: 5862 case Intrinsic::smul_with_overflow: { 5863 ISD::NodeType Op; 5864 switch (Intrinsic) { 5865 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5866 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 5867 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 5868 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 5869 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 5870 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 5871 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 5872 } 5873 SDValue Op1 = getValue(I.getArgOperand(0)); 5874 SDValue Op2 = getValue(I.getArgOperand(1)); 5875 5876 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 5877 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 5878 return nullptr; 5879 } 5880 case Intrinsic::prefetch: { 5881 SDValue Ops[5]; 5882 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 5883 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 5884 Ops[0] = DAG.getRoot(); 5885 Ops[1] = getValue(I.getArgOperand(0)); 5886 Ops[2] = getValue(I.getArgOperand(1)); 5887 Ops[3] = getValue(I.getArgOperand(2)); 5888 Ops[4] = getValue(I.getArgOperand(3)); 5889 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 5890 DAG.getVTList(MVT::Other), Ops, 5891 EVT::getIntegerVT(*Context, 8), 5892 MachinePointerInfo(I.getArgOperand(0)), 5893 0, /* align */ 5894 Flags); 5895 5896 // Chain the prefetch in parallell with any pending loads, to stay out of 5897 // the way of later optimizations. 5898 PendingLoads.push_back(Result); 5899 Result = getRoot(); 5900 DAG.setRoot(Result); 5901 return nullptr; 5902 } 5903 case Intrinsic::lifetime_start: 5904 case Intrinsic::lifetime_end: { 5905 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 5906 // Stack coloring is not enabled in O0, discard region information. 5907 if (TM.getOptLevel() == CodeGenOpt::None) 5908 return nullptr; 5909 5910 SmallVector<Value *, 4> Allocas; 5911 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 5912 5913 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 5914 E = Allocas.end(); Object != E; ++Object) { 5915 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 5916 5917 // Could not find an Alloca. 5918 if (!LifetimeObject) 5919 continue; 5920 5921 // First check that the Alloca is static, otherwise it won't have a 5922 // valid frame index. 5923 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 5924 if (SI == FuncInfo.StaticAllocaMap.end()) 5925 return nullptr; 5926 5927 int FI = SI->second; 5928 5929 SDValue Ops[2]; 5930 Ops[0] = getRoot(); 5931 Ops[1] = 5932 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 5933 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 5934 5935 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 5936 DAG.setRoot(Res); 5937 } 5938 return nullptr; 5939 } 5940 case Intrinsic::invariant_start: 5941 // Discard region information. 5942 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 5943 return nullptr; 5944 case Intrinsic::invariant_end: 5945 // Discard region information. 5946 return nullptr; 5947 case Intrinsic::clear_cache: 5948 return TLI.getClearCacheBuiltinName(); 5949 case Intrinsic::donothing: 5950 // ignore 5951 return nullptr; 5952 case Intrinsic::experimental_stackmap: 5953 visitStackmap(I); 5954 return nullptr; 5955 case Intrinsic::experimental_patchpoint_void: 5956 case Intrinsic::experimental_patchpoint_i64: 5957 visitPatchpoint(&I); 5958 return nullptr; 5959 case Intrinsic::experimental_gc_statepoint: 5960 LowerStatepoint(ImmutableStatepoint(&I)); 5961 return nullptr; 5962 case Intrinsic::experimental_gc_result: 5963 visitGCResult(cast<GCResultInst>(I)); 5964 return nullptr; 5965 case Intrinsic::experimental_gc_relocate: 5966 visitGCRelocate(cast<GCRelocateInst>(I)); 5967 return nullptr; 5968 case Intrinsic::instrprof_increment: 5969 llvm_unreachable("instrprof failed to lower an increment"); 5970 case Intrinsic::instrprof_value_profile: 5971 llvm_unreachable("instrprof failed to lower a value profiling call"); 5972 case Intrinsic::localescape: { 5973 MachineFunction &MF = DAG.getMachineFunction(); 5974 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5975 5976 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 5977 // is the same on all targets. 5978 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 5979 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 5980 if (isa<ConstantPointerNull>(Arg)) 5981 continue; // Skip null pointers. They represent a hole in index space. 5982 AllocaInst *Slot = cast<AllocaInst>(Arg); 5983 assert(FuncInfo.StaticAllocaMap.count(Slot) && 5984 "can only escape static allocas"); 5985 int FI = FuncInfo.StaticAllocaMap[Slot]; 5986 MCSymbol *FrameAllocSym = 5987 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5988 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 5989 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 5990 TII->get(TargetOpcode::LOCAL_ESCAPE)) 5991 .addSym(FrameAllocSym) 5992 .addFrameIndex(FI); 5993 } 5994 5995 return nullptr; 5996 } 5997 5998 case Intrinsic::localrecover: { 5999 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6000 MachineFunction &MF = DAG.getMachineFunction(); 6001 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6002 6003 // Get the symbol that defines the frame offset. 6004 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6005 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6006 unsigned IdxVal = 6007 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6008 MCSymbol *FrameAllocSym = 6009 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6010 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6011 6012 // Create a MCSymbol for the label to avoid any target lowering 6013 // that would make this PC relative. 6014 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6015 SDValue OffsetVal = 6016 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6017 6018 // Add the offset to the FP. 6019 Value *FP = I.getArgOperand(1); 6020 SDValue FPVal = getValue(FP); 6021 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6022 setValue(&I, Add); 6023 6024 return nullptr; 6025 } 6026 6027 case Intrinsic::eh_exceptionpointer: 6028 case Intrinsic::eh_exceptioncode: { 6029 // Get the exception pointer vreg, copy from it, and resize it to fit. 6030 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6031 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6032 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6033 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6034 SDValue N = 6035 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6036 if (Intrinsic == Intrinsic::eh_exceptioncode) 6037 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6038 setValue(&I, N); 6039 return nullptr; 6040 } 6041 case Intrinsic::xray_customevent: { 6042 // Here we want to make sure that the intrinsic behaves as if it has a 6043 // specific calling convention, and only for x86_64. 6044 // FIXME: Support other platforms later. 6045 const auto &Triple = DAG.getTarget().getTargetTriple(); 6046 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6047 return nullptr; 6048 6049 SDLoc DL = getCurSDLoc(); 6050 SmallVector<SDValue, 8> Ops; 6051 6052 // We want to say that we always want the arguments in registers. 6053 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6054 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6055 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6056 SDValue Chain = getRoot(); 6057 Ops.push_back(LogEntryVal); 6058 Ops.push_back(StrSizeVal); 6059 Ops.push_back(Chain); 6060 6061 // We need to enforce the calling convention for the callsite, so that 6062 // argument ordering is enforced correctly, and that register allocation can 6063 // see that some registers may be assumed clobbered and have to preserve 6064 // them across calls to the intrinsic. 6065 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6066 DL, NodeTys, Ops); 6067 SDValue patchableNode = SDValue(MN, 0); 6068 DAG.setRoot(patchableNode); 6069 setValue(&I, patchableNode); 6070 return nullptr; 6071 } 6072 case Intrinsic::experimental_deoptimize: 6073 LowerDeoptimizeCall(&I); 6074 return nullptr; 6075 6076 case Intrinsic::experimental_vector_reduce_fadd: 6077 case Intrinsic::experimental_vector_reduce_fmul: 6078 case Intrinsic::experimental_vector_reduce_add: 6079 case Intrinsic::experimental_vector_reduce_mul: 6080 case Intrinsic::experimental_vector_reduce_and: 6081 case Intrinsic::experimental_vector_reduce_or: 6082 case Intrinsic::experimental_vector_reduce_xor: 6083 case Intrinsic::experimental_vector_reduce_smax: 6084 case Intrinsic::experimental_vector_reduce_smin: 6085 case Intrinsic::experimental_vector_reduce_umax: 6086 case Intrinsic::experimental_vector_reduce_umin: 6087 case Intrinsic::experimental_vector_reduce_fmax: 6088 case Intrinsic::experimental_vector_reduce_fmin: 6089 visitVectorReduce(I, Intrinsic); 6090 return nullptr; 6091 6092 case Intrinsic::icall_branch_funnel: { 6093 SmallVector<SDValue, 16> Ops; 6094 Ops.push_back(DAG.getRoot()); 6095 Ops.push_back(getValue(I.getArgOperand(0))); 6096 6097 int64_t Offset; 6098 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6099 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6100 if (!Base) 6101 report_fatal_error( 6102 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6103 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6104 6105 struct BranchFunnelTarget { 6106 int64_t Offset; 6107 SDValue Target; 6108 }; 6109 SmallVector<BranchFunnelTarget, 8> Targets; 6110 6111 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6112 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6113 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6114 if (ElemBase != Base) 6115 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6116 "to the same GlobalValue"); 6117 6118 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6119 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6120 if (!GA) 6121 report_fatal_error( 6122 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6123 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6124 GA->getGlobal(), getCurSDLoc(), 6125 Val.getValueType(), GA->getOffset())}); 6126 } 6127 std::sort(Targets.begin(), Targets.end(), 6128 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6129 return T1.Offset < T2.Offset; 6130 }); 6131 6132 for (auto &T : Targets) { 6133 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6134 Ops.push_back(T.Target); 6135 } 6136 6137 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6138 getCurSDLoc(), MVT::Other, Ops), 6139 0); 6140 DAG.setRoot(N); 6141 setValue(&I, N); 6142 HasTailCall = true; 6143 return nullptr; 6144 } 6145 } 6146 } 6147 6148 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6149 const ConstrainedFPIntrinsic &FPI) { 6150 SDLoc sdl = getCurSDLoc(); 6151 unsigned Opcode; 6152 switch (FPI.getIntrinsicID()) { 6153 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6154 case Intrinsic::experimental_constrained_fadd: 6155 Opcode = ISD::STRICT_FADD; 6156 break; 6157 case Intrinsic::experimental_constrained_fsub: 6158 Opcode = ISD::STRICT_FSUB; 6159 break; 6160 case Intrinsic::experimental_constrained_fmul: 6161 Opcode = ISD::STRICT_FMUL; 6162 break; 6163 case Intrinsic::experimental_constrained_fdiv: 6164 Opcode = ISD::STRICT_FDIV; 6165 break; 6166 case Intrinsic::experimental_constrained_frem: 6167 Opcode = ISD::STRICT_FREM; 6168 break; 6169 case Intrinsic::experimental_constrained_fma: 6170 Opcode = ISD::STRICT_FMA; 6171 break; 6172 case Intrinsic::experimental_constrained_sqrt: 6173 Opcode = ISD::STRICT_FSQRT; 6174 break; 6175 case Intrinsic::experimental_constrained_pow: 6176 Opcode = ISD::STRICT_FPOW; 6177 break; 6178 case Intrinsic::experimental_constrained_powi: 6179 Opcode = ISD::STRICT_FPOWI; 6180 break; 6181 case Intrinsic::experimental_constrained_sin: 6182 Opcode = ISD::STRICT_FSIN; 6183 break; 6184 case Intrinsic::experimental_constrained_cos: 6185 Opcode = ISD::STRICT_FCOS; 6186 break; 6187 case Intrinsic::experimental_constrained_exp: 6188 Opcode = ISD::STRICT_FEXP; 6189 break; 6190 case Intrinsic::experimental_constrained_exp2: 6191 Opcode = ISD::STRICT_FEXP2; 6192 break; 6193 case Intrinsic::experimental_constrained_log: 6194 Opcode = ISD::STRICT_FLOG; 6195 break; 6196 case Intrinsic::experimental_constrained_log10: 6197 Opcode = ISD::STRICT_FLOG10; 6198 break; 6199 case Intrinsic::experimental_constrained_log2: 6200 Opcode = ISD::STRICT_FLOG2; 6201 break; 6202 case Intrinsic::experimental_constrained_rint: 6203 Opcode = ISD::STRICT_FRINT; 6204 break; 6205 case Intrinsic::experimental_constrained_nearbyint: 6206 Opcode = ISD::STRICT_FNEARBYINT; 6207 break; 6208 } 6209 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6210 SDValue Chain = getRoot(); 6211 SmallVector<EVT, 4> ValueVTs; 6212 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6213 ValueVTs.push_back(MVT::Other); // Out chain 6214 6215 SDVTList VTs = DAG.getVTList(ValueVTs); 6216 SDValue Result; 6217 if (FPI.isUnaryOp()) 6218 Result = DAG.getNode(Opcode, sdl, VTs, 6219 { Chain, getValue(FPI.getArgOperand(0)) }); 6220 else if (FPI.isTernaryOp()) 6221 Result = DAG.getNode(Opcode, sdl, VTs, 6222 { Chain, getValue(FPI.getArgOperand(0)), 6223 getValue(FPI.getArgOperand(1)), 6224 getValue(FPI.getArgOperand(2)) }); 6225 else 6226 Result = DAG.getNode(Opcode, sdl, VTs, 6227 { Chain, getValue(FPI.getArgOperand(0)), 6228 getValue(FPI.getArgOperand(1)) }); 6229 6230 assert(Result.getNode()->getNumValues() == 2); 6231 SDValue OutChain = Result.getValue(1); 6232 DAG.setRoot(OutChain); 6233 SDValue FPResult = Result.getValue(0); 6234 setValue(&FPI, FPResult); 6235 } 6236 6237 std::pair<SDValue, SDValue> 6238 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6239 const BasicBlock *EHPadBB) { 6240 MachineFunction &MF = DAG.getMachineFunction(); 6241 MachineModuleInfo &MMI = MF.getMMI(); 6242 MCSymbol *BeginLabel = nullptr; 6243 6244 if (EHPadBB) { 6245 // Insert a label before the invoke call to mark the try range. This can be 6246 // used to detect deletion of the invoke via the MachineModuleInfo. 6247 BeginLabel = MMI.getContext().createTempSymbol(); 6248 6249 // For SjLj, keep track of which landing pads go with which invokes 6250 // so as to maintain the ordering of pads in the LSDA. 6251 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6252 if (CallSiteIndex) { 6253 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6254 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6255 6256 // Now that the call site is handled, stop tracking it. 6257 MMI.setCurrentCallSite(0); 6258 } 6259 6260 // Both PendingLoads and PendingExports must be flushed here; 6261 // this call might not return. 6262 (void)getRoot(); 6263 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6264 6265 CLI.setChain(getRoot()); 6266 } 6267 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6268 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6269 6270 assert((CLI.IsTailCall || Result.second.getNode()) && 6271 "Non-null chain expected with non-tail call!"); 6272 assert((Result.second.getNode() || !Result.first.getNode()) && 6273 "Null value expected with tail call!"); 6274 6275 if (!Result.second.getNode()) { 6276 // As a special case, a null chain means that a tail call has been emitted 6277 // and the DAG root is already updated. 6278 HasTailCall = true; 6279 6280 // Since there's no actual continuation from this block, nothing can be 6281 // relying on us setting vregs for them. 6282 PendingExports.clear(); 6283 } else { 6284 DAG.setRoot(Result.second); 6285 } 6286 6287 if (EHPadBB) { 6288 // Insert a label at the end of the invoke call to mark the try range. This 6289 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6290 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6291 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6292 6293 // Inform MachineModuleInfo of range. 6294 if (MF.hasEHFunclets()) { 6295 assert(CLI.CS); 6296 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6297 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6298 BeginLabel, EndLabel); 6299 } else { 6300 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6301 } 6302 } 6303 6304 return Result; 6305 } 6306 6307 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6308 bool isTailCall, 6309 const BasicBlock *EHPadBB) { 6310 auto &DL = DAG.getDataLayout(); 6311 FunctionType *FTy = CS.getFunctionType(); 6312 Type *RetTy = CS.getType(); 6313 6314 TargetLowering::ArgListTy Args; 6315 Args.reserve(CS.arg_size()); 6316 6317 const Value *SwiftErrorVal = nullptr; 6318 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6319 6320 // We can't tail call inside a function with a swifterror argument. Lowering 6321 // does not support this yet. It would have to move into the swifterror 6322 // register before the call. 6323 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6324 if (TLI.supportSwiftError() && 6325 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6326 isTailCall = false; 6327 6328 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6329 i != e; ++i) { 6330 TargetLowering::ArgListEntry Entry; 6331 const Value *V = *i; 6332 6333 // Skip empty types 6334 if (V->getType()->isEmptyTy()) 6335 continue; 6336 6337 SDValue ArgNode = getValue(V); 6338 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6339 6340 Entry.setAttributes(&CS, i - CS.arg_begin()); 6341 6342 // Use swifterror virtual register as input to the call. 6343 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6344 SwiftErrorVal = V; 6345 // We find the virtual register for the actual swifterror argument. 6346 // Instead of using the Value, we use the virtual register instead. 6347 Entry.Node = DAG.getRegister(FuncInfo 6348 .getOrCreateSwiftErrorVRegUseAt( 6349 CS.getInstruction(), FuncInfo.MBB, V) 6350 .first, 6351 EVT(TLI.getPointerTy(DL))); 6352 } 6353 6354 Args.push_back(Entry); 6355 6356 // If we have an explicit sret argument that is an Instruction, (i.e., it 6357 // might point to function-local memory), we can't meaningfully tail-call. 6358 if (Entry.IsSRet && isa<Instruction>(V)) 6359 isTailCall = false; 6360 } 6361 6362 // Check if target-independent constraints permit a tail call here. 6363 // Target-dependent constraints are checked within TLI->LowerCallTo. 6364 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6365 isTailCall = false; 6366 6367 // Disable tail calls if there is an swifterror argument. Targets have not 6368 // been updated to support tail calls. 6369 if (TLI.supportSwiftError() && SwiftErrorVal) 6370 isTailCall = false; 6371 6372 TargetLowering::CallLoweringInfo CLI(DAG); 6373 CLI.setDebugLoc(getCurSDLoc()) 6374 .setChain(getRoot()) 6375 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6376 .setTailCall(isTailCall) 6377 .setConvergent(CS.isConvergent()); 6378 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6379 6380 if (Result.first.getNode()) { 6381 const Instruction *Inst = CS.getInstruction(); 6382 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6383 setValue(Inst, Result.first); 6384 } 6385 6386 // The last element of CLI.InVals has the SDValue for swifterror return. 6387 // Here we copy it to a virtual register and update SwiftErrorMap for 6388 // book-keeping. 6389 if (SwiftErrorVal && TLI.supportSwiftError()) { 6390 // Get the last element of InVals. 6391 SDValue Src = CLI.InVals.back(); 6392 unsigned VReg; bool CreatedVReg; 6393 std::tie(VReg, CreatedVReg) = 6394 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6395 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6396 // We update the virtual register for the actual swifterror argument. 6397 if (CreatedVReg) 6398 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6399 DAG.setRoot(CopyNode); 6400 } 6401 } 6402 6403 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6404 SelectionDAGBuilder &Builder) { 6405 // Check to see if this load can be trivially constant folded, e.g. if the 6406 // input is from a string literal. 6407 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6408 // Cast pointer to the type we really want to load. 6409 Type *LoadTy = 6410 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6411 if (LoadVT.isVector()) 6412 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6413 6414 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6415 PointerType::getUnqual(LoadTy)); 6416 6417 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6418 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6419 return Builder.getValue(LoadCst); 6420 } 6421 6422 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6423 // still constant memory, the input chain can be the entry node. 6424 SDValue Root; 6425 bool ConstantMemory = false; 6426 6427 // Do not serialize (non-volatile) loads of constant memory with anything. 6428 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6429 Root = Builder.DAG.getEntryNode(); 6430 ConstantMemory = true; 6431 } else { 6432 // Do not serialize non-volatile loads against each other. 6433 Root = Builder.DAG.getRoot(); 6434 } 6435 6436 SDValue Ptr = Builder.getValue(PtrVal); 6437 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6438 Ptr, MachinePointerInfo(PtrVal), 6439 /* Alignment = */ 1); 6440 6441 if (!ConstantMemory) 6442 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6443 return LoadVal; 6444 } 6445 6446 /// Record the value for an instruction that produces an integer result, 6447 /// converting the type where necessary. 6448 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6449 SDValue Value, 6450 bool IsSigned) { 6451 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6452 I.getType(), true); 6453 if (IsSigned) 6454 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6455 else 6456 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6457 setValue(&I, Value); 6458 } 6459 6460 /// See if we can lower a memcmp call into an optimized form. If so, return 6461 /// true and lower it. Otherwise return false, and it will be lowered like a 6462 /// normal call. 6463 /// The caller already checked that \p I calls the appropriate LibFunc with a 6464 /// correct prototype. 6465 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6466 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6467 const Value *Size = I.getArgOperand(2); 6468 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6469 if (CSize && CSize->getZExtValue() == 0) { 6470 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6471 I.getType(), true); 6472 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6473 return true; 6474 } 6475 6476 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6477 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6478 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6479 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6480 if (Res.first.getNode()) { 6481 processIntegerCallValue(I, Res.first, true); 6482 PendingLoads.push_back(Res.second); 6483 return true; 6484 } 6485 6486 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6487 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6488 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6489 return false; 6490 6491 // If the target has a fast compare for the given size, it will return a 6492 // preferred load type for that size. Require that the load VT is legal and 6493 // that the target supports unaligned loads of that type. Otherwise, return 6494 // INVALID. 6495 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6496 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6497 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6498 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6499 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6500 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6501 // TODO: Check alignment of src and dest ptrs. 6502 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6503 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6504 if (!TLI.isTypeLegal(LVT) || 6505 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6506 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6507 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6508 } 6509 6510 return LVT; 6511 }; 6512 6513 // This turns into unaligned loads. We only do this if the target natively 6514 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6515 // we'll only produce a small number of byte loads. 6516 MVT LoadVT; 6517 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6518 switch (NumBitsToCompare) { 6519 default: 6520 return false; 6521 case 16: 6522 LoadVT = MVT::i16; 6523 break; 6524 case 32: 6525 LoadVT = MVT::i32; 6526 break; 6527 case 64: 6528 case 128: 6529 case 256: 6530 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6531 break; 6532 } 6533 6534 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6535 return false; 6536 6537 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6538 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6539 6540 // Bitcast to a wide integer type if the loads are vectors. 6541 if (LoadVT.isVector()) { 6542 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6543 LoadL = DAG.getBitcast(CmpVT, LoadL); 6544 LoadR = DAG.getBitcast(CmpVT, LoadR); 6545 } 6546 6547 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6548 processIntegerCallValue(I, Cmp, false); 6549 return true; 6550 } 6551 6552 /// See if we can lower a memchr call into an optimized form. If so, return 6553 /// true and lower it. Otherwise return false, and it will be lowered like a 6554 /// normal call. 6555 /// The caller already checked that \p I calls the appropriate LibFunc with a 6556 /// correct prototype. 6557 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6558 const Value *Src = I.getArgOperand(0); 6559 const Value *Char = I.getArgOperand(1); 6560 const Value *Length = I.getArgOperand(2); 6561 6562 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6563 std::pair<SDValue, SDValue> Res = 6564 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6565 getValue(Src), getValue(Char), getValue(Length), 6566 MachinePointerInfo(Src)); 6567 if (Res.first.getNode()) { 6568 setValue(&I, Res.first); 6569 PendingLoads.push_back(Res.second); 6570 return true; 6571 } 6572 6573 return false; 6574 } 6575 6576 /// See if we can lower a mempcpy call into an optimized form. If so, return 6577 /// true and lower it. Otherwise return false, and it will be lowered like a 6578 /// normal call. 6579 /// The caller already checked that \p I calls the appropriate LibFunc with a 6580 /// correct prototype. 6581 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6582 SDValue Dst = getValue(I.getArgOperand(0)); 6583 SDValue Src = getValue(I.getArgOperand(1)); 6584 SDValue Size = getValue(I.getArgOperand(2)); 6585 6586 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6587 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6588 unsigned Align = std::min(DstAlign, SrcAlign); 6589 if (Align == 0) // Alignment of one or both could not be inferred. 6590 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6591 6592 bool isVol = false; 6593 SDLoc sdl = getCurSDLoc(); 6594 6595 // In the mempcpy context we need to pass in a false value for isTailCall 6596 // because the return pointer needs to be adjusted by the size of 6597 // the copied memory. 6598 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6599 false, /*isTailCall=*/false, 6600 MachinePointerInfo(I.getArgOperand(0)), 6601 MachinePointerInfo(I.getArgOperand(1))); 6602 assert(MC.getNode() != nullptr && 6603 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6604 DAG.setRoot(MC); 6605 6606 // Check if Size needs to be truncated or extended. 6607 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6608 6609 // Adjust return pointer to point just past the last dst byte. 6610 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6611 Dst, Size); 6612 setValue(&I, DstPlusSize); 6613 return true; 6614 } 6615 6616 /// See if we can lower a strcpy call into an optimized form. If so, return 6617 /// true and lower it, otherwise return false and it will be lowered like a 6618 /// normal call. 6619 /// The caller already checked that \p I calls the appropriate LibFunc with a 6620 /// correct prototype. 6621 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6622 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6623 6624 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6625 std::pair<SDValue, SDValue> Res = 6626 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6627 getValue(Arg0), getValue(Arg1), 6628 MachinePointerInfo(Arg0), 6629 MachinePointerInfo(Arg1), isStpcpy); 6630 if (Res.first.getNode()) { 6631 setValue(&I, Res.first); 6632 DAG.setRoot(Res.second); 6633 return true; 6634 } 6635 6636 return false; 6637 } 6638 6639 /// See if we can lower a strcmp call into an optimized form. If so, return 6640 /// true and lower it, otherwise return false and it will be lowered like a 6641 /// normal call. 6642 /// The caller already checked that \p I calls the appropriate LibFunc with a 6643 /// correct prototype. 6644 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6645 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6646 6647 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6648 std::pair<SDValue, SDValue> Res = 6649 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6650 getValue(Arg0), getValue(Arg1), 6651 MachinePointerInfo(Arg0), 6652 MachinePointerInfo(Arg1)); 6653 if (Res.first.getNode()) { 6654 processIntegerCallValue(I, Res.first, true); 6655 PendingLoads.push_back(Res.second); 6656 return true; 6657 } 6658 6659 return false; 6660 } 6661 6662 /// See if we can lower a strlen call into an optimized form. If so, return 6663 /// true and lower it, otherwise return false and it will be lowered like a 6664 /// normal call. 6665 /// The caller already checked that \p I calls the appropriate LibFunc with a 6666 /// correct prototype. 6667 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6668 const Value *Arg0 = I.getArgOperand(0); 6669 6670 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6671 std::pair<SDValue, SDValue> Res = 6672 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6673 getValue(Arg0), MachinePointerInfo(Arg0)); 6674 if (Res.first.getNode()) { 6675 processIntegerCallValue(I, Res.first, false); 6676 PendingLoads.push_back(Res.second); 6677 return true; 6678 } 6679 6680 return false; 6681 } 6682 6683 /// See if we can lower a strnlen call into an optimized form. If so, return 6684 /// true and lower it, otherwise return false and it will be lowered like a 6685 /// normal call. 6686 /// The caller already checked that \p I calls the appropriate LibFunc with a 6687 /// correct prototype. 6688 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6689 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6690 6691 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6692 std::pair<SDValue, SDValue> Res = 6693 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6694 getValue(Arg0), getValue(Arg1), 6695 MachinePointerInfo(Arg0)); 6696 if (Res.first.getNode()) { 6697 processIntegerCallValue(I, Res.first, false); 6698 PendingLoads.push_back(Res.second); 6699 return true; 6700 } 6701 6702 return false; 6703 } 6704 6705 /// See if we can lower a unary floating-point operation into an SDNode with 6706 /// the specified Opcode. If so, return true and lower it, otherwise return 6707 /// false and it will be lowered like a normal call. 6708 /// The caller already checked that \p I calls the appropriate LibFunc with a 6709 /// correct prototype. 6710 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6711 unsigned Opcode) { 6712 // We already checked this call's prototype; verify it doesn't modify errno. 6713 if (!I.onlyReadsMemory()) 6714 return false; 6715 6716 SDValue Tmp = getValue(I.getArgOperand(0)); 6717 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6718 return true; 6719 } 6720 6721 /// See if we can lower a binary floating-point operation into an SDNode with 6722 /// the specified Opcode. If so, return true and lower it. Otherwise return 6723 /// false, and it will be lowered like a normal call. 6724 /// The caller already checked that \p I calls the appropriate LibFunc with a 6725 /// correct prototype. 6726 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6727 unsigned Opcode) { 6728 // We already checked this call's prototype; verify it doesn't modify errno. 6729 if (!I.onlyReadsMemory()) 6730 return false; 6731 6732 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6733 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6734 EVT VT = Tmp0.getValueType(); 6735 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6736 return true; 6737 } 6738 6739 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6740 // Handle inline assembly differently. 6741 if (isa<InlineAsm>(I.getCalledValue())) { 6742 visitInlineAsm(&I); 6743 return; 6744 } 6745 6746 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6747 computeUsesVAFloatArgument(I, MMI); 6748 6749 const char *RenameFn = nullptr; 6750 if (Function *F = I.getCalledFunction()) { 6751 if (F->isDeclaration()) { 6752 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) { 6753 if (unsigned IID = II->getIntrinsicID(F)) { 6754 RenameFn = visitIntrinsicCall(I, IID); 6755 if (!RenameFn) 6756 return; 6757 } 6758 } 6759 if (Intrinsic::ID IID = F->getIntrinsicID()) { 6760 RenameFn = visitIntrinsicCall(I, IID); 6761 if (!RenameFn) 6762 return; 6763 } 6764 } 6765 6766 // Check for well-known libc/libm calls. If the function is internal, it 6767 // can't be a library call. Don't do the check if marked as nobuiltin for 6768 // some reason or the call site requires strict floating point semantics. 6769 LibFunc Func; 6770 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 6771 F->hasName() && LibInfo->getLibFunc(*F, Func) && 6772 LibInfo->hasOptimizedCodeGen(Func)) { 6773 switch (Func) { 6774 default: break; 6775 case LibFunc_copysign: 6776 case LibFunc_copysignf: 6777 case LibFunc_copysignl: 6778 // We already checked this call's prototype; verify it doesn't modify 6779 // errno. 6780 if (I.onlyReadsMemory()) { 6781 SDValue LHS = getValue(I.getArgOperand(0)); 6782 SDValue RHS = getValue(I.getArgOperand(1)); 6783 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 6784 LHS.getValueType(), LHS, RHS)); 6785 return; 6786 } 6787 break; 6788 case LibFunc_fabs: 6789 case LibFunc_fabsf: 6790 case LibFunc_fabsl: 6791 if (visitUnaryFloatCall(I, ISD::FABS)) 6792 return; 6793 break; 6794 case LibFunc_fmin: 6795 case LibFunc_fminf: 6796 case LibFunc_fminl: 6797 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 6798 return; 6799 break; 6800 case LibFunc_fmax: 6801 case LibFunc_fmaxf: 6802 case LibFunc_fmaxl: 6803 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 6804 return; 6805 break; 6806 case LibFunc_sin: 6807 case LibFunc_sinf: 6808 case LibFunc_sinl: 6809 if (visitUnaryFloatCall(I, ISD::FSIN)) 6810 return; 6811 break; 6812 case LibFunc_cos: 6813 case LibFunc_cosf: 6814 case LibFunc_cosl: 6815 if (visitUnaryFloatCall(I, ISD::FCOS)) 6816 return; 6817 break; 6818 case LibFunc_sqrt: 6819 case LibFunc_sqrtf: 6820 case LibFunc_sqrtl: 6821 case LibFunc_sqrt_finite: 6822 case LibFunc_sqrtf_finite: 6823 case LibFunc_sqrtl_finite: 6824 if (visitUnaryFloatCall(I, ISD::FSQRT)) 6825 return; 6826 break; 6827 case LibFunc_floor: 6828 case LibFunc_floorf: 6829 case LibFunc_floorl: 6830 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 6831 return; 6832 break; 6833 case LibFunc_nearbyint: 6834 case LibFunc_nearbyintf: 6835 case LibFunc_nearbyintl: 6836 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 6837 return; 6838 break; 6839 case LibFunc_ceil: 6840 case LibFunc_ceilf: 6841 case LibFunc_ceill: 6842 if (visitUnaryFloatCall(I, ISD::FCEIL)) 6843 return; 6844 break; 6845 case LibFunc_rint: 6846 case LibFunc_rintf: 6847 case LibFunc_rintl: 6848 if (visitUnaryFloatCall(I, ISD::FRINT)) 6849 return; 6850 break; 6851 case LibFunc_round: 6852 case LibFunc_roundf: 6853 case LibFunc_roundl: 6854 if (visitUnaryFloatCall(I, ISD::FROUND)) 6855 return; 6856 break; 6857 case LibFunc_trunc: 6858 case LibFunc_truncf: 6859 case LibFunc_truncl: 6860 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 6861 return; 6862 break; 6863 case LibFunc_log2: 6864 case LibFunc_log2f: 6865 case LibFunc_log2l: 6866 if (visitUnaryFloatCall(I, ISD::FLOG2)) 6867 return; 6868 break; 6869 case LibFunc_exp2: 6870 case LibFunc_exp2f: 6871 case LibFunc_exp2l: 6872 if (visitUnaryFloatCall(I, ISD::FEXP2)) 6873 return; 6874 break; 6875 case LibFunc_memcmp: 6876 if (visitMemCmpCall(I)) 6877 return; 6878 break; 6879 case LibFunc_mempcpy: 6880 if (visitMemPCpyCall(I)) 6881 return; 6882 break; 6883 case LibFunc_memchr: 6884 if (visitMemChrCall(I)) 6885 return; 6886 break; 6887 case LibFunc_strcpy: 6888 if (visitStrCpyCall(I, false)) 6889 return; 6890 break; 6891 case LibFunc_stpcpy: 6892 if (visitStrCpyCall(I, true)) 6893 return; 6894 break; 6895 case LibFunc_strcmp: 6896 if (visitStrCmpCall(I)) 6897 return; 6898 break; 6899 case LibFunc_strlen: 6900 if (visitStrLenCall(I)) 6901 return; 6902 break; 6903 case LibFunc_strnlen: 6904 if (visitStrNLenCall(I)) 6905 return; 6906 break; 6907 } 6908 } 6909 } 6910 6911 SDValue Callee; 6912 if (!RenameFn) 6913 Callee = getValue(I.getCalledValue()); 6914 else 6915 Callee = DAG.getExternalSymbol( 6916 RenameFn, 6917 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6918 6919 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 6920 // have to do anything here to lower funclet bundles. 6921 assert(!I.hasOperandBundlesOtherThan( 6922 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 6923 "Cannot lower calls with arbitrary operand bundles!"); 6924 6925 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 6926 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 6927 else 6928 // Check if we can potentially perform a tail call. More detailed checking 6929 // is be done within LowerCallTo, after more information about the call is 6930 // known. 6931 LowerCallTo(&I, Callee, I.isTailCall()); 6932 } 6933 6934 namespace { 6935 6936 /// AsmOperandInfo - This contains information for each constraint that we are 6937 /// lowering. 6938 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 6939 public: 6940 /// CallOperand - If this is the result output operand or a clobber 6941 /// this is null, otherwise it is the incoming operand to the CallInst. 6942 /// This gets modified as the asm is processed. 6943 SDValue CallOperand; 6944 6945 /// AssignedRegs - If this is a register or register class operand, this 6946 /// contains the set of register corresponding to the operand. 6947 RegsForValue AssignedRegs; 6948 6949 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 6950 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 6951 } 6952 6953 /// Whether or not this operand accesses memory 6954 bool hasMemory(const TargetLowering &TLI) const { 6955 // Indirect operand accesses access memory. 6956 if (isIndirect) 6957 return true; 6958 6959 for (const auto &Code : Codes) 6960 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 6961 return true; 6962 6963 return false; 6964 } 6965 6966 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 6967 /// corresponds to. If there is no Value* for this operand, it returns 6968 /// MVT::Other. 6969 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 6970 const DataLayout &DL) const { 6971 if (!CallOperandVal) return MVT::Other; 6972 6973 if (isa<BasicBlock>(CallOperandVal)) 6974 return TLI.getPointerTy(DL); 6975 6976 llvm::Type *OpTy = CallOperandVal->getType(); 6977 6978 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 6979 // If this is an indirect operand, the operand is a pointer to the 6980 // accessed type. 6981 if (isIndirect) { 6982 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 6983 if (!PtrTy) 6984 report_fatal_error("Indirect operand for inline asm not a pointer!"); 6985 OpTy = PtrTy->getElementType(); 6986 } 6987 6988 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 6989 if (StructType *STy = dyn_cast<StructType>(OpTy)) 6990 if (STy->getNumElements() == 1) 6991 OpTy = STy->getElementType(0); 6992 6993 // If OpTy is not a single value, it may be a struct/union that we 6994 // can tile with integers. 6995 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 6996 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 6997 switch (BitSize) { 6998 default: break; 6999 case 1: 7000 case 8: 7001 case 16: 7002 case 32: 7003 case 64: 7004 case 128: 7005 OpTy = IntegerType::get(Context, BitSize); 7006 break; 7007 } 7008 } 7009 7010 return TLI.getValueType(DL, OpTy, true); 7011 } 7012 }; 7013 7014 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7015 7016 } // end anonymous namespace 7017 7018 /// Make sure that the output operand \p OpInfo and its corresponding input 7019 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7020 /// out). 7021 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7022 SDISelAsmOperandInfo &MatchingOpInfo, 7023 SelectionDAG &DAG) { 7024 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7025 return; 7026 7027 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7028 const auto &TLI = DAG.getTargetLoweringInfo(); 7029 7030 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7031 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7032 OpInfo.ConstraintVT); 7033 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7034 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7035 MatchingOpInfo.ConstraintVT); 7036 if ((OpInfo.ConstraintVT.isInteger() != 7037 MatchingOpInfo.ConstraintVT.isInteger()) || 7038 (MatchRC.second != InputRC.second)) { 7039 // FIXME: error out in a more elegant fashion 7040 report_fatal_error("Unsupported asm: input constraint" 7041 " with a matching output constraint of" 7042 " incompatible type!"); 7043 } 7044 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7045 } 7046 7047 /// Get a direct memory input to behave well as an indirect operand. 7048 /// This may introduce stores, hence the need for a \p Chain. 7049 /// \return The (possibly updated) chain. 7050 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7051 SDISelAsmOperandInfo &OpInfo, 7052 SelectionDAG &DAG) { 7053 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7054 7055 // If we don't have an indirect input, put it in the constpool if we can, 7056 // otherwise spill it to a stack slot. 7057 // TODO: This isn't quite right. We need to handle these according to 7058 // the addressing mode that the constraint wants. Also, this may take 7059 // an additional register for the computation and we don't want that 7060 // either. 7061 7062 // If the operand is a float, integer, or vector constant, spill to a 7063 // constant pool entry to get its address. 7064 const Value *OpVal = OpInfo.CallOperandVal; 7065 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7066 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7067 OpInfo.CallOperand = DAG.getConstantPool( 7068 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7069 return Chain; 7070 } 7071 7072 // Otherwise, create a stack slot and emit a store to it before the asm. 7073 Type *Ty = OpVal->getType(); 7074 auto &DL = DAG.getDataLayout(); 7075 uint64_t TySize = DL.getTypeAllocSize(Ty); 7076 unsigned Align = DL.getPrefTypeAlignment(Ty); 7077 MachineFunction &MF = DAG.getMachineFunction(); 7078 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7079 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7080 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7081 MachinePointerInfo::getFixedStack(MF, SSFI)); 7082 OpInfo.CallOperand = StackSlot; 7083 7084 return Chain; 7085 } 7086 7087 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7088 /// specified operand. We prefer to assign virtual registers, to allow the 7089 /// register allocator to handle the assignment process. However, if the asm 7090 /// uses features that we can't model on machineinstrs, we have SDISel do the 7091 /// allocation. This produces generally horrible, but correct, code. 7092 /// 7093 /// OpInfo describes the operand. 7094 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI, 7095 const SDLoc &DL, 7096 SDISelAsmOperandInfo &OpInfo) { 7097 LLVMContext &Context = *DAG.getContext(); 7098 7099 MachineFunction &MF = DAG.getMachineFunction(); 7100 SmallVector<unsigned, 4> Regs; 7101 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7102 7103 // If this is a constraint for a single physreg, or a constraint for a 7104 // register class, find it. 7105 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 7106 TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode, 7107 OpInfo.ConstraintVT); 7108 7109 unsigned NumRegs = 1; 7110 if (OpInfo.ConstraintVT != MVT::Other) { 7111 // If this is a FP input in an integer register (or visa versa) insert a bit 7112 // cast of the input value. More generally, handle any case where the input 7113 // value disagrees with the register class we plan to stick this in. 7114 if (OpInfo.Type == InlineAsm::isInput && PhysReg.second && 7115 !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) { 7116 // Try to convert to the first EVT that the reg class contains. If the 7117 // types are identical size, use a bitcast to convert (e.g. two differing 7118 // vector types). 7119 MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second); 7120 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) { 7121 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 7122 RegVT, OpInfo.CallOperand); 7123 OpInfo.ConstraintVT = RegVT; 7124 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7125 // If the input is a FP value and we want it in FP registers, do a 7126 // bitcast to the corresponding integer type. This turns an f64 value 7127 // into i64, which can be passed with two i32 values on a 32-bit 7128 // machine. 7129 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7130 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 7131 RegVT, OpInfo.CallOperand); 7132 OpInfo.ConstraintVT = RegVT; 7133 } 7134 } 7135 7136 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7137 } 7138 7139 MVT RegVT; 7140 EVT ValueVT = OpInfo.ConstraintVT; 7141 7142 // If this is a constraint for a specific physical register, like {r17}, 7143 // assign it now. 7144 if (unsigned AssignedReg = PhysReg.first) { 7145 const TargetRegisterClass *RC = PhysReg.second; 7146 if (OpInfo.ConstraintVT == MVT::Other) 7147 ValueVT = *TRI.legalclasstypes_begin(*RC); 7148 7149 // Get the actual register value type. This is important, because the user 7150 // may have asked for (e.g.) the AX register in i32 type. We need to 7151 // remember that AX is actually i16 to get the right extension. 7152 RegVT = *TRI.legalclasstypes_begin(*RC); 7153 7154 // This is a explicit reference to a physical register. 7155 Regs.push_back(AssignedReg); 7156 7157 // If this is an expanded reference, add the rest of the regs to Regs. 7158 if (NumRegs != 1) { 7159 TargetRegisterClass::iterator I = RC->begin(); 7160 for (; *I != AssignedReg; ++I) 7161 assert(I != RC->end() && "Didn't find reg!"); 7162 7163 // Already added the first reg. 7164 --NumRegs; ++I; 7165 for (; NumRegs; --NumRegs, ++I) { 7166 assert(I != RC->end() && "Ran out of registers to allocate!"); 7167 Regs.push_back(*I); 7168 } 7169 } 7170 7171 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7172 return; 7173 } 7174 7175 // Otherwise, if this was a reference to an LLVM register class, create vregs 7176 // for this reference. 7177 if (const TargetRegisterClass *RC = PhysReg.second) { 7178 RegVT = *TRI.legalclasstypes_begin(*RC); 7179 if (OpInfo.ConstraintVT == MVT::Other) 7180 ValueVT = RegVT; 7181 7182 // Create the appropriate number of virtual registers. 7183 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7184 for (; NumRegs; --NumRegs) 7185 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7186 7187 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7188 return; 7189 } 7190 7191 // Otherwise, we couldn't allocate enough registers for this. 7192 } 7193 7194 static unsigned 7195 findMatchingInlineAsmOperand(unsigned OperandNo, 7196 const std::vector<SDValue> &AsmNodeOperands) { 7197 // Scan until we find the definition we already emitted of this operand. 7198 unsigned CurOp = InlineAsm::Op_FirstOperand; 7199 for (; OperandNo; --OperandNo) { 7200 // Advance to the next operand. 7201 unsigned OpFlag = 7202 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7203 assert((InlineAsm::isRegDefKind(OpFlag) || 7204 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7205 InlineAsm::isMemKind(OpFlag)) && 7206 "Skipped past definitions?"); 7207 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7208 } 7209 return CurOp; 7210 } 7211 7212 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT 7213 /// \return true if it has succeeded, false otherwise 7214 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs, 7215 MVT RegVT, SelectionDAG &DAG) { 7216 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7217 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 7218 for (unsigned i = 0, e = NumRegs; i != e; ++i) { 7219 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 7220 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7221 else 7222 return false; 7223 } 7224 return true; 7225 } 7226 7227 namespace { 7228 7229 class ExtraFlags { 7230 unsigned Flags = 0; 7231 7232 public: 7233 explicit ExtraFlags(ImmutableCallSite CS) { 7234 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7235 if (IA->hasSideEffects()) 7236 Flags |= InlineAsm::Extra_HasSideEffects; 7237 if (IA->isAlignStack()) 7238 Flags |= InlineAsm::Extra_IsAlignStack; 7239 if (CS.isConvergent()) 7240 Flags |= InlineAsm::Extra_IsConvergent; 7241 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7242 } 7243 7244 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7245 // Ideally, we would only check against memory constraints. However, the 7246 // meaning of an Other constraint can be target-specific and we can't easily 7247 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7248 // for Other constraints as well. 7249 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7250 OpInfo.ConstraintType == TargetLowering::C_Other) { 7251 if (OpInfo.Type == InlineAsm::isInput) 7252 Flags |= InlineAsm::Extra_MayLoad; 7253 else if (OpInfo.Type == InlineAsm::isOutput) 7254 Flags |= InlineAsm::Extra_MayStore; 7255 else if (OpInfo.Type == InlineAsm::isClobber) 7256 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7257 } 7258 } 7259 7260 unsigned get() const { return Flags; } 7261 }; 7262 7263 } // end anonymous namespace 7264 7265 /// visitInlineAsm - Handle a call to an InlineAsm object. 7266 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7267 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7268 7269 /// ConstraintOperands - Information about all of the constraints. 7270 SDISelAsmOperandInfoVector ConstraintOperands; 7271 7272 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7273 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7274 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7275 7276 bool hasMemory = false; 7277 7278 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7279 ExtraFlags ExtraInfo(CS); 7280 7281 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7282 unsigned ResNo = 0; // ResNo - The result number of the next output. 7283 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 7284 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 7285 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7286 7287 MVT OpVT = MVT::Other; 7288 7289 // Compute the value type for each operand. 7290 if (OpInfo.Type == InlineAsm::isInput || 7291 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7292 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7293 7294 // Process the call argument. BasicBlocks are labels, currently appearing 7295 // only in asm's. 7296 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7297 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7298 } else { 7299 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7300 } 7301 7302 OpVT = 7303 OpInfo 7304 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7305 .getSimpleVT(); 7306 } 7307 7308 if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7309 // The return value of the call is this value. As such, there is no 7310 // corresponding argument. 7311 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7312 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7313 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 7314 STy->getElementType(ResNo)); 7315 } else { 7316 assert(ResNo == 0 && "Asm only has one result!"); 7317 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7318 } 7319 ++ResNo; 7320 } 7321 7322 OpInfo.ConstraintVT = OpVT; 7323 7324 if (!hasMemory) 7325 hasMemory = OpInfo.hasMemory(TLI); 7326 7327 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7328 // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]? 7329 auto TargetConstraint = TargetConstraints[i]; 7330 7331 // Compute the constraint code and ConstraintType to use. 7332 TLI.ComputeConstraintToUse(TargetConstraint, SDValue()); 7333 7334 ExtraInfo.update(TargetConstraint); 7335 } 7336 7337 SDValue Chain, Flag; 7338 7339 // We won't need to flush pending loads if this asm doesn't touch 7340 // memory and is nonvolatile. 7341 if (hasMemory || IA->hasSideEffects()) 7342 Chain = getRoot(); 7343 else 7344 Chain = DAG.getRoot(); 7345 7346 // Second pass over the constraints: compute which constraint option to use 7347 // and assign registers to constraints that want a specific physreg. 7348 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7349 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7350 7351 // If this is an output operand with a matching input operand, look up the 7352 // matching input. If their types mismatch, e.g. one is an integer, the 7353 // other is floating point, or their sizes are different, flag it as an 7354 // error. 7355 if (OpInfo.hasMatchingInput()) { 7356 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7357 patchMatchingInput(OpInfo, Input, DAG); 7358 } 7359 7360 // Compute the constraint code and ConstraintType to use. 7361 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7362 7363 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7364 OpInfo.Type == InlineAsm::isClobber) 7365 continue; 7366 7367 // If this is a memory input, and if the operand is not indirect, do what we 7368 // need to provide an address for the memory input. 7369 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7370 !OpInfo.isIndirect) { 7371 assert((OpInfo.isMultipleAlternative || 7372 (OpInfo.Type == InlineAsm::isInput)) && 7373 "Can only indirectify direct input operands!"); 7374 7375 // Memory operands really want the address of the value. 7376 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7377 7378 // There is no longer a Value* corresponding to this operand. 7379 OpInfo.CallOperandVal = nullptr; 7380 7381 // It is now an indirect operand. 7382 OpInfo.isIndirect = true; 7383 } 7384 7385 // If this constraint is for a specific register, allocate it before 7386 // anything else. 7387 if (OpInfo.ConstraintType == TargetLowering::C_Register) 7388 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 7389 } 7390 7391 // Third pass - Loop over all of the operands, assigning virtual or physregs 7392 // to register class operands. 7393 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7394 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7395 7396 // C_Register operands have already been allocated, Other/Memory don't need 7397 // to be. 7398 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 7399 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 7400 } 7401 7402 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7403 std::vector<SDValue> AsmNodeOperands; 7404 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7405 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7406 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7407 7408 // If we have a !srcloc metadata node associated with it, we want to attach 7409 // this to the ultimately generated inline asm machineinstr. To do this, we 7410 // pass in the third operand as this (potentially null) inline asm MDNode. 7411 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7412 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7413 7414 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7415 // bits as operand 3. 7416 AsmNodeOperands.push_back(DAG.getTargetConstant( 7417 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7418 7419 // Loop over all of the inputs, copying the operand values into the 7420 // appropriate registers and processing the output regs. 7421 RegsForValue RetValRegs; 7422 7423 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 7424 std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit; 7425 7426 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7427 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7428 7429 switch (OpInfo.Type) { 7430 case InlineAsm::isOutput: 7431 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7432 OpInfo.ConstraintType != TargetLowering::C_Register) { 7433 // Memory output, or 'other' output (e.g. 'X' constraint). 7434 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7435 7436 unsigned ConstraintID = 7437 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7438 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7439 "Failed to convert memory constraint code to constraint id."); 7440 7441 // Add information to the INLINEASM node to know about this output. 7442 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7443 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7444 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7445 MVT::i32)); 7446 AsmNodeOperands.push_back(OpInfo.CallOperand); 7447 break; 7448 } 7449 7450 // Otherwise, this is a register or register class output. 7451 7452 // Copy the output from the appropriate register. Find a register that 7453 // we can use. 7454 if (OpInfo.AssignedRegs.Regs.empty()) { 7455 emitInlineAsmError( 7456 CS, "couldn't allocate output register for constraint '" + 7457 Twine(OpInfo.ConstraintCode) + "'"); 7458 return; 7459 } 7460 7461 // If this is an indirect operand, store through the pointer after the 7462 // asm. 7463 if (OpInfo.isIndirect) { 7464 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 7465 OpInfo.CallOperandVal)); 7466 } else { 7467 // This is the result value of the call. 7468 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7469 // Concatenate this output onto the outputs list. 7470 RetValRegs.append(OpInfo.AssignedRegs); 7471 } 7472 7473 // Add information to the INLINEASM node to know that this register is 7474 // set. 7475 OpInfo.AssignedRegs 7476 .AddInlineAsmOperands(OpInfo.isEarlyClobber 7477 ? InlineAsm::Kind_RegDefEarlyClobber 7478 : InlineAsm::Kind_RegDef, 7479 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7480 break; 7481 7482 case InlineAsm::isInput: { 7483 SDValue InOperandVal = OpInfo.CallOperand; 7484 7485 if (OpInfo.isMatchingInputConstraint()) { 7486 // If this is required to match an output register we have already set, 7487 // just use its register. 7488 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7489 AsmNodeOperands); 7490 unsigned OpFlag = 7491 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7492 if (InlineAsm::isRegDefKind(OpFlag) || 7493 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7494 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7495 if (OpInfo.isIndirect) { 7496 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7497 emitInlineAsmError(CS, "inline asm not supported yet:" 7498 " don't know how to handle tied " 7499 "indirect register inputs"); 7500 return; 7501 } 7502 7503 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7504 SmallVector<unsigned, 4> Regs; 7505 7506 if (!createVirtualRegs(Regs, 7507 InlineAsm::getNumOperandRegisters(OpFlag), 7508 RegVT, DAG)) { 7509 emitInlineAsmError(CS, "inline asm error: This value type register " 7510 "class is not natively supported!"); 7511 return; 7512 } 7513 7514 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7515 7516 SDLoc dl = getCurSDLoc(); 7517 // Use the produced MatchedRegs object to 7518 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7519 CS.getInstruction()); 7520 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7521 true, OpInfo.getMatchedOperand(), dl, 7522 DAG, AsmNodeOperands); 7523 break; 7524 } 7525 7526 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7527 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7528 "Unexpected number of operands"); 7529 // Add information to the INLINEASM node to know about this input. 7530 // See InlineAsm.h isUseOperandTiedToDef. 7531 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7532 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7533 OpInfo.getMatchedOperand()); 7534 AsmNodeOperands.push_back(DAG.getTargetConstant( 7535 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7536 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7537 break; 7538 } 7539 7540 // Treat indirect 'X' constraint as memory. 7541 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7542 OpInfo.isIndirect) 7543 OpInfo.ConstraintType = TargetLowering::C_Memory; 7544 7545 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7546 std::vector<SDValue> Ops; 7547 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7548 Ops, DAG); 7549 if (Ops.empty()) { 7550 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7551 Twine(OpInfo.ConstraintCode) + "'"); 7552 return; 7553 } 7554 7555 // Add information to the INLINEASM node to know about this input. 7556 unsigned ResOpType = 7557 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7558 AsmNodeOperands.push_back(DAG.getTargetConstant( 7559 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7560 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7561 break; 7562 } 7563 7564 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7565 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7566 assert(InOperandVal.getValueType() == 7567 TLI.getPointerTy(DAG.getDataLayout()) && 7568 "Memory operands expect pointer values"); 7569 7570 unsigned ConstraintID = 7571 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7572 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7573 "Failed to convert memory constraint code to constraint id."); 7574 7575 // Add information to the INLINEASM node to know about this input. 7576 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7577 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7578 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7579 getCurSDLoc(), 7580 MVT::i32)); 7581 AsmNodeOperands.push_back(InOperandVal); 7582 break; 7583 } 7584 7585 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7586 OpInfo.ConstraintType == TargetLowering::C_Register) && 7587 "Unknown constraint type!"); 7588 7589 // TODO: Support this. 7590 if (OpInfo.isIndirect) { 7591 emitInlineAsmError( 7592 CS, "Don't know how to handle indirect register inputs yet " 7593 "for constraint '" + 7594 Twine(OpInfo.ConstraintCode) + "'"); 7595 return; 7596 } 7597 7598 // Copy the input into the appropriate registers. 7599 if (OpInfo.AssignedRegs.Regs.empty()) { 7600 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7601 Twine(OpInfo.ConstraintCode) + "'"); 7602 return; 7603 } 7604 7605 SDLoc dl = getCurSDLoc(); 7606 7607 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7608 Chain, &Flag, CS.getInstruction()); 7609 7610 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7611 dl, DAG, AsmNodeOperands); 7612 break; 7613 } 7614 case InlineAsm::isClobber: 7615 // Add the clobbered value to the operand list, so that the register 7616 // allocator is aware that the physreg got clobbered. 7617 if (!OpInfo.AssignedRegs.Regs.empty()) 7618 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7619 false, 0, getCurSDLoc(), DAG, 7620 AsmNodeOperands); 7621 break; 7622 } 7623 } 7624 7625 // Finish up input operands. Set the input chain and add the flag last. 7626 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7627 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7628 7629 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7630 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7631 Flag = Chain.getValue(1); 7632 7633 // If this asm returns a register value, copy the result from that register 7634 // and set it as the value of the call. 7635 if (!RetValRegs.Regs.empty()) { 7636 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7637 Chain, &Flag, CS.getInstruction()); 7638 7639 // FIXME: Why don't we do this for inline asms with MRVs? 7640 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 7641 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7642 7643 // If any of the results of the inline asm is a vector, it may have the 7644 // wrong width/num elts. This can happen for register classes that can 7645 // contain multiple different value types. The preg or vreg allocated may 7646 // not have the same VT as was expected. Convert it to the right type 7647 // with bit_convert. 7648 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 7649 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), 7650 ResultType, Val); 7651 7652 } else if (ResultType != Val.getValueType() && 7653 ResultType.isInteger() && Val.getValueType().isInteger()) { 7654 // If a result value was tied to an input value, the computed result may 7655 // have a wider width than the expected result. Extract the relevant 7656 // portion. 7657 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val); 7658 } 7659 7660 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 7661 } 7662 7663 setValue(CS.getInstruction(), Val); 7664 // Don't need to use this as a chain in this case. 7665 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 7666 return; 7667 } 7668 7669 std::vector<std::pair<SDValue, const Value *>> StoresToEmit; 7670 7671 // Process indirect outputs, first output all of the flagged copies out of 7672 // physregs. 7673 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 7674 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 7675 const Value *Ptr = IndirectStoresToEmit[i].second; 7676 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7677 Chain, &Flag, IA); 7678 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 7679 } 7680 7681 // Emit the non-flagged stores from the physregs. 7682 SmallVector<SDValue, 8> OutChains; 7683 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 7684 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first, 7685 getValue(StoresToEmit[i].second), 7686 MachinePointerInfo(StoresToEmit[i].second)); 7687 OutChains.push_back(Val); 7688 } 7689 7690 if (!OutChains.empty()) 7691 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7692 7693 DAG.setRoot(Chain); 7694 } 7695 7696 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7697 const Twine &Message) { 7698 LLVMContext &Ctx = *DAG.getContext(); 7699 Ctx.emitError(CS.getInstruction(), Message); 7700 7701 // Make sure we leave the DAG in a valid state 7702 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7703 auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7704 setValue(CS.getInstruction(), DAG.getUNDEF(VT)); 7705 } 7706 7707 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7708 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7709 MVT::Other, getRoot(), 7710 getValue(I.getArgOperand(0)), 7711 DAG.getSrcValue(I.getArgOperand(0)))); 7712 } 7713 7714 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7715 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7716 const DataLayout &DL = DAG.getDataLayout(); 7717 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7718 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7719 DAG.getSrcValue(I.getOperand(0)), 7720 DL.getABITypeAlignment(I.getType())); 7721 setValue(&I, V); 7722 DAG.setRoot(V.getValue(1)); 7723 } 7724 7725 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7726 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7727 MVT::Other, getRoot(), 7728 getValue(I.getArgOperand(0)), 7729 DAG.getSrcValue(I.getArgOperand(0)))); 7730 } 7731 7732 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7733 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7734 MVT::Other, getRoot(), 7735 getValue(I.getArgOperand(0)), 7736 getValue(I.getArgOperand(1)), 7737 DAG.getSrcValue(I.getArgOperand(0)), 7738 DAG.getSrcValue(I.getArgOperand(1)))); 7739 } 7740 7741 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7742 const Instruction &I, 7743 SDValue Op) { 7744 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7745 if (!Range) 7746 return Op; 7747 7748 ConstantRange CR = getConstantRangeFromMetadata(*Range); 7749 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 7750 return Op; 7751 7752 APInt Lo = CR.getUnsignedMin(); 7753 if (!Lo.isMinValue()) 7754 return Op; 7755 7756 APInt Hi = CR.getUnsignedMax(); 7757 unsigned Bits = Hi.getActiveBits(); 7758 7759 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7760 7761 SDLoc SL = getCurSDLoc(); 7762 7763 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 7764 DAG.getValueType(SmallVT)); 7765 unsigned NumVals = Op.getNode()->getNumValues(); 7766 if (NumVals == 1) 7767 return ZExt; 7768 7769 SmallVector<SDValue, 4> Ops; 7770 7771 Ops.push_back(ZExt); 7772 for (unsigned I = 1; I != NumVals; ++I) 7773 Ops.push_back(Op.getValue(I)); 7774 7775 return DAG.getMergeValues(Ops, SL); 7776 } 7777 7778 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of 7779 /// the call being lowered. 7780 /// 7781 /// This is a helper for lowering intrinsics that follow a target calling 7782 /// convention or require stack pointer adjustment. Only a subset of the 7783 /// intrinsic's operands need to participate in the calling convention. 7784 void SelectionDAGBuilder::populateCallLoweringInfo( 7785 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 7786 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 7787 bool IsPatchPoint) { 7788 TargetLowering::ArgListTy Args; 7789 Args.reserve(NumArgs); 7790 7791 // Populate the argument list. 7792 // Attributes for args start at offset 1, after the return attribute. 7793 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 7794 ArgI != ArgE; ++ArgI) { 7795 const Value *V = CS->getOperand(ArgI); 7796 7797 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 7798 7799 TargetLowering::ArgListEntry Entry; 7800 Entry.Node = getValue(V); 7801 Entry.Ty = V->getType(); 7802 Entry.setAttributes(&CS, ArgI); 7803 Args.push_back(Entry); 7804 } 7805 7806 CLI.setDebugLoc(getCurSDLoc()) 7807 .setChain(getRoot()) 7808 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 7809 .setDiscardResult(CS->use_empty()) 7810 .setIsPatchPoint(IsPatchPoint); 7811 } 7812 7813 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap 7814 /// or patchpoint target node's operand list. 7815 /// 7816 /// Constants are converted to TargetConstants purely as an optimization to 7817 /// avoid constant materialization and register allocation. 7818 /// 7819 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 7820 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 7821 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 7822 /// address materialization and register allocation, but may also be required 7823 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 7824 /// alloca in the entry block, then the runtime may assume that the alloca's 7825 /// StackMap location can be read immediately after compilation and that the 7826 /// location is valid at any point during execution (this is similar to the 7827 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 7828 /// only available in a register, then the runtime would need to trap when 7829 /// execution reaches the StackMap in order to read the alloca's location. 7830 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 7831 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 7832 SelectionDAGBuilder &Builder) { 7833 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 7834 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 7835 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 7836 Ops.push_back( 7837 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 7838 Ops.push_back( 7839 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 7840 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 7841 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 7842 Ops.push_back(Builder.DAG.getTargetFrameIndex( 7843 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 7844 } else 7845 Ops.push_back(OpVal); 7846 } 7847 } 7848 7849 /// \brief Lower llvm.experimental.stackmap directly to its target opcode. 7850 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 7851 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 7852 // [live variables...]) 7853 7854 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 7855 7856 SDValue Chain, InFlag, Callee, NullPtr; 7857 SmallVector<SDValue, 32> Ops; 7858 7859 SDLoc DL = getCurSDLoc(); 7860 Callee = getValue(CI.getCalledValue()); 7861 NullPtr = DAG.getIntPtrConstant(0, DL, true); 7862 7863 // The stackmap intrinsic only records the live variables (the arguemnts 7864 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 7865 // intrinsic, this won't be lowered to a function call. This means we don't 7866 // have to worry about calling conventions and target specific lowering code. 7867 // Instead we perform the call lowering right here. 7868 // 7869 // chain, flag = CALLSEQ_START(chain, 0, 0) 7870 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 7871 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 7872 // 7873 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 7874 InFlag = Chain.getValue(1); 7875 7876 // Add the <id> and <numBytes> constants. 7877 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 7878 Ops.push_back(DAG.getTargetConstant( 7879 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 7880 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 7881 Ops.push_back(DAG.getTargetConstant( 7882 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 7883 MVT::i32)); 7884 7885 // Push live variables for the stack map. 7886 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 7887 7888 // We are not pushing any register mask info here on the operands list, 7889 // because the stackmap doesn't clobber anything. 7890 7891 // Push the chain and the glue flag. 7892 Ops.push_back(Chain); 7893 Ops.push_back(InFlag); 7894 7895 // Create the STACKMAP node. 7896 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7897 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 7898 Chain = SDValue(SM, 0); 7899 InFlag = Chain.getValue(1); 7900 7901 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 7902 7903 // Stackmaps don't generate values, so nothing goes into the NodeMap. 7904 7905 // Set the root to the target-lowered call chain. 7906 DAG.setRoot(Chain); 7907 7908 // Inform the Frame Information that we have a stackmap in this function. 7909 FuncInfo.MF->getFrameInfo().setHasStackMap(); 7910 } 7911 7912 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode. 7913 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 7914 const BasicBlock *EHPadBB) { 7915 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 7916 // i32 <numBytes>, 7917 // i8* <target>, 7918 // i32 <numArgs>, 7919 // [Args...], 7920 // [live variables...]) 7921 7922 CallingConv::ID CC = CS.getCallingConv(); 7923 bool IsAnyRegCC = CC == CallingConv::AnyReg; 7924 bool HasDef = !CS->getType()->isVoidTy(); 7925 SDLoc dl = getCurSDLoc(); 7926 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 7927 7928 // Handle immediate and symbolic callees. 7929 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 7930 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 7931 /*isTarget=*/true); 7932 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 7933 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 7934 SDLoc(SymbolicCallee), 7935 SymbolicCallee->getValueType(0)); 7936 7937 // Get the real number of arguments participating in the call <numArgs> 7938 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 7939 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 7940 7941 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 7942 // Intrinsics include all meta-operands up to but not including CC. 7943 unsigned NumMetaOpers = PatchPointOpers::CCPos; 7944 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 7945 "Not enough arguments provided to the patchpoint intrinsic"); 7946 7947 // For AnyRegCC the arguments are lowered later on manually. 7948 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 7949 Type *ReturnTy = 7950 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 7951 7952 TargetLowering::CallLoweringInfo CLI(DAG); 7953 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 7954 true); 7955 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7956 7957 SDNode *CallEnd = Result.second.getNode(); 7958 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 7959 CallEnd = CallEnd->getOperand(0).getNode(); 7960 7961 /// Get a call instruction from the call sequence chain. 7962 /// Tail calls are not allowed. 7963 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 7964 "Expected a callseq node."); 7965 SDNode *Call = CallEnd->getOperand(0).getNode(); 7966 bool HasGlue = Call->getGluedNode(); 7967 7968 // Replace the target specific call node with the patchable intrinsic. 7969 SmallVector<SDValue, 8> Ops; 7970 7971 // Add the <id> and <numBytes> constants. 7972 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 7973 Ops.push_back(DAG.getTargetConstant( 7974 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 7975 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 7976 Ops.push_back(DAG.getTargetConstant( 7977 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 7978 MVT::i32)); 7979 7980 // Add the callee. 7981 Ops.push_back(Callee); 7982 7983 // Adjust <numArgs> to account for any arguments that have been passed on the 7984 // stack instead. 7985 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 7986 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 7987 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 7988 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 7989 7990 // Add the calling convention 7991 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 7992 7993 // Add the arguments we omitted previously. The register allocator should 7994 // place these in any free register. 7995 if (IsAnyRegCC) 7996 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 7997 Ops.push_back(getValue(CS.getArgument(i))); 7998 7999 // Push the arguments from the call instruction up to the register mask. 8000 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8001 Ops.append(Call->op_begin() + 2, e); 8002 8003 // Push live variables for the stack map. 8004 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8005 8006 // Push the register mask info. 8007 if (HasGlue) 8008 Ops.push_back(*(Call->op_end()-2)); 8009 else 8010 Ops.push_back(*(Call->op_end()-1)); 8011 8012 // Push the chain (this is originally the first operand of the call, but 8013 // becomes now the last or second to last operand). 8014 Ops.push_back(*(Call->op_begin())); 8015 8016 // Push the glue flag (last operand). 8017 if (HasGlue) 8018 Ops.push_back(*(Call->op_end()-1)); 8019 8020 SDVTList NodeTys; 8021 if (IsAnyRegCC && HasDef) { 8022 // Create the return types based on the intrinsic definition 8023 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8024 SmallVector<EVT, 3> ValueVTs; 8025 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8026 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8027 8028 // There is always a chain and a glue type at the end 8029 ValueVTs.push_back(MVT::Other); 8030 ValueVTs.push_back(MVT::Glue); 8031 NodeTys = DAG.getVTList(ValueVTs); 8032 } else 8033 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8034 8035 // Replace the target specific call node with a PATCHPOINT node. 8036 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8037 dl, NodeTys, Ops); 8038 8039 // Update the NodeMap. 8040 if (HasDef) { 8041 if (IsAnyRegCC) 8042 setValue(CS.getInstruction(), SDValue(MN, 0)); 8043 else 8044 setValue(CS.getInstruction(), Result.first); 8045 } 8046 8047 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8048 // call sequence. Furthermore the location of the chain and glue can change 8049 // when the AnyReg calling convention is used and the intrinsic returns a 8050 // value. 8051 if (IsAnyRegCC && HasDef) { 8052 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8053 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8054 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8055 } else 8056 DAG.ReplaceAllUsesWith(Call, MN); 8057 DAG.DeleteNode(Call); 8058 8059 // Inform the Frame Information that we have a patchpoint in this function. 8060 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8061 } 8062 8063 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8064 unsigned Intrinsic) { 8065 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8066 SDValue Op1 = getValue(I.getArgOperand(0)); 8067 SDValue Op2; 8068 if (I.getNumArgOperands() > 1) 8069 Op2 = getValue(I.getArgOperand(1)); 8070 SDLoc dl = getCurSDLoc(); 8071 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8072 SDValue Res; 8073 FastMathFlags FMF; 8074 if (isa<FPMathOperator>(I)) 8075 FMF = I.getFastMathFlags(); 8076 SDNodeFlags SDFlags; 8077 SDFlags.setNoNaNs(FMF.noNaNs()); 8078 8079 switch (Intrinsic) { 8080 case Intrinsic::experimental_vector_reduce_fadd: 8081 if (FMF.isFast()) 8082 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8083 else 8084 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8085 break; 8086 case Intrinsic::experimental_vector_reduce_fmul: 8087 if (FMF.isFast()) 8088 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8089 else 8090 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8091 break; 8092 case Intrinsic::experimental_vector_reduce_add: 8093 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8094 break; 8095 case Intrinsic::experimental_vector_reduce_mul: 8096 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8097 break; 8098 case Intrinsic::experimental_vector_reduce_and: 8099 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8100 break; 8101 case Intrinsic::experimental_vector_reduce_or: 8102 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8103 break; 8104 case Intrinsic::experimental_vector_reduce_xor: 8105 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8106 break; 8107 case Intrinsic::experimental_vector_reduce_smax: 8108 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8109 break; 8110 case Intrinsic::experimental_vector_reduce_smin: 8111 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8112 break; 8113 case Intrinsic::experimental_vector_reduce_umax: 8114 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8115 break; 8116 case Intrinsic::experimental_vector_reduce_umin: 8117 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8118 break; 8119 case Intrinsic::experimental_vector_reduce_fmax: 8120 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 8121 break; 8122 case Intrinsic::experimental_vector_reduce_fmin: 8123 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 8124 break; 8125 default: 8126 llvm_unreachable("Unhandled vector reduce intrinsic"); 8127 } 8128 setValue(&I, Res); 8129 } 8130 8131 /// Returns an AttributeList representing the attributes applied to the return 8132 /// value of the given call. 8133 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8134 SmallVector<Attribute::AttrKind, 2> Attrs; 8135 if (CLI.RetSExt) 8136 Attrs.push_back(Attribute::SExt); 8137 if (CLI.RetZExt) 8138 Attrs.push_back(Attribute::ZExt); 8139 if (CLI.IsInReg) 8140 Attrs.push_back(Attribute::InReg); 8141 8142 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8143 Attrs); 8144 } 8145 8146 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8147 /// implementation, which just calls LowerCall. 8148 /// FIXME: When all targets are 8149 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8150 std::pair<SDValue, SDValue> 8151 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8152 // Handle the incoming return values from the call. 8153 CLI.Ins.clear(); 8154 Type *OrigRetTy = CLI.RetTy; 8155 SmallVector<EVT, 4> RetTys; 8156 SmallVector<uint64_t, 4> Offsets; 8157 auto &DL = CLI.DAG.getDataLayout(); 8158 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8159 8160 if (CLI.IsPostTypeLegalization) { 8161 // If we are lowering a libcall after legalization, split the return type. 8162 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8163 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8164 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8165 EVT RetVT = OldRetTys[i]; 8166 uint64_t Offset = OldOffsets[i]; 8167 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8168 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8169 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8170 RetTys.append(NumRegs, RegisterVT); 8171 for (unsigned j = 0; j != NumRegs; ++j) 8172 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8173 } 8174 } 8175 8176 SmallVector<ISD::OutputArg, 4> Outs; 8177 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8178 8179 bool CanLowerReturn = 8180 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8181 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8182 8183 SDValue DemoteStackSlot; 8184 int DemoteStackIdx = -100; 8185 if (!CanLowerReturn) { 8186 // FIXME: equivalent assert? 8187 // assert(!CS.hasInAllocaArgument() && 8188 // "sret demotion is incompatible with inalloca"); 8189 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8190 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8191 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8192 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8193 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy); 8194 8195 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8196 ArgListEntry Entry; 8197 Entry.Node = DemoteStackSlot; 8198 Entry.Ty = StackSlotPtrType; 8199 Entry.IsSExt = false; 8200 Entry.IsZExt = false; 8201 Entry.IsInReg = false; 8202 Entry.IsSRet = true; 8203 Entry.IsNest = false; 8204 Entry.IsByVal = false; 8205 Entry.IsReturned = false; 8206 Entry.IsSwiftSelf = false; 8207 Entry.IsSwiftError = false; 8208 Entry.Alignment = Align; 8209 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8210 CLI.NumFixedArgs += 1; 8211 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8212 8213 // sret demotion isn't compatible with tail-calls, since the sret argument 8214 // points into the callers stack frame. 8215 CLI.IsTailCall = false; 8216 } else { 8217 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8218 EVT VT = RetTys[I]; 8219 MVT RegisterVT = 8220 getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8221 unsigned NumRegs = 8222 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8223 for (unsigned i = 0; i != NumRegs; ++i) { 8224 ISD::InputArg MyFlags; 8225 MyFlags.VT = RegisterVT; 8226 MyFlags.ArgVT = VT; 8227 MyFlags.Used = CLI.IsReturnValueUsed; 8228 if (CLI.RetSExt) 8229 MyFlags.Flags.setSExt(); 8230 if (CLI.RetZExt) 8231 MyFlags.Flags.setZExt(); 8232 if (CLI.IsInReg) 8233 MyFlags.Flags.setInReg(); 8234 CLI.Ins.push_back(MyFlags); 8235 } 8236 } 8237 } 8238 8239 // We push in swifterror return as the last element of CLI.Ins. 8240 ArgListTy &Args = CLI.getArgs(); 8241 if (supportSwiftError()) { 8242 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8243 if (Args[i].IsSwiftError) { 8244 ISD::InputArg MyFlags; 8245 MyFlags.VT = getPointerTy(DL); 8246 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8247 MyFlags.Flags.setSwiftError(); 8248 CLI.Ins.push_back(MyFlags); 8249 } 8250 } 8251 } 8252 8253 // Handle all of the outgoing arguments. 8254 CLI.Outs.clear(); 8255 CLI.OutVals.clear(); 8256 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8257 SmallVector<EVT, 4> ValueVTs; 8258 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8259 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8260 Type *FinalType = Args[i].Ty; 8261 if (Args[i].IsByVal) 8262 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8263 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8264 FinalType, CLI.CallConv, CLI.IsVarArg); 8265 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8266 ++Value) { 8267 EVT VT = ValueVTs[Value]; 8268 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8269 SDValue Op = SDValue(Args[i].Node.getNode(), 8270 Args[i].Node.getResNo() + Value); 8271 ISD::ArgFlagsTy Flags; 8272 8273 // Certain targets (such as MIPS), may have a different ABI alignment 8274 // for a type depending on the context. Give the target a chance to 8275 // specify the alignment it wants. 8276 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8277 8278 if (Args[i].IsZExt) 8279 Flags.setZExt(); 8280 if (Args[i].IsSExt) 8281 Flags.setSExt(); 8282 if (Args[i].IsInReg) { 8283 // If we are using vectorcall calling convention, a structure that is 8284 // passed InReg - is surely an HVA 8285 if (CLI.CallConv == CallingConv::X86_VectorCall && 8286 isa<StructType>(FinalType)) { 8287 // The first value of a structure is marked 8288 if (0 == Value) 8289 Flags.setHvaStart(); 8290 Flags.setHva(); 8291 } 8292 // Set InReg Flag 8293 Flags.setInReg(); 8294 } 8295 if (Args[i].IsSRet) 8296 Flags.setSRet(); 8297 if (Args[i].IsSwiftSelf) 8298 Flags.setSwiftSelf(); 8299 if (Args[i].IsSwiftError) 8300 Flags.setSwiftError(); 8301 if (Args[i].IsByVal) 8302 Flags.setByVal(); 8303 if (Args[i].IsInAlloca) { 8304 Flags.setInAlloca(); 8305 // Set the byval flag for CCAssignFn callbacks that don't know about 8306 // inalloca. This way we can know how many bytes we should've allocated 8307 // and how many bytes a callee cleanup function will pop. If we port 8308 // inalloca to more targets, we'll have to add custom inalloca handling 8309 // in the various CC lowering callbacks. 8310 Flags.setByVal(); 8311 } 8312 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8313 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8314 Type *ElementTy = Ty->getElementType(); 8315 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8316 // For ByVal, alignment should come from FE. BE will guess if this 8317 // info is not there but there are cases it cannot get right. 8318 unsigned FrameAlign; 8319 if (Args[i].Alignment) 8320 FrameAlign = Args[i].Alignment; 8321 else 8322 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8323 Flags.setByValAlign(FrameAlign); 8324 } 8325 if (Args[i].IsNest) 8326 Flags.setNest(); 8327 if (NeedsRegBlock) 8328 Flags.setInConsecutiveRegs(); 8329 Flags.setOrigAlign(OriginalAlignment); 8330 8331 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8332 unsigned NumParts = 8333 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8334 SmallVector<SDValue, 4> Parts(NumParts); 8335 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8336 8337 if (Args[i].IsSExt) 8338 ExtendKind = ISD::SIGN_EXTEND; 8339 else if (Args[i].IsZExt) 8340 ExtendKind = ISD::ZERO_EXTEND; 8341 8342 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8343 // for now. 8344 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8345 CanLowerReturn) { 8346 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8347 "unexpected use of 'returned'"); 8348 // Before passing 'returned' to the target lowering code, ensure that 8349 // either the register MVT and the actual EVT are the same size or that 8350 // the return value and argument are extended in the same way; in these 8351 // cases it's safe to pass the argument register value unchanged as the 8352 // return register value (although it's at the target's option whether 8353 // to do so) 8354 // TODO: allow code generation to take advantage of partially preserved 8355 // registers rather than clobbering the entire register when the 8356 // parameter extension method is not compatible with the return 8357 // extension method 8358 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8359 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8360 CLI.RetZExt == Args[i].IsZExt)) 8361 Flags.setReturned(); 8362 } 8363 8364 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8365 CLI.CS.getInstruction(), ExtendKind, true); 8366 8367 for (unsigned j = 0; j != NumParts; ++j) { 8368 // if it isn't first piece, alignment must be 1 8369 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8370 i < CLI.NumFixedArgs, 8371 i, j*Parts[j].getValueType().getStoreSize()); 8372 if (NumParts > 1 && j == 0) 8373 MyFlags.Flags.setSplit(); 8374 else if (j != 0) { 8375 MyFlags.Flags.setOrigAlign(1); 8376 if (j == NumParts - 1) 8377 MyFlags.Flags.setSplitEnd(); 8378 } 8379 8380 CLI.Outs.push_back(MyFlags); 8381 CLI.OutVals.push_back(Parts[j]); 8382 } 8383 8384 if (NeedsRegBlock && Value == NumValues - 1) 8385 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8386 } 8387 } 8388 8389 SmallVector<SDValue, 4> InVals; 8390 CLI.Chain = LowerCall(CLI, InVals); 8391 8392 // Update CLI.InVals to use outside of this function. 8393 CLI.InVals = InVals; 8394 8395 // Verify that the target's LowerCall behaved as expected. 8396 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8397 "LowerCall didn't return a valid chain!"); 8398 assert((!CLI.IsTailCall || InVals.empty()) && 8399 "LowerCall emitted a return value for a tail call!"); 8400 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8401 "LowerCall didn't emit the correct number of values!"); 8402 8403 // For a tail call, the return value is merely live-out and there aren't 8404 // any nodes in the DAG representing it. Return a special value to 8405 // indicate that a tail call has been emitted and no more Instructions 8406 // should be processed in the current block. 8407 if (CLI.IsTailCall) { 8408 CLI.DAG.setRoot(CLI.Chain); 8409 return std::make_pair(SDValue(), SDValue()); 8410 } 8411 8412 #ifndef NDEBUG 8413 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8414 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8415 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8416 "LowerCall emitted a value with the wrong type!"); 8417 } 8418 #endif 8419 8420 SmallVector<SDValue, 4> ReturnValues; 8421 if (!CanLowerReturn) { 8422 // The instruction result is the result of loading from the 8423 // hidden sret parameter. 8424 SmallVector<EVT, 1> PVTs; 8425 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8426 8427 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8428 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8429 EVT PtrVT = PVTs[0]; 8430 8431 unsigned NumValues = RetTys.size(); 8432 ReturnValues.resize(NumValues); 8433 SmallVector<SDValue, 4> Chains(NumValues); 8434 8435 // An aggregate return value cannot wrap around the address space, so 8436 // offsets to its parts don't wrap either. 8437 SDNodeFlags Flags; 8438 Flags.setNoUnsignedWrap(true); 8439 8440 for (unsigned i = 0; i < NumValues; ++i) { 8441 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8442 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8443 PtrVT), Flags); 8444 SDValue L = CLI.DAG.getLoad( 8445 RetTys[i], CLI.DL, CLI.Chain, Add, 8446 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8447 DemoteStackIdx, Offsets[i]), 8448 /* Alignment = */ 1); 8449 ReturnValues[i] = L; 8450 Chains[i] = L.getValue(1); 8451 } 8452 8453 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8454 } else { 8455 // Collect the legal value parts into potentially illegal values 8456 // that correspond to the original function's return values. 8457 Optional<ISD::NodeType> AssertOp; 8458 if (CLI.RetSExt) 8459 AssertOp = ISD::AssertSext; 8460 else if (CLI.RetZExt) 8461 AssertOp = ISD::AssertZext; 8462 unsigned CurReg = 0; 8463 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8464 EVT VT = RetTys[I]; 8465 MVT RegisterVT = 8466 getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8467 unsigned NumRegs = 8468 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8469 8470 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8471 NumRegs, RegisterVT, VT, nullptr, 8472 AssertOp, true)); 8473 CurReg += NumRegs; 8474 } 8475 8476 // For a function returning void, there is no return value. We can't create 8477 // such a node, so we just return a null return value in that case. In 8478 // that case, nothing will actually look at the value. 8479 if (ReturnValues.empty()) 8480 return std::make_pair(SDValue(), CLI.Chain); 8481 } 8482 8483 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8484 CLI.DAG.getVTList(RetTys), ReturnValues); 8485 return std::make_pair(Res, CLI.Chain); 8486 } 8487 8488 void TargetLowering::LowerOperationWrapper(SDNode *N, 8489 SmallVectorImpl<SDValue> &Results, 8490 SelectionDAG &DAG) const { 8491 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8492 Results.push_back(Res); 8493 } 8494 8495 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8496 llvm_unreachable("LowerOperation not implemented for this target!"); 8497 } 8498 8499 void 8500 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8501 SDValue Op = getNonRegisterValue(V); 8502 assert((Op.getOpcode() != ISD::CopyFromReg || 8503 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8504 "Copy from a reg to the same reg!"); 8505 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8506 8507 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8508 // If this is an InlineAsm we have to match the registers required, not the 8509 // notional registers required by the type. 8510 8511 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 8512 V->getType(), isABIRegCopy(V)); 8513 SDValue Chain = DAG.getEntryNode(); 8514 8515 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8516 FuncInfo.PreferredExtendType.end()) 8517 ? ISD::ANY_EXTEND 8518 : FuncInfo.PreferredExtendType[V]; 8519 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8520 PendingExports.push_back(Chain); 8521 } 8522 8523 #include "llvm/CodeGen/SelectionDAGISel.h" 8524 8525 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8526 /// entry block, return true. This includes arguments used by switches, since 8527 /// the switch may expand into multiple basic blocks. 8528 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8529 // With FastISel active, we may be splitting blocks, so force creation 8530 // of virtual registers for all non-dead arguments. 8531 if (FastISel) 8532 return A->use_empty(); 8533 8534 const BasicBlock &Entry = A->getParent()->front(); 8535 for (const User *U : A->users()) 8536 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8537 return false; // Use not in entry block. 8538 8539 return true; 8540 } 8541 8542 using ArgCopyElisionMapTy = 8543 DenseMap<const Argument *, 8544 std::pair<const AllocaInst *, const StoreInst *>>; 8545 8546 /// Scan the entry block of the function in FuncInfo for arguments that look 8547 /// like copies into a local alloca. Record any copied arguments in 8548 /// ArgCopyElisionCandidates. 8549 static void 8550 findArgumentCopyElisionCandidates(const DataLayout &DL, 8551 FunctionLoweringInfo *FuncInfo, 8552 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8553 // Record the state of every static alloca used in the entry block. Argument 8554 // allocas are all used in the entry block, so we need approximately as many 8555 // entries as we have arguments. 8556 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8557 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8558 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8559 StaticAllocas.reserve(NumArgs * 2); 8560 8561 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8562 if (!V) 8563 return nullptr; 8564 V = V->stripPointerCasts(); 8565 const auto *AI = dyn_cast<AllocaInst>(V); 8566 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8567 return nullptr; 8568 auto Iter = StaticAllocas.insert({AI, Unknown}); 8569 return &Iter.first->second; 8570 }; 8571 8572 // Look for stores of arguments to static allocas. Look through bitcasts and 8573 // GEPs to handle type coercions, as long as the alloca is fully initialized 8574 // by the store. Any non-store use of an alloca escapes it and any subsequent 8575 // unanalyzed store might write it. 8576 // FIXME: Handle structs initialized with multiple stores. 8577 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8578 // Look for stores, and handle non-store uses conservatively. 8579 const auto *SI = dyn_cast<StoreInst>(&I); 8580 if (!SI) { 8581 // We will look through cast uses, so ignore them completely. 8582 if (I.isCast()) 8583 continue; 8584 // Ignore debug info intrinsics, they don't escape or store to allocas. 8585 if (isa<DbgInfoIntrinsic>(I)) 8586 continue; 8587 // This is an unknown instruction. Assume it escapes or writes to all 8588 // static alloca operands. 8589 for (const Use &U : I.operands()) { 8590 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8591 *Info = StaticAllocaInfo::Clobbered; 8592 } 8593 continue; 8594 } 8595 8596 // If the stored value is a static alloca, mark it as escaped. 8597 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8598 *Info = StaticAllocaInfo::Clobbered; 8599 8600 // Check if the destination is a static alloca. 8601 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8602 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8603 if (!Info) 8604 continue; 8605 const AllocaInst *AI = cast<AllocaInst>(Dst); 8606 8607 // Skip allocas that have been initialized or clobbered. 8608 if (*Info != StaticAllocaInfo::Unknown) 8609 continue; 8610 8611 // Check if the stored value is an argument, and that this store fully 8612 // initializes the alloca. Don't elide copies from the same argument twice. 8613 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8614 const auto *Arg = dyn_cast<Argument>(Val); 8615 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8616 Arg->getType()->isEmptyTy() || 8617 DL.getTypeStoreSize(Arg->getType()) != 8618 DL.getTypeAllocSize(AI->getAllocatedType()) || 8619 ArgCopyElisionCandidates.count(Arg)) { 8620 *Info = StaticAllocaInfo::Clobbered; 8621 continue; 8622 } 8623 8624 DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n'); 8625 8626 // Mark this alloca and store for argument copy elision. 8627 *Info = StaticAllocaInfo::Elidable; 8628 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8629 8630 // Stop scanning if we've seen all arguments. This will happen early in -O0 8631 // builds, which is useful, because -O0 builds have large entry blocks and 8632 // many allocas. 8633 if (ArgCopyElisionCandidates.size() == NumArgs) 8634 break; 8635 } 8636 } 8637 8638 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8639 /// ArgVal is a load from a suitable fixed stack object. 8640 static void tryToElideArgumentCopy( 8641 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8642 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8643 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8644 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8645 SDValue ArgVal, bool &ArgHasUses) { 8646 // Check if this is a load from a fixed stack object. 8647 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8648 if (!LNode) 8649 return; 8650 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8651 if (!FINode) 8652 return; 8653 8654 // Check that the fixed stack object is the right size and alignment. 8655 // Look at the alignment that the user wrote on the alloca instead of looking 8656 // at the stack object. 8657 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8658 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8659 const AllocaInst *AI = ArgCopyIter->second.first; 8660 int FixedIndex = FINode->getIndex(); 8661 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8662 int OldIndex = AllocaIndex; 8663 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8664 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8665 DEBUG(dbgs() << " argument copy elision failed due to bad fixed stack " 8666 "object size\n"); 8667 return; 8668 } 8669 unsigned RequiredAlignment = AI->getAlignment(); 8670 if (!RequiredAlignment) { 8671 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8672 AI->getAllocatedType()); 8673 } 8674 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8675 DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8676 "greater than stack argument alignment (" 8677 << RequiredAlignment << " vs " 8678 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8679 return; 8680 } 8681 8682 // Perform the elision. Delete the old stack object and replace its only use 8683 // in the variable info map. Mark the stack object as mutable. 8684 DEBUG({ 8685 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8686 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8687 << '\n'; 8688 }); 8689 MFI.RemoveStackObject(OldIndex); 8690 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8691 AllocaIndex = FixedIndex; 8692 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8693 Chains.push_back(ArgVal.getValue(1)); 8694 8695 // Avoid emitting code for the store implementing the copy. 8696 const StoreInst *SI = ArgCopyIter->second.second; 8697 ElidedArgCopyInstrs.insert(SI); 8698 8699 // Check for uses of the argument again so that we can avoid exporting ArgVal 8700 // if it is't used by anything other than the store. 8701 for (const Value *U : Arg.users()) { 8702 if (U != SI) { 8703 ArgHasUses = true; 8704 break; 8705 } 8706 } 8707 } 8708 8709 void SelectionDAGISel::LowerArguments(const Function &F) { 8710 SelectionDAG &DAG = SDB->DAG; 8711 SDLoc dl = SDB->getCurSDLoc(); 8712 const DataLayout &DL = DAG.getDataLayout(); 8713 SmallVector<ISD::InputArg, 16> Ins; 8714 8715 if (!FuncInfo->CanLowerReturn) { 8716 // Put in an sret pointer parameter before all the other parameters. 8717 SmallVector<EVT, 1> ValueVTs; 8718 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8719 F.getReturnType()->getPointerTo( 8720 DAG.getDataLayout().getAllocaAddrSpace()), 8721 ValueVTs); 8722 8723 // NOTE: Assuming that a pointer will never break down to more than one VT 8724 // or one register. 8725 ISD::ArgFlagsTy Flags; 8726 Flags.setSRet(); 8727 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8728 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8729 ISD::InputArg::NoArgIndex, 0); 8730 Ins.push_back(RetArg); 8731 } 8732 8733 // Look for stores of arguments to static allocas. Mark such arguments with a 8734 // flag to ask the target to give us the memory location of that argument if 8735 // available. 8736 ArgCopyElisionMapTy ArgCopyElisionCandidates; 8737 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 8738 8739 // Set up the incoming argument description vector. 8740 for (const Argument &Arg : F.args()) { 8741 unsigned ArgNo = Arg.getArgNo(); 8742 SmallVector<EVT, 4> ValueVTs; 8743 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8744 bool isArgValueUsed = !Arg.use_empty(); 8745 unsigned PartBase = 0; 8746 Type *FinalType = Arg.getType(); 8747 if (Arg.hasAttribute(Attribute::ByVal)) 8748 FinalType = cast<PointerType>(FinalType)->getElementType(); 8749 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 8750 FinalType, F.getCallingConv(), F.isVarArg()); 8751 for (unsigned Value = 0, NumValues = ValueVTs.size(); 8752 Value != NumValues; ++Value) { 8753 EVT VT = ValueVTs[Value]; 8754 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 8755 ISD::ArgFlagsTy Flags; 8756 8757 // Certain targets (such as MIPS), may have a different ABI alignment 8758 // for a type depending on the context. Give the target a chance to 8759 // specify the alignment it wants. 8760 unsigned OriginalAlignment = 8761 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 8762 8763 if (Arg.hasAttribute(Attribute::ZExt)) 8764 Flags.setZExt(); 8765 if (Arg.hasAttribute(Attribute::SExt)) 8766 Flags.setSExt(); 8767 if (Arg.hasAttribute(Attribute::InReg)) { 8768 // If we are using vectorcall calling convention, a structure that is 8769 // passed InReg - is surely an HVA 8770 if (F.getCallingConv() == CallingConv::X86_VectorCall && 8771 isa<StructType>(Arg.getType())) { 8772 // The first value of a structure is marked 8773 if (0 == Value) 8774 Flags.setHvaStart(); 8775 Flags.setHva(); 8776 } 8777 // Set InReg Flag 8778 Flags.setInReg(); 8779 } 8780 if (Arg.hasAttribute(Attribute::StructRet)) 8781 Flags.setSRet(); 8782 if (Arg.hasAttribute(Attribute::SwiftSelf)) 8783 Flags.setSwiftSelf(); 8784 if (Arg.hasAttribute(Attribute::SwiftError)) 8785 Flags.setSwiftError(); 8786 if (Arg.hasAttribute(Attribute::ByVal)) 8787 Flags.setByVal(); 8788 if (Arg.hasAttribute(Attribute::InAlloca)) { 8789 Flags.setInAlloca(); 8790 // Set the byval flag for CCAssignFn callbacks that don't know about 8791 // inalloca. This way we can know how many bytes we should've allocated 8792 // and how many bytes a callee cleanup function will pop. If we port 8793 // inalloca to more targets, we'll have to add custom inalloca handling 8794 // in the various CC lowering callbacks. 8795 Flags.setByVal(); 8796 } 8797 if (F.getCallingConv() == CallingConv::X86_INTR) { 8798 // IA Interrupt passes frame (1st parameter) by value in the stack. 8799 if (ArgNo == 0) 8800 Flags.setByVal(); 8801 } 8802 if (Flags.isByVal() || Flags.isInAlloca()) { 8803 PointerType *Ty = cast<PointerType>(Arg.getType()); 8804 Type *ElementTy = Ty->getElementType(); 8805 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8806 // For ByVal, alignment should be passed from FE. BE will guess if 8807 // this info is not there but there are cases it cannot get right. 8808 unsigned FrameAlign; 8809 if (Arg.getParamAlignment()) 8810 FrameAlign = Arg.getParamAlignment(); 8811 else 8812 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 8813 Flags.setByValAlign(FrameAlign); 8814 } 8815 if (Arg.hasAttribute(Attribute::Nest)) 8816 Flags.setNest(); 8817 if (NeedsRegBlock) 8818 Flags.setInConsecutiveRegs(); 8819 Flags.setOrigAlign(OriginalAlignment); 8820 if (ArgCopyElisionCandidates.count(&Arg)) 8821 Flags.setCopyElisionCandidate(); 8822 8823 MVT RegisterVT = 8824 TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT); 8825 unsigned NumRegs = 8826 TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT); 8827 for (unsigned i = 0; i != NumRegs; ++i) { 8828 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 8829 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 8830 if (NumRegs > 1 && i == 0) 8831 MyFlags.Flags.setSplit(); 8832 // if it isn't first piece, alignment must be 1 8833 else if (i > 0) { 8834 MyFlags.Flags.setOrigAlign(1); 8835 if (i == NumRegs - 1) 8836 MyFlags.Flags.setSplitEnd(); 8837 } 8838 Ins.push_back(MyFlags); 8839 } 8840 if (NeedsRegBlock && Value == NumValues - 1) 8841 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 8842 PartBase += VT.getStoreSize(); 8843 } 8844 } 8845 8846 // Call the target to set up the argument values. 8847 SmallVector<SDValue, 8> InVals; 8848 SDValue NewRoot = TLI->LowerFormalArguments( 8849 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 8850 8851 // Verify that the target's LowerFormalArguments behaved as expected. 8852 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 8853 "LowerFormalArguments didn't return a valid chain!"); 8854 assert(InVals.size() == Ins.size() && 8855 "LowerFormalArguments didn't emit the correct number of values!"); 8856 DEBUG({ 8857 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 8858 assert(InVals[i].getNode() && 8859 "LowerFormalArguments emitted a null value!"); 8860 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 8861 "LowerFormalArguments emitted a value with the wrong type!"); 8862 } 8863 }); 8864 8865 // Update the DAG with the new chain value resulting from argument lowering. 8866 DAG.setRoot(NewRoot); 8867 8868 // Set up the argument values. 8869 unsigned i = 0; 8870 if (!FuncInfo->CanLowerReturn) { 8871 // Create a virtual register for the sret pointer, and put in a copy 8872 // from the sret argument into it. 8873 SmallVector<EVT, 1> ValueVTs; 8874 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8875 F.getReturnType()->getPointerTo( 8876 DAG.getDataLayout().getAllocaAddrSpace()), 8877 ValueVTs); 8878 MVT VT = ValueVTs[0].getSimpleVT(); 8879 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 8880 Optional<ISD::NodeType> AssertOp = None; 8881 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 8882 RegVT, VT, nullptr, AssertOp); 8883 8884 MachineFunction& MF = SDB->DAG.getMachineFunction(); 8885 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 8886 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 8887 FuncInfo->DemoteRegister = SRetReg; 8888 NewRoot = 8889 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 8890 DAG.setRoot(NewRoot); 8891 8892 // i indexes lowered arguments. Bump it past the hidden sret argument. 8893 ++i; 8894 } 8895 8896 SmallVector<SDValue, 4> Chains; 8897 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 8898 for (const Argument &Arg : F.args()) { 8899 SmallVector<SDValue, 4> ArgValues; 8900 SmallVector<EVT, 4> ValueVTs; 8901 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8902 unsigned NumValues = ValueVTs.size(); 8903 if (NumValues == 0) 8904 continue; 8905 8906 bool ArgHasUses = !Arg.use_empty(); 8907 8908 // Elide the copying store if the target loaded this argument from a 8909 // suitable fixed stack object. 8910 if (Ins[i].Flags.isCopyElisionCandidate()) { 8911 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 8912 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 8913 InVals[i], ArgHasUses); 8914 } 8915 8916 // If this argument is unused then remember its value. It is used to generate 8917 // debugging information. 8918 bool isSwiftErrorArg = 8919 TLI->supportSwiftError() && 8920 Arg.hasAttribute(Attribute::SwiftError); 8921 if (!ArgHasUses && !isSwiftErrorArg) { 8922 SDB->setUnusedArgValue(&Arg, InVals[i]); 8923 8924 // Also remember any frame index for use in FastISel. 8925 if (FrameIndexSDNode *FI = 8926 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 8927 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 8928 } 8929 8930 for (unsigned Val = 0; Val != NumValues; ++Val) { 8931 EVT VT = ValueVTs[Val]; 8932 MVT PartVT = 8933 TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT); 8934 unsigned NumParts = 8935 TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT); 8936 8937 // Even an apparant 'unused' swifterror argument needs to be returned. So 8938 // we do generate a copy for it that can be used on return from the 8939 // function. 8940 if (ArgHasUses || isSwiftErrorArg) { 8941 Optional<ISD::NodeType> AssertOp; 8942 if (Arg.hasAttribute(Attribute::SExt)) 8943 AssertOp = ISD::AssertSext; 8944 else if (Arg.hasAttribute(Attribute::ZExt)) 8945 AssertOp = ISD::AssertZext; 8946 8947 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 8948 PartVT, VT, nullptr, AssertOp, 8949 true)); 8950 } 8951 8952 i += NumParts; 8953 } 8954 8955 // We don't need to do anything else for unused arguments. 8956 if (ArgValues.empty()) 8957 continue; 8958 8959 // Note down frame index. 8960 if (FrameIndexSDNode *FI = 8961 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 8962 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 8963 8964 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 8965 SDB->getCurSDLoc()); 8966 8967 SDB->setValue(&Arg, Res); 8968 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 8969 // We want to associate the argument with the frame index, among 8970 // involved operands, that correspond to the lowest address. The 8971 // getCopyFromParts function, called earlier, is swapping the order of 8972 // the operands to BUILD_PAIR depending on endianness. The result of 8973 // that swapping is that the least significant bits of the argument will 8974 // be in the first operand of the BUILD_PAIR node, and the most 8975 // significant bits will be in the second operand. 8976 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8977 if (LoadSDNode *LNode = 8978 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 8979 if (FrameIndexSDNode *FI = 8980 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 8981 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 8982 } 8983 8984 // Update the SwiftErrorVRegDefMap. 8985 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 8986 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 8987 if (TargetRegisterInfo::isVirtualRegister(Reg)) 8988 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 8989 FuncInfo->SwiftErrorArg, Reg); 8990 } 8991 8992 // If this argument is live outside of the entry block, insert a copy from 8993 // wherever we got it to the vreg that other BB's will reference it as. 8994 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 8995 // If we can, though, try to skip creating an unnecessary vreg. 8996 // FIXME: This isn't very clean... it would be nice to make this more 8997 // general. It's also subtly incompatible with the hacks FastISel 8998 // uses with vregs. 8999 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9000 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9001 FuncInfo->ValueMap[&Arg] = Reg; 9002 continue; 9003 } 9004 } 9005 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9006 FuncInfo->InitializeRegForValue(&Arg); 9007 SDB->CopyToExportRegsIfNeeded(&Arg); 9008 } 9009 } 9010 9011 if (!Chains.empty()) { 9012 Chains.push_back(NewRoot); 9013 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9014 } 9015 9016 DAG.setRoot(NewRoot); 9017 9018 assert(i == InVals.size() && "Argument register count mismatch!"); 9019 9020 // If any argument copy elisions occurred and we have debug info, update the 9021 // stale frame indices used in the dbg.declare variable info table. 9022 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9023 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9024 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9025 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9026 if (I != ArgCopyElisionFrameIndexMap.end()) 9027 VI.Slot = I->second; 9028 } 9029 } 9030 9031 // Finally, if the target has anything special to do, allow it to do so. 9032 EmitFunctionEntryCode(); 9033 } 9034 9035 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9036 /// ensure constants are generated when needed. Remember the virtual registers 9037 /// that need to be added to the Machine PHI nodes as input. We cannot just 9038 /// directly add them, because expansion might result in multiple MBB's for one 9039 /// BB. As such, the start of the BB might correspond to a different MBB than 9040 /// the end. 9041 void 9042 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9043 const TerminatorInst *TI = LLVMBB->getTerminator(); 9044 9045 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9046 9047 // Check PHI nodes in successors that expect a value to be available from this 9048 // block. 9049 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9050 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9051 if (!isa<PHINode>(SuccBB->begin())) continue; 9052 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9053 9054 // If this terminator has multiple identical successors (common for 9055 // switches), only handle each succ once. 9056 if (!SuccsHandled.insert(SuccMBB).second) 9057 continue; 9058 9059 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9060 9061 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9062 // nodes and Machine PHI nodes, but the incoming operands have not been 9063 // emitted yet. 9064 for (const PHINode &PN : SuccBB->phis()) { 9065 // Ignore dead phi's. 9066 if (PN.use_empty()) 9067 continue; 9068 9069 // Skip empty types 9070 if (PN.getType()->isEmptyTy()) 9071 continue; 9072 9073 unsigned Reg; 9074 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9075 9076 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9077 unsigned &RegOut = ConstantsOut[C]; 9078 if (RegOut == 0) { 9079 RegOut = FuncInfo.CreateRegs(C->getType()); 9080 CopyValueToVirtualRegister(C, RegOut); 9081 } 9082 Reg = RegOut; 9083 } else { 9084 DenseMap<const Value *, unsigned>::iterator I = 9085 FuncInfo.ValueMap.find(PHIOp); 9086 if (I != FuncInfo.ValueMap.end()) 9087 Reg = I->second; 9088 else { 9089 assert(isa<AllocaInst>(PHIOp) && 9090 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9091 "Didn't codegen value into a register!??"); 9092 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9093 CopyValueToVirtualRegister(PHIOp, Reg); 9094 } 9095 } 9096 9097 // Remember that this register needs to added to the machine PHI node as 9098 // the input for this MBB. 9099 SmallVector<EVT, 4> ValueVTs; 9100 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9101 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9102 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9103 EVT VT = ValueVTs[vti]; 9104 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9105 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9106 FuncInfo.PHINodesToUpdate.push_back( 9107 std::make_pair(&*MBBI++, Reg + i)); 9108 Reg += NumRegisters; 9109 } 9110 } 9111 } 9112 9113 ConstantsOut.clear(); 9114 } 9115 9116 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9117 /// is 0. 9118 MachineBasicBlock * 9119 SelectionDAGBuilder::StackProtectorDescriptor:: 9120 AddSuccessorMBB(const BasicBlock *BB, 9121 MachineBasicBlock *ParentMBB, 9122 bool IsLikely, 9123 MachineBasicBlock *SuccMBB) { 9124 // If SuccBB has not been created yet, create it. 9125 if (!SuccMBB) { 9126 MachineFunction *MF = ParentMBB->getParent(); 9127 MachineFunction::iterator BBI(ParentMBB); 9128 SuccMBB = MF->CreateMachineBasicBlock(BB); 9129 MF->insert(++BBI, SuccMBB); 9130 } 9131 // Add it as a successor of ParentMBB. 9132 ParentMBB->addSuccessor( 9133 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9134 return SuccMBB; 9135 } 9136 9137 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9138 MachineFunction::iterator I(MBB); 9139 if (++I == FuncInfo.MF->end()) 9140 return nullptr; 9141 return &*I; 9142 } 9143 9144 /// During lowering new call nodes can be created (such as memset, etc.). 9145 /// Those will become new roots of the current DAG, but complications arise 9146 /// when they are tail calls. In such cases, the call lowering will update 9147 /// the root, but the builder still needs to know that a tail call has been 9148 /// lowered in order to avoid generating an additional return. 9149 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9150 // If the node is null, we do have a tail call. 9151 if (MaybeTC.getNode() != nullptr) 9152 DAG.setRoot(MaybeTC); 9153 else 9154 HasTailCall = true; 9155 } 9156 9157 uint64_t 9158 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9159 unsigned First, unsigned Last) const { 9160 assert(Last >= First); 9161 const APInt &LowCase = Clusters[First].Low->getValue(); 9162 const APInt &HighCase = Clusters[Last].High->getValue(); 9163 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9164 9165 // FIXME: A range of consecutive cases has 100% density, but only requires one 9166 // comparison to lower. We should discriminate against such consecutive ranges 9167 // in jump tables. 9168 9169 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9170 } 9171 9172 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9173 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9174 unsigned Last) const { 9175 assert(Last >= First); 9176 assert(TotalCases[Last] >= TotalCases[First]); 9177 uint64_t NumCases = 9178 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9179 return NumCases; 9180 } 9181 9182 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9183 unsigned First, unsigned Last, 9184 const SwitchInst *SI, 9185 MachineBasicBlock *DefaultMBB, 9186 CaseCluster &JTCluster) { 9187 assert(First <= Last); 9188 9189 auto Prob = BranchProbability::getZero(); 9190 unsigned NumCmps = 0; 9191 std::vector<MachineBasicBlock*> Table; 9192 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9193 9194 // Initialize probabilities in JTProbs. 9195 for (unsigned I = First; I <= Last; ++I) 9196 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9197 9198 for (unsigned I = First; I <= Last; ++I) { 9199 assert(Clusters[I].Kind == CC_Range); 9200 Prob += Clusters[I].Prob; 9201 const APInt &Low = Clusters[I].Low->getValue(); 9202 const APInt &High = Clusters[I].High->getValue(); 9203 NumCmps += (Low == High) ? 1 : 2; 9204 if (I != First) { 9205 // Fill the gap between this and the previous cluster. 9206 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9207 assert(PreviousHigh.slt(Low)); 9208 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9209 for (uint64_t J = 0; J < Gap; J++) 9210 Table.push_back(DefaultMBB); 9211 } 9212 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9213 for (uint64_t J = 0; J < ClusterSize; ++J) 9214 Table.push_back(Clusters[I].MBB); 9215 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9216 } 9217 9218 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9219 unsigned NumDests = JTProbs.size(); 9220 if (TLI.isSuitableForBitTests( 9221 NumDests, NumCmps, Clusters[First].Low->getValue(), 9222 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9223 // Clusters[First..Last] should be lowered as bit tests instead. 9224 return false; 9225 } 9226 9227 // Create the MBB that will load from and jump through the table. 9228 // Note: We create it here, but it's not inserted into the function yet. 9229 MachineFunction *CurMF = FuncInfo.MF; 9230 MachineBasicBlock *JumpTableMBB = 9231 CurMF->CreateMachineBasicBlock(SI->getParent()); 9232 9233 // Add successors. Note: use table order for determinism. 9234 SmallPtrSet<MachineBasicBlock *, 8> Done; 9235 for (MachineBasicBlock *Succ : Table) { 9236 if (Done.count(Succ)) 9237 continue; 9238 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9239 Done.insert(Succ); 9240 } 9241 JumpTableMBB->normalizeSuccProbs(); 9242 9243 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9244 ->createJumpTableIndex(Table); 9245 9246 // Set up the jump table info. 9247 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9248 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9249 Clusters[Last].High->getValue(), SI->getCondition(), 9250 nullptr, false); 9251 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9252 9253 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9254 JTCases.size() - 1, Prob); 9255 return true; 9256 } 9257 9258 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9259 const SwitchInst *SI, 9260 MachineBasicBlock *DefaultMBB) { 9261 #ifndef NDEBUG 9262 // Clusters must be non-empty, sorted, and only contain Range clusters. 9263 assert(!Clusters.empty()); 9264 for (CaseCluster &C : Clusters) 9265 assert(C.Kind == CC_Range); 9266 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9267 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9268 #endif 9269 9270 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9271 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9272 return; 9273 9274 const int64_t N = Clusters.size(); 9275 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9276 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9277 9278 if (N < 2 || N < MinJumpTableEntries) 9279 return; 9280 9281 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9282 SmallVector<unsigned, 8> TotalCases(N); 9283 for (unsigned i = 0; i < N; ++i) { 9284 const APInt &Hi = Clusters[i].High->getValue(); 9285 const APInt &Lo = Clusters[i].Low->getValue(); 9286 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9287 if (i != 0) 9288 TotalCases[i] += TotalCases[i - 1]; 9289 } 9290 9291 // Cheap case: the whole range may be suitable for jump table. 9292 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9293 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9294 assert(NumCases < UINT64_MAX / 100); 9295 assert(Range >= NumCases); 9296 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9297 CaseCluster JTCluster; 9298 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9299 Clusters[0] = JTCluster; 9300 Clusters.resize(1); 9301 return; 9302 } 9303 } 9304 9305 // The algorithm below is not suitable for -O0. 9306 if (TM.getOptLevel() == CodeGenOpt::None) 9307 return; 9308 9309 // Split Clusters into minimum number of dense partitions. The algorithm uses 9310 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9311 // for the Case Statement'" (1994), but builds the MinPartitions array in 9312 // reverse order to make it easier to reconstruct the partitions in ascending 9313 // order. In the choice between two optimal partitionings, it picks the one 9314 // which yields more jump tables. 9315 9316 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9317 SmallVector<unsigned, 8> MinPartitions(N); 9318 // LastElement[i] is the last element of the partition starting at i. 9319 SmallVector<unsigned, 8> LastElement(N); 9320 // PartitionsScore[i] is used to break ties when choosing between two 9321 // partitionings resulting in the same number of partitions. 9322 SmallVector<unsigned, 8> PartitionsScore(N); 9323 // For PartitionsScore, a small number of comparisons is considered as good as 9324 // a jump table and a single comparison is considered better than a jump 9325 // table. 9326 enum PartitionScores : unsigned { 9327 NoTable = 0, 9328 Table = 1, 9329 FewCases = 1, 9330 SingleCase = 2 9331 }; 9332 9333 // Base case: There is only one way to partition Clusters[N-1]. 9334 MinPartitions[N - 1] = 1; 9335 LastElement[N - 1] = N - 1; 9336 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9337 9338 // Note: loop indexes are signed to avoid underflow. 9339 for (int64_t i = N - 2; i >= 0; i--) { 9340 // Find optimal partitioning of Clusters[i..N-1]. 9341 // Baseline: Put Clusters[i] into a partition on its own. 9342 MinPartitions[i] = MinPartitions[i + 1] + 1; 9343 LastElement[i] = i; 9344 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9345 9346 // Search for a solution that results in fewer partitions. 9347 for (int64_t j = N - 1; j > i; j--) { 9348 // Try building a partition from Clusters[i..j]. 9349 uint64_t Range = getJumpTableRange(Clusters, i, j); 9350 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9351 assert(NumCases < UINT64_MAX / 100); 9352 assert(Range >= NumCases); 9353 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9354 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9355 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9356 int64_t NumEntries = j - i + 1; 9357 9358 if (NumEntries == 1) 9359 Score += PartitionScores::SingleCase; 9360 else if (NumEntries <= SmallNumberOfEntries) 9361 Score += PartitionScores::FewCases; 9362 else if (NumEntries >= MinJumpTableEntries) 9363 Score += PartitionScores::Table; 9364 9365 // If this leads to fewer partitions, or to the same number of 9366 // partitions with better score, it is a better partitioning. 9367 if (NumPartitions < MinPartitions[i] || 9368 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9369 MinPartitions[i] = NumPartitions; 9370 LastElement[i] = j; 9371 PartitionsScore[i] = Score; 9372 } 9373 } 9374 } 9375 } 9376 9377 // Iterate over the partitions, replacing some with jump tables in-place. 9378 unsigned DstIndex = 0; 9379 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9380 Last = LastElement[First]; 9381 assert(Last >= First); 9382 assert(DstIndex <= First); 9383 unsigned NumClusters = Last - First + 1; 9384 9385 CaseCluster JTCluster; 9386 if (NumClusters >= MinJumpTableEntries && 9387 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9388 Clusters[DstIndex++] = JTCluster; 9389 } else { 9390 for (unsigned I = First; I <= Last; ++I) 9391 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9392 } 9393 } 9394 Clusters.resize(DstIndex); 9395 } 9396 9397 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9398 unsigned First, unsigned Last, 9399 const SwitchInst *SI, 9400 CaseCluster &BTCluster) { 9401 assert(First <= Last); 9402 if (First == Last) 9403 return false; 9404 9405 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9406 unsigned NumCmps = 0; 9407 for (int64_t I = First; I <= Last; ++I) { 9408 assert(Clusters[I].Kind == CC_Range); 9409 Dests.set(Clusters[I].MBB->getNumber()); 9410 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9411 } 9412 unsigned NumDests = Dests.count(); 9413 9414 APInt Low = Clusters[First].Low->getValue(); 9415 APInt High = Clusters[Last].High->getValue(); 9416 assert(Low.slt(High)); 9417 9418 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9419 const DataLayout &DL = DAG.getDataLayout(); 9420 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9421 return false; 9422 9423 APInt LowBound; 9424 APInt CmpRange; 9425 9426 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9427 assert(TLI.rangeFitsInWord(Low, High, DL) && 9428 "Case range must fit in bit mask!"); 9429 9430 // Check if the clusters cover a contiguous range such that no value in the 9431 // range will jump to the default statement. 9432 bool ContiguousRange = true; 9433 for (int64_t I = First + 1; I <= Last; ++I) { 9434 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9435 ContiguousRange = false; 9436 break; 9437 } 9438 } 9439 9440 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9441 // Optimize the case where all the case values fit in a word without having 9442 // to subtract minValue. In this case, we can optimize away the subtraction. 9443 LowBound = APInt::getNullValue(Low.getBitWidth()); 9444 CmpRange = High; 9445 ContiguousRange = false; 9446 } else { 9447 LowBound = Low; 9448 CmpRange = High - Low; 9449 } 9450 9451 CaseBitsVector CBV; 9452 auto TotalProb = BranchProbability::getZero(); 9453 for (unsigned i = First; i <= Last; ++i) { 9454 // Find the CaseBits for this destination. 9455 unsigned j; 9456 for (j = 0; j < CBV.size(); ++j) 9457 if (CBV[j].BB == Clusters[i].MBB) 9458 break; 9459 if (j == CBV.size()) 9460 CBV.push_back( 9461 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9462 CaseBits *CB = &CBV[j]; 9463 9464 // Update Mask, Bits and ExtraProb. 9465 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9466 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9467 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9468 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9469 CB->Bits += Hi - Lo + 1; 9470 CB->ExtraProb += Clusters[i].Prob; 9471 TotalProb += Clusters[i].Prob; 9472 } 9473 9474 BitTestInfo BTI; 9475 std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) { 9476 // Sort by probability first, number of bits second, bit mask third. 9477 if (a.ExtraProb != b.ExtraProb) 9478 return a.ExtraProb > b.ExtraProb; 9479 if (a.Bits != b.Bits) 9480 return a.Bits > b.Bits; 9481 return a.Mask < b.Mask; 9482 }); 9483 9484 for (auto &CB : CBV) { 9485 MachineBasicBlock *BitTestBB = 9486 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9487 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9488 } 9489 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9490 SI->getCondition(), -1U, MVT::Other, false, 9491 ContiguousRange, nullptr, nullptr, std::move(BTI), 9492 TotalProb); 9493 9494 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9495 BitTestCases.size() - 1, TotalProb); 9496 return true; 9497 } 9498 9499 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9500 const SwitchInst *SI) { 9501 // Partition Clusters into as few subsets as possible, where each subset has a 9502 // range that fits in a machine word and has <= 3 unique destinations. 9503 9504 #ifndef NDEBUG 9505 // Clusters must be sorted and contain Range or JumpTable clusters. 9506 assert(!Clusters.empty()); 9507 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9508 for (const CaseCluster &C : Clusters) 9509 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9510 for (unsigned i = 1; i < Clusters.size(); ++i) 9511 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9512 #endif 9513 9514 // The algorithm below is not suitable for -O0. 9515 if (TM.getOptLevel() == CodeGenOpt::None) 9516 return; 9517 9518 // If target does not have legal shift left, do not emit bit tests at all. 9519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9520 const DataLayout &DL = DAG.getDataLayout(); 9521 9522 EVT PTy = TLI.getPointerTy(DL); 9523 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9524 return; 9525 9526 int BitWidth = PTy.getSizeInBits(); 9527 const int64_t N = Clusters.size(); 9528 9529 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9530 SmallVector<unsigned, 8> MinPartitions(N); 9531 // LastElement[i] is the last element of the partition starting at i. 9532 SmallVector<unsigned, 8> LastElement(N); 9533 9534 // FIXME: This might not be the best algorithm for finding bit test clusters. 9535 9536 // Base case: There is only one way to partition Clusters[N-1]. 9537 MinPartitions[N - 1] = 1; 9538 LastElement[N - 1] = N - 1; 9539 9540 // Note: loop indexes are signed to avoid underflow. 9541 for (int64_t i = N - 2; i >= 0; --i) { 9542 // Find optimal partitioning of Clusters[i..N-1]. 9543 // Baseline: Put Clusters[i] into a partition on its own. 9544 MinPartitions[i] = MinPartitions[i + 1] + 1; 9545 LastElement[i] = i; 9546 9547 // Search for a solution that results in fewer partitions. 9548 // Note: the search is limited by BitWidth, reducing time complexity. 9549 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9550 // Try building a partition from Clusters[i..j]. 9551 9552 // Check the range. 9553 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9554 Clusters[j].High->getValue(), DL)) 9555 continue; 9556 9557 // Check nbr of destinations and cluster types. 9558 // FIXME: This works, but doesn't seem very efficient. 9559 bool RangesOnly = true; 9560 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9561 for (int64_t k = i; k <= j; k++) { 9562 if (Clusters[k].Kind != CC_Range) { 9563 RangesOnly = false; 9564 break; 9565 } 9566 Dests.set(Clusters[k].MBB->getNumber()); 9567 } 9568 if (!RangesOnly || Dests.count() > 3) 9569 break; 9570 9571 // Check if it's a better partition. 9572 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9573 if (NumPartitions < MinPartitions[i]) { 9574 // Found a better partition. 9575 MinPartitions[i] = NumPartitions; 9576 LastElement[i] = j; 9577 } 9578 } 9579 } 9580 9581 // Iterate over the partitions, replacing with bit-test clusters in-place. 9582 unsigned DstIndex = 0; 9583 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9584 Last = LastElement[First]; 9585 assert(First <= Last); 9586 assert(DstIndex <= First); 9587 9588 CaseCluster BitTestCluster; 9589 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9590 Clusters[DstIndex++] = BitTestCluster; 9591 } else { 9592 size_t NumClusters = Last - First + 1; 9593 std::memmove(&Clusters[DstIndex], &Clusters[First], 9594 sizeof(Clusters[0]) * NumClusters); 9595 DstIndex += NumClusters; 9596 } 9597 } 9598 Clusters.resize(DstIndex); 9599 } 9600 9601 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9602 MachineBasicBlock *SwitchMBB, 9603 MachineBasicBlock *DefaultMBB) { 9604 MachineFunction *CurMF = FuncInfo.MF; 9605 MachineBasicBlock *NextMBB = nullptr; 9606 MachineFunction::iterator BBI(W.MBB); 9607 if (++BBI != FuncInfo.MF->end()) 9608 NextMBB = &*BBI; 9609 9610 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9611 9612 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9613 9614 if (Size == 2 && W.MBB == SwitchMBB) { 9615 // If any two of the cases has the same destination, and if one value 9616 // is the same as the other, but has one bit unset that the other has set, 9617 // use bit manipulation to do two compares at once. For example: 9618 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9619 // TODO: This could be extended to merge any 2 cases in switches with 3 9620 // cases. 9621 // TODO: Handle cases where W.CaseBB != SwitchBB. 9622 CaseCluster &Small = *W.FirstCluster; 9623 CaseCluster &Big = *W.LastCluster; 9624 9625 if (Small.Low == Small.High && Big.Low == Big.High && 9626 Small.MBB == Big.MBB) { 9627 const APInt &SmallValue = Small.Low->getValue(); 9628 const APInt &BigValue = Big.Low->getValue(); 9629 9630 // Check that there is only one bit different. 9631 APInt CommonBit = BigValue ^ SmallValue; 9632 if (CommonBit.isPowerOf2()) { 9633 SDValue CondLHS = getValue(Cond); 9634 EVT VT = CondLHS.getValueType(); 9635 SDLoc DL = getCurSDLoc(); 9636 9637 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9638 DAG.getConstant(CommonBit, DL, VT)); 9639 SDValue Cond = DAG.getSetCC( 9640 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9641 ISD::SETEQ); 9642 9643 // Update successor info. 9644 // Both Small and Big will jump to Small.BB, so we sum up the 9645 // probabilities. 9646 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9647 if (BPI) 9648 addSuccessorWithProb( 9649 SwitchMBB, DefaultMBB, 9650 // The default destination is the first successor in IR. 9651 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9652 else 9653 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9654 9655 // Insert the true branch. 9656 SDValue BrCond = 9657 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9658 DAG.getBasicBlock(Small.MBB)); 9659 // Insert the false branch. 9660 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9661 DAG.getBasicBlock(DefaultMBB)); 9662 9663 DAG.setRoot(BrCond); 9664 return; 9665 } 9666 } 9667 } 9668 9669 if (TM.getOptLevel() != CodeGenOpt::None) { 9670 // Here, we order cases by probability so the most likely case will be 9671 // checked first. However, two clusters can have the same probability in 9672 // which case their relative ordering is non-deterministic. So we use Low 9673 // as a tie-breaker as clusters are guaranteed to never overlap. 9674 std::sort(W.FirstCluster, W.LastCluster + 1, 9675 [](const CaseCluster &a, const CaseCluster &b) { 9676 return a.Prob != b.Prob ? 9677 a.Prob > b.Prob : 9678 a.Low->getValue().slt(b.Low->getValue()); 9679 }); 9680 9681 // Rearrange the case blocks so that the last one falls through if possible 9682 // without without changing the order of probabilities. 9683 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9684 --I; 9685 if (I->Prob > W.LastCluster->Prob) 9686 break; 9687 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9688 std::swap(*I, *W.LastCluster); 9689 break; 9690 } 9691 } 9692 } 9693 9694 // Compute total probability. 9695 BranchProbability DefaultProb = W.DefaultProb; 9696 BranchProbability UnhandledProbs = DefaultProb; 9697 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9698 UnhandledProbs += I->Prob; 9699 9700 MachineBasicBlock *CurMBB = W.MBB; 9701 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9702 MachineBasicBlock *Fallthrough; 9703 if (I == W.LastCluster) { 9704 // For the last cluster, fall through to the default destination. 9705 Fallthrough = DefaultMBB; 9706 } else { 9707 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9708 CurMF->insert(BBI, Fallthrough); 9709 // Put Cond in a virtual register to make it available from the new blocks. 9710 ExportFromCurrentBlock(Cond); 9711 } 9712 UnhandledProbs -= I->Prob; 9713 9714 switch (I->Kind) { 9715 case CC_JumpTable: { 9716 // FIXME: Optimize away range check based on pivot comparisons. 9717 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9718 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9719 9720 // The jump block hasn't been inserted yet; insert it here. 9721 MachineBasicBlock *JumpMBB = JT->MBB; 9722 CurMF->insert(BBI, JumpMBB); 9723 9724 auto JumpProb = I->Prob; 9725 auto FallthroughProb = UnhandledProbs; 9726 9727 // If the default statement is a target of the jump table, we evenly 9728 // distribute the default probability to successors of CurMBB. Also 9729 // update the probability on the edge from JumpMBB to Fallthrough. 9730 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 9731 SE = JumpMBB->succ_end(); 9732 SI != SE; ++SI) { 9733 if (*SI == DefaultMBB) { 9734 JumpProb += DefaultProb / 2; 9735 FallthroughProb -= DefaultProb / 2; 9736 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 9737 JumpMBB->normalizeSuccProbs(); 9738 break; 9739 } 9740 } 9741 9742 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 9743 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 9744 CurMBB->normalizeSuccProbs(); 9745 9746 // The jump table header will be inserted in our current block, do the 9747 // range check, and fall through to our fallthrough block. 9748 JTH->HeaderBB = CurMBB; 9749 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 9750 9751 // If we're in the right place, emit the jump table header right now. 9752 if (CurMBB == SwitchMBB) { 9753 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 9754 JTH->Emitted = true; 9755 } 9756 break; 9757 } 9758 case CC_BitTests: { 9759 // FIXME: Optimize away range check based on pivot comparisons. 9760 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 9761 9762 // The bit test blocks haven't been inserted yet; insert them here. 9763 for (BitTestCase &BTC : BTB->Cases) 9764 CurMF->insert(BBI, BTC.ThisBB); 9765 9766 // Fill in fields of the BitTestBlock. 9767 BTB->Parent = CurMBB; 9768 BTB->Default = Fallthrough; 9769 9770 BTB->DefaultProb = UnhandledProbs; 9771 // If the cases in bit test don't form a contiguous range, we evenly 9772 // distribute the probability on the edge to Fallthrough to two 9773 // successors of CurMBB. 9774 if (!BTB->ContiguousRange) { 9775 BTB->Prob += DefaultProb / 2; 9776 BTB->DefaultProb -= DefaultProb / 2; 9777 } 9778 9779 // If we're in the right place, emit the bit test header right now. 9780 if (CurMBB == SwitchMBB) { 9781 visitBitTestHeader(*BTB, SwitchMBB); 9782 BTB->Emitted = true; 9783 } 9784 break; 9785 } 9786 case CC_Range: { 9787 const Value *RHS, *LHS, *MHS; 9788 ISD::CondCode CC; 9789 if (I->Low == I->High) { 9790 // Check Cond == I->Low. 9791 CC = ISD::SETEQ; 9792 LHS = Cond; 9793 RHS=I->Low; 9794 MHS = nullptr; 9795 } else { 9796 // Check I->Low <= Cond <= I->High. 9797 CC = ISD::SETLE; 9798 LHS = I->Low; 9799 MHS = Cond; 9800 RHS = I->High; 9801 } 9802 9803 // The false probability is the sum of all unhandled cases. 9804 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 9805 getCurSDLoc(), I->Prob, UnhandledProbs); 9806 9807 if (CurMBB == SwitchMBB) 9808 visitSwitchCase(CB, SwitchMBB); 9809 else 9810 SwitchCases.push_back(CB); 9811 9812 break; 9813 } 9814 } 9815 CurMBB = Fallthrough; 9816 } 9817 } 9818 9819 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 9820 CaseClusterIt First, 9821 CaseClusterIt Last) { 9822 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 9823 if (X.Prob != CC.Prob) 9824 return X.Prob > CC.Prob; 9825 9826 // Ties are broken by comparing the case value. 9827 return X.Low->getValue().slt(CC.Low->getValue()); 9828 }); 9829 } 9830 9831 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 9832 const SwitchWorkListItem &W, 9833 Value *Cond, 9834 MachineBasicBlock *SwitchMBB) { 9835 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 9836 "Clusters not sorted?"); 9837 9838 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 9839 9840 // Balance the tree based on branch probabilities to create a near-optimal (in 9841 // terms of search time given key frequency) binary search tree. See e.g. Kurt 9842 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 9843 CaseClusterIt LastLeft = W.FirstCluster; 9844 CaseClusterIt FirstRight = W.LastCluster; 9845 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 9846 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 9847 9848 // Move LastLeft and FirstRight towards each other from opposite directions to 9849 // find a partitioning of the clusters which balances the probability on both 9850 // sides. If LeftProb and RightProb are equal, alternate which side is 9851 // taken to ensure 0-probability nodes are distributed evenly. 9852 unsigned I = 0; 9853 while (LastLeft + 1 < FirstRight) { 9854 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 9855 LeftProb += (++LastLeft)->Prob; 9856 else 9857 RightProb += (--FirstRight)->Prob; 9858 I++; 9859 } 9860 9861 while (true) { 9862 // Our binary search tree differs from a typical BST in that ours can have up 9863 // to three values in each leaf. The pivot selection above doesn't take that 9864 // into account, which means the tree might require more nodes and be less 9865 // efficient. We compensate for this here. 9866 9867 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 9868 unsigned NumRight = W.LastCluster - FirstRight + 1; 9869 9870 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 9871 // If one side has less than 3 clusters, and the other has more than 3, 9872 // consider taking a cluster from the other side. 9873 9874 if (NumLeft < NumRight) { 9875 // Consider moving the first cluster on the right to the left side. 9876 CaseCluster &CC = *FirstRight; 9877 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 9878 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 9879 if (LeftSideRank <= RightSideRank) { 9880 // Moving the cluster to the left does not demote it. 9881 ++LastLeft; 9882 ++FirstRight; 9883 continue; 9884 } 9885 } else { 9886 assert(NumRight < NumLeft); 9887 // Consider moving the last element on the left to the right side. 9888 CaseCluster &CC = *LastLeft; 9889 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 9890 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 9891 if (RightSideRank <= LeftSideRank) { 9892 // Moving the cluster to the right does not demot it. 9893 --LastLeft; 9894 --FirstRight; 9895 continue; 9896 } 9897 } 9898 } 9899 break; 9900 } 9901 9902 assert(LastLeft + 1 == FirstRight); 9903 assert(LastLeft >= W.FirstCluster); 9904 assert(FirstRight <= W.LastCluster); 9905 9906 // Use the first element on the right as pivot since we will make less-than 9907 // comparisons against it. 9908 CaseClusterIt PivotCluster = FirstRight; 9909 assert(PivotCluster > W.FirstCluster); 9910 assert(PivotCluster <= W.LastCluster); 9911 9912 CaseClusterIt FirstLeft = W.FirstCluster; 9913 CaseClusterIt LastRight = W.LastCluster; 9914 9915 const ConstantInt *Pivot = PivotCluster->Low; 9916 9917 // New blocks will be inserted immediately after the current one. 9918 MachineFunction::iterator BBI(W.MBB); 9919 ++BBI; 9920 9921 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 9922 // we can branch to its destination directly if it's squeezed exactly in 9923 // between the known lower bound and Pivot - 1. 9924 MachineBasicBlock *LeftMBB; 9925 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 9926 FirstLeft->Low == W.GE && 9927 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 9928 LeftMBB = FirstLeft->MBB; 9929 } else { 9930 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 9931 FuncInfo.MF->insert(BBI, LeftMBB); 9932 WorkList.push_back( 9933 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 9934 // Put Cond in a virtual register to make it available from the new blocks. 9935 ExportFromCurrentBlock(Cond); 9936 } 9937 9938 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 9939 // single cluster, RHS.Low == Pivot, and we can branch to its destination 9940 // directly if RHS.High equals the current upper bound. 9941 MachineBasicBlock *RightMBB; 9942 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 9943 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 9944 RightMBB = FirstRight->MBB; 9945 } else { 9946 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 9947 FuncInfo.MF->insert(BBI, RightMBB); 9948 WorkList.push_back( 9949 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 9950 // Put Cond in a virtual register to make it available from the new blocks. 9951 ExportFromCurrentBlock(Cond); 9952 } 9953 9954 // Create the CaseBlock record that will be used to lower the branch. 9955 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 9956 getCurSDLoc(), LeftProb, RightProb); 9957 9958 if (W.MBB == SwitchMBB) 9959 visitSwitchCase(CB, SwitchMBB); 9960 else 9961 SwitchCases.push_back(CB); 9962 } 9963 9964 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 9965 // from the swith statement. 9966 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 9967 BranchProbability PeeledCaseProb) { 9968 if (PeeledCaseProb == BranchProbability::getOne()) 9969 return BranchProbability::getZero(); 9970 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 9971 9972 uint32_t Numerator = CaseProb.getNumerator(); 9973 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 9974 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 9975 } 9976 9977 // Try to peel the top probability case if it exceeds the threshold. 9978 // Return current MachineBasicBlock for the switch statement if the peeling 9979 // does not occur. 9980 // If the peeling is performed, return the newly created MachineBasicBlock 9981 // for the peeled switch statement. Also update Clusters to remove the peeled 9982 // case. PeeledCaseProb is the BranchProbability for the peeled case. 9983 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 9984 const SwitchInst &SI, CaseClusterVector &Clusters, 9985 BranchProbability &PeeledCaseProb) { 9986 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 9987 // Don't perform if there is only one cluster or optimizing for size. 9988 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 9989 TM.getOptLevel() == CodeGenOpt::None || 9990 SwitchMBB->getParent()->getFunction().optForMinSize()) 9991 return SwitchMBB; 9992 9993 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 9994 unsigned PeeledCaseIndex = 0; 9995 bool SwitchPeeled = false; 9996 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 9997 CaseCluster &CC = Clusters[Index]; 9998 if (CC.Prob < TopCaseProb) 9999 continue; 10000 TopCaseProb = CC.Prob; 10001 PeeledCaseIndex = Index; 10002 SwitchPeeled = true; 10003 } 10004 if (!SwitchPeeled) 10005 return SwitchMBB; 10006 10007 DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " << TopCaseProb 10008 << "\n"); 10009 10010 // Record the MBB for the peeled switch statement. 10011 MachineFunction::iterator BBI(SwitchMBB); 10012 ++BBI; 10013 MachineBasicBlock *PeeledSwitchMBB = 10014 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10015 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10016 10017 ExportFromCurrentBlock(SI.getCondition()); 10018 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10019 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10020 nullptr, nullptr, TopCaseProb.getCompl()}; 10021 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10022 10023 Clusters.erase(PeeledCaseIt); 10024 for (CaseCluster &CC : Clusters) { 10025 DEBUG(dbgs() << "Scale the probablity for one cluster, before scaling: " 10026 << CC.Prob << "\n"); 10027 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10028 DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10029 } 10030 PeeledCaseProb = TopCaseProb; 10031 return PeeledSwitchMBB; 10032 } 10033 10034 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10035 // Extract cases from the switch. 10036 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10037 CaseClusterVector Clusters; 10038 Clusters.reserve(SI.getNumCases()); 10039 for (auto I : SI.cases()) { 10040 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10041 const ConstantInt *CaseVal = I.getCaseValue(); 10042 BranchProbability Prob = 10043 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10044 : BranchProbability(1, SI.getNumCases() + 1); 10045 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10046 } 10047 10048 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10049 10050 // Cluster adjacent cases with the same destination. We do this at all 10051 // optimization levels because it's cheap to do and will make codegen faster 10052 // if there are many clusters. 10053 sortAndRangeify(Clusters); 10054 10055 if (TM.getOptLevel() != CodeGenOpt::None) { 10056 // Replace an unreachable default with the most popular destination. 10057 // FIXME: Exploit unreachable default more aggressively. 10058 bool UnreachableDefault = 10059 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10060 if (UnreachableDefault && !Clusters.empty()) { 10061 DenseMap<const BasicBlock *, unsigned> Popularity; 10062 unsigned MaxPop = 0; 10063 const BasicBlock *MaxBB = nullptr; 10064 for (auto I : SI.cases()) { 10065 const BasicBlock *BB = I.getCaseSuccessor(); 10066 if (++Popularity[BB] > MaxPop) { 10067 MaxPop = Popularity[BB]; 10068 MaxBB = BB; 10069 } 10070 } 10071 // Set new default. 10072 assert(MaxPop > 0 && MaxBB); 10073 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10074 10075 // Remove cases that were pointing to the destination that is now the 10076 // default. 10077 CaseClusterVector New; 10078 New.reserve(Clusters.size()); 10079 for (CaseCluster &CC : Clusters) { 10080 if (CC.MBB != DefaultMBB) 10081 New.push_back(CC); 10082 } 10083 Clusters = std::move(New); 10084 } 10085 } 10086 10087 // The branch probablity of the peeled case. 10088 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10089 MachineBasicBlock *PeeledSwitchMBB = 10090 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10091 10092 // If there is only the default destination, jump there directly. 10093 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10094 if (Clusters.empty()) { 10095 assert(PeeledSwitchMBB == SwitchMBB); 10096 SwitchMBB->addSuccessor(DefaultMBB); 10097 if (DefaultMBB != NextBlock(SwitchMBB)) { 10098 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10099 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10100 } 10101 return; 10102 } 10103 10104 findJumpTables(Clusters, &SI, DefaultMBB); 10105 findBitTestClusters(Clusters, &SI); 10106 10107 DEBUG({ 10108 dbgs() << "Case clusters: "; 10109 for (const CaseCluster &C : Clusters) { 10110 if (C.Kind == CC_JumpTable) dbgs() << "JT:"; 10111 if (C.Kind == CC_BitTests) dbgs() << "BT:"; 10112 10113 C.Low->getValue().print(dbgs(), true); 10114 if (C.Low != C.High) { 10115 dbgs() << '-'; 10116 C.High->getValue().print(dbgs(), true); 10117 } 10118 dbgs() << ' '; 10119 } 10120 dbgs() << '\n'; 10121 }); 10122 10123 assert(!Clusters.empty()); 10124 SwitchWorkList WorkList; 10125 CaseClusterIt First = Clusters.begin(); 10126 CaseClusterIt Last = Clusters.end() - 1; 10127 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10128 // Scale the branchprobability for DefaultMBB if the peel occurs and 10129 // DefaultMBB is not replaced. 10130 if (PeeledCaseProb != BranchProbability::getZero() && 10131 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10132 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10133 WorkList.push_back( 10134 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10135 10136 while (!WorkList.empty()) { 10137 SwitchWorkListItem W = WorkList.back(); 10138 WorkList.pop_back(); 10139 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10140 10141 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10142 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10143 // For optimized builds, lower large range as a balanced binary tree. 10144 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10145 continue; 10146 } 10147 10148 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10149 } 10150 } 10151