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