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/PatternMatch.h" 92 #include "llvm/IR/Statepoint.h" 93 #include "llvm/IR/Type.h" 94 #include "llvm/IR/User.h" 95 #include "llvm/IR/Value.h" 96 #include "llvm/MC/MCContext.h" 97 #include "llvm/MC/MCSymbol.h" 98 #include "llvm/Support/AtomicOrdering.h" 99 #include "llvm/Support/BranchProbability.h" 100 #include "llvm/Support/Casting.h" 101 #include "llvm/Support/CodeGen.h" 102 #include "llvm/Support/CommandLine.h" 103 #include "llvm/Support/Compiler.h" 104 #include "llvm/Support/Debug.h" 105 #include "llvm/Support/ErrorHandling.h" 106 #include "llvm/Support/MachineValueType.h" 107 #include "llvm/Support/MathExtras.h" 108 #include "llvm/Support/raw_ostream.h" 109 #include "llvm/Target/TargetIntrinsicInfo.h" 110 #include "llvm/Target/TargetMachine.h" 111 #include "llvm/Target/TargetOptions.h" 112 #include <algorithm> 113 #include <cassert> 114 #include <cstddef> 115 #include <cstdint> 116 #include <cstring> 117 #include <iterator> 118 #include <limits> 119 #include <numeric> 120 #include <tuple> 121 #include <utility> 122 #include <vector> 123 124 using namespace llvm; 125 using namespace PatternMatch; 126 127 #define DEBUG_TYPE "isel" 128 129 /// LimitFloatPrecision - Generate low-precision inline sequences for 130 /// some float libcalls (6, 8 or 12 bits). 131 static unsigned LimitFloatPrecision; 132 133 static cl::opt<unsigned, true> 134 LimitFPPrecision("limit-float-precision", 135 cl::desc("Generate low-precision inline sequences " 136 "for some float libcalls"), 137 cl::location(LimitFloatPrecision), cl::Hidden, 138 cl::init(0)); 139 140 static cl::opt<unsigned> SwitchPeelThreshold( 141 "switch-peel-threshold", cl::Hidden, cl::init(66), 142 cl::desc("Set the case probability threshold for peeling the case from a " 143 "switch statement. A value greater than 100 will void this " 144 "optimization")); 145 146 // Limit the width of DAG chains. This is important in general to prevent 147 // DAG-based analysis from blowing up. For example, alias analysis and 148 // load clustering may not complete in reasonable time. It is difficult to 149 // recognize and avoid this situation within each individual analysis, and 150 // future analyses are likely to have the same behavior. Limiting DAG width is 151 // the safe approach and will be especially important with global DAGs. 152 // 153 // MaxParallelChains default is arbitrarily high to avoid affecting 154 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 155 // sequence over this should have been converted to llvm.memcpy by the 156 // frontend. It is easy to induce this behavior with .ll code such as: 157 // %buffer = alloca [4096 x i8] 158 // %data = load [4096 x i8]* %argPtr 159 // store [4096 x i8] %data, [4096 x i8]* %buffer 160 static const unsigned MaxParallelChains = 64; 161 162 // Return the calling convention if the Value passed requires ABI mangling as it 163 // is a parameter to a function or a return value from a function which is not 164 // an intrinsic. 165 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 166 if (auto *R = dyn_cast<ReturnInst>(V)) 167 return R->getParent()->getParent()->getCallingConv(); 168 169 if (auto *CI = dyn_cast<CallInst>(V)) { 170 const bool IsInlineAsm = CI->isInlineAsm(); 171 const bool IsIndirectFunctionCall = 172 !IsInlineAsm && !CI->getCalledFunction(); 173 174 // It is possible that the call instruction is an inline asm statement or an 175 // indirect function call in which case the return value of 176 // getCalledFunction() would be nullptr. 177 const bool IsInstrinsicCall = 178 !IsInlineAsm && !IsIndirectFunctionCall && 179 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 180 181 if (!IsInlineAsm && !IsInstrinsicCall) 182 return CI->getCallingConv(); 183 } 184 185 return None; 186 } 187 188 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 189 const SDValue *Parts, unsigned NumParts, 190 MVT PartVT, EVT ValueVT, const Value *V, 191 Optional<CallingConv::ID> CC); 192 193 /// getCopyFromParts - Create a value that contains the specified legal parts 194 /// combined into the value they represent. If the parts combine to a type 195 /// larger than ValueVT then AssertOp can be used to specify whether the extra 196 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 197 /// (ISD::AssertSext). 198 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 199 const SDValue *Parts, unsigned NumParts, 200 MVT PartVT, EVT ValueVT, const Value *V, 201 Optional<CallingConv::ID> CC = None, 202 Optional<ISD::NodeType> AssertOp = None) { 203 if (ValueVT.isVector()) 204 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 205 CC); 206 207 assert(NumParts > 0 && "No parts to assemble!"); 208 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 209 SDValue Val = Parts[0]; 210 211 if (NumParts > 1) { 212 // Assemble the value from multiple parts. 213 if (ValueVT.isInteger()) { 214 unsigned PartBits = PartVT.getSizeInBits(); 215 unsigned ValueBits = ValueVT.getSizeInBits(); 216 217 // Assemble the power of 2 part. 218 unsigned RoundParts = NumParts & (NumParts - 1) ? 219 1 << Log2_32(NumParts) : NumParts; 220 unsigned RoundBits = PartBits * RoundParts; 221 EVT RoundVT = RoundBits == ValueBits ? 222 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 223 SDValue Lo, Hi; 224 225 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 226 227 if (RoundParts > 2) { 228 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 229 PartVT, HalfVT, V); 230 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 231 RoundParts / 2, PartVT, HalfVT, V); 232 } else { 233 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 234 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 235 } 236 237 if (DAG.getDataLayout().isBigEndian()) 238 std::swap(Lo, Hi); 239 240 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 241 242 if (RoundParts < NumParts) { 243 // Assemble the trailing non-power-of-2 part. 244 unsigned OddParts = NumParts - RoundParts; 245 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 246 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 247 OddVT, V, CC); 248 249 // Combine the round and odd parts. 250 Lo = Val; 251 if (DAG.getDataLayout().isBigEndian()) 252 std::swap(Lo, Hi); 253 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 254 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 255 Hi = 256 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 257 DAG.getConstant(Lo.getValueSizeInBits(), DL, 258 TLI.getPointerTy(DAG.getDataLayout()))); 259 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 260 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 261 } 262 } else if (PartVT.isFloatingPoint()) { 263 // FP split into multiple FP parts (for ppcf128) 264 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 265 "Unexpected split"); 266 SDValue Lo, Hi; 267 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 268 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 269 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 270 std::swap(Lo, Hi); 271 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 272 } else { 273 // FP split into integer parts (soft fp) 274 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 275 !PartVT.isVector() && "Unexpected split"); 276 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 277 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 278 } 279 } 280 281 // There is now one part, held in Val. Correct it to match ValueVT. 282 // PartEVT is the type of the register class that holds the value. 283 // ValueVT is the type of the inline asm operation. 284 EVT PartEVT = Val.getValueType(); 285 286 if (PartEVT == ValueVT) 287 return Val; 288 289 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 290 ValueVT.bitsLT(PartEVT)) { 291 // For an FP value in an integer part, we need to truncate to the right 292 // width first. 293 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 294 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 295 } 296 297 // Handle types that have the same size. 298 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 299 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 300 301 // Handle types with different sizes. 302 if (PartEVT.isInteger() && ValueVT.isInteger()) { 303 if (ValueVT.bitsLT(PartEVT)) { 304 // For a truncate, see if we have any information to 305 // indicate whether the truncated bits will always be 306 // zero or sign-extension. 307 if (AssertOp.hasValue()) 308 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 309 DAG.getValueType(ValueVT)); 310 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 311 } 312 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 313 } 314 315 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 316 // FP_ROUND's are always exact here. 317 if (ValueVT.bitsLT(Val.getValueType())) 318 return DAG.getNode( 319 ISD::FP_ROUND, DL, ValueVT, Val, 320 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 321 322 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 323 } 324 325 llvm_unreachable("Unknown mismatch!"); 326 } 327 328 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 329 const Twine &ErrMsg) { 330 const Instruction *I = dyn_cast_or_null<Instruction>(V); 331 if (!V) 332 return Ctx.emitError(ErrMsg); 333 334 const char *AsmError = ", possible invalid constraint for vector type"; 335 if (const CallInst *CI = dyn_cast<CallInst>(I)) 336 if (isa<InlineAsm>(CI->getCalledValue())) 337 return Ctx.emitError(I, ErrMsg + AsmError); 338 339 return Ctx.emitError(I, ErrMsg); 340 } 341 342 /// getCopyFromPartsVector - Create a value that contains the specified legal 343 /// parts combined into the value they represent. If the parts combine to a 344 /// type larger than ValueVT then AssertOp can be used to specify whether the 345 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 346 /// ValueVT (ISD::AssertSext). 347 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 348 const SDValue *Parts, unsigned NumParts, 349 MVT PartVT, EVT ValueVT, const Value *V, 350 Optional<CallingConv::ID> CallConv) { 351 assert(ValueVT.isVector() && "Not a vector value"); 352 assert(NumParts > 0 && "No parts to assemble!"); 353 const bool IsABIRegCopy = CallConv.hasValue(); 354 355 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 356 SDValue Val = Parts[0]; 357 358 // Handle a multi-element vector. 359 if (NumParts > 1) { 360 EVT IntermediateVT; 361 MVT RegisterVT; 362 unsigned NumIntermediates; 363 unsigned NumRegs; 364 365 if (IsABIRegCopy) { 366 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 367 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 368 NumIntermediates, RegisterVT); 369 } else { 370 NumRegs = 371 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 372 NumIntermediates, RegisterVT); 373 } 374 375 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 376 NumParts = NumRegs; // Silence a compiler warning. 377 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 378 assert(RegisterVT.getSizeInBits() == 379 Parts[0].getSimpleValueType().getSizeInBits() && 380 "Part type sizes don't match!"); 381 382 // Assemble the parts into intermediate operands. 383 SmallVector<SDValue, 8> Ops(NumIntermediates); 384 if (NumIntermediates == NumParts) { 385 // If the register was not expanded, truncate or copy the value, 386 // as appropriate. 387 for (unsigned i = 0; i != NumParts; ++i) 388 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 389 PartVT, IntermediateVT, V); 390 } else if (NumParts > 0) { 391 // If the intermediate type was expanded, build the intermediate 392 // operands from the parts. 393 assert(NumParts % NumIntermediates == 0 && 394 "Must expand into a divisible number of parts!"); 395 unsigned Factor = NumParts / NumIntermediates; 396 for (unsigned i = 0; i != NumIntermediates; ++i) 397 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 398 PartVT, IntermediateVT, V); 399 } 400 401 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 402 // intermediate operands. 403 EVT BuiltVectorTy = 404 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 405 (IntermediateVT.isVector() 406 ? IntermediateVT.getVectorNumElements() * NumParts 407 : NumIntermediates)); 408 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 409 : ISD::BUILD_VECTOR, 410 DL, BuiltVectorTy, Ops); 411 } 412 413 // There is now one part, held in Val. Correct it to match ValueVT. 414 EVT PartEVT = Val.getValueType(); 415 416 if (PartEVT == ValueVT) 417 return Val; 418 419 if (PartEVT.isVector()) { 420 // If the element type of the source/dest vectors are the same, but the 421 // parts vector has more elements than the value vector, then we have a 422 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 423 // elements we want. 424 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 425 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 426 "Cannot narrow, it would be a lossy transformation"); 427 return DAG.getNode( 428 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 429 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 430 } 431 432 // Vector/Vector bitcast. 433 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 434 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 435 436 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 437 "Cannot handle this kind of promotion"); 438 // Promoted vector extract 439 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 440 441 } 442 443 // Trivial bitcast if the types are the same size and the destination 444 // vector type is legal. 445 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 446 TLI.isTypeLegal(ValueVT)) 447 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 448 449 if (ValueVT.getVectorNumElements() != 1) { 450 // Certain ABIs require that vectors are passed as integers. For vectors 451 // are the same size, this is an obvious bitcast. 452 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 453 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 454 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 455 // Bitcast Val back the original type and extract the corresponding 456 // vector we want. 457 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 458 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 459 ValueVT.getVectorElementType(), Elts); 460 Val = DAG.getBitcast(WiderVecType, Val); 461 return DAG.getNode( 462 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 463 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 464 } 465 466 diagnosePossiblyInvalidConstraint( 467 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 468 return DAG.getUNDEF(ValueVT); 469 } 470 471 // Handle cases such as i8 -> <1 x i1> 472 EVT ValueSVT = ValueVT.getVectorElementType(); 473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 474 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 475 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 476 477 return DAG.getBuildVector(ValueVT, DL, Val); 478 } 479 480 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 481 SDValue Val, SDValue *Parts, unsigned NumParts, 482 MVT PartVT, const Value *V, 483 Optional<CallingConv::ID> CallConv); 484 485 /// getCopyToParts - Create a series of nodes that contain the specified value 486 /// split into legal parts. If the parts contain more bits than Val, then, for 487 /// integers, ExtendKind can be used to specify how to generate the extra bits. 488 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 489 SDValue *Parts, unsigned NumParts, MVT PartVT, 490 const Value *V, 491 Optional<CallingConv::ID> CallConv = None, 492 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 493 EVT ValueVT = Val.getValueType(); 494 495 // Handle the vector case separately. 496 if (ValueVT.isVector()) 497 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 498 CallConv); 499 500 unsigned PartBits = PartVT.getSizeInBits(); 501 unsigned OrigNumParts = NumParts; 502 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 503 "Copying to an illegal type!"); 504 505 if (NumParts == 0) 506 return; 507 508 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 509 EVT PartEVT = PartVT; 510 if (PartEVT == ValueVT) { 511 assert(NumParts == 1 && "No-op copy with multiple parts!"); 512 Parts[0] = Val; 513 return; 514 } 515 516 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 517 // If the parts cover more bits than the value has, promote the value. 518 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 519 assert(NumParts == 1 && "Do not know what to promote to!"); 520 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 521 } else { 522 if (ValueVT.isFloatingPoint()) { 523 // FP values need to be bitcast, then extended if they are being put 524 // into a larger container. 525 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 526 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 527 } 528 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 529 ValueVT.isInteger() && 530 "Unknown mismatch!"); 531 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 532 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 533 if (PartVT == MVT::x86mmx) 534 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 535 } 536 } else if (PartBits == ValueVT.getSizeInBits()) { 537 // Different types of the same size. 538 assert(NumParts == 1 && PartEVT != ValueVT); 539 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 540 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 541 // If the parts cover less bits than value has, truncate the value. 542 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 543 ValueVT.isInteger() && 544 "Unknown mismatch!"); 545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 546 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 547 if (PartVT == MVT::x86mmx) 548 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 549 } 550 551 // The value may have changed - recompute ValueVT. 552 ValueVT = Val.getValueType(); 553 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 554 "Failed to tile the value with PartVT!"); 555 556 if (NumParts == 1) { 557 if (PartEVT != ValueVT) { 558 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 559 "scalar-to-vector conversion failed"); 560 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 561 } 562 563 Parts[0] = Val; 564 return; 565 } 566 567 // Expand the value into multiple parts. 568 if (NumParts & (NumParts - 1)) { 569 // The number of parts is not a power of 2. Split off and copy the tail. 570 assert(PartVT.isInteger() && ValueVT.isInteger() && 571 "Do not know what to expand to!"); 572 unsigned RoundParts = 1 << Log2_32(NumParts); 573 unsigned RoundBits = RoundParts * PartBits; 574 unsigned OddParts = NumParts - RoundParts; 575 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 576 DAG.getIntPtrConstant(RoundBits, DL)); 577 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 578 CallConv); 579 580 if (DAG.getDataLayout().isBigEndian()) 581 // The odd parts were reversed by getCopyToParts - unreverse them. 582 std::reverse(Parts + RoundParts, Parts + NumParts); 583 584 NumParts = RoundParts; 585 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 587 } 588 589 // The number of parts is a power of 2. Repeatedly bisect the value using 590 // EXTRACT_ELEMENT. 591 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 592 EVT::getIntegerVT(*DAG.getContext(), 593 ValueVT.getSizeInBits()), 594 Val); 595 596 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 597 for (unsigned i = 0; i < NumParts; i += StepSize) { 598 unsigned ThisBits = StepSize * PartBits / 2; 599 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 600 SDValue &Part0 = Parts[i]; 601 SDValue &Part1 = Parts[i+StepSize/2]; 602 603 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 605 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 606 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 607 608 if (ThisBits == PartBits && ThisVT != PartVT) { 609 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 610 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 611 } 612 } 613 } 614 615 if (DAG.getDataLayout().isBigEndian()) 616 std::reverse(Parts, Parts + OrigNumParts); 617 } 618 619 static SDValue widenVectorToPartType(SelectionDAG &DAG, 620 SDValue Val, const SDLoc &DL, EVT PartVT) { 621 if (!PartVT.isVector()) 622 return SDValue(); 623 624 EVT ValueVT = Val.getValueType(); 625 unsigned PartNumElts = PartVT.getVectorNumElements(); 626 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 627 if (PartNumElts > ValueNumElts && 628 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 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 DAG.ExtractVectorElements(Val, Ops); 634 SDValue EltUndef = DAG.getUNDEF(ElementVT); 635 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 636 Ops.push_back(EltUndef); 637 638 // FIXME: Use CONCAT for 2x -> 4x. 639 return DAG.getBuildVector(PartVT, DL, Ops); 640 } 641 642 return SDValue(); 643 } 644 645 /// getCopyToPartsVector - Create a series of nodes that contain the specified 646 /// value split into legal parts. 647 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 648 SDValue Val, SDValue *Parts, unsigned NumParts, 649 MVT PartVT, const Value *V, 650 Optional<CallingConv::ID> CallConv) { 651 EVT ValueVT = Val.getValueType(); 652 assert(ValueVT.isVector() && "Not a vector"); 653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 654 const bool IsABIRegCopy = CallConv.hasValue(); 655 656 if (NumParts == 1) { 657 EVT PartEVT = PartVT; 658 if (PartEVT == ValueVT) { 659 // Nothing to do. 660 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 661 // Bitconvert vector->vector case. 662 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 663 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 664 Val = Widened; 665 } else if (PartVT.isVector() && 666 PartEVT.getVectorElementType().bitsGE( 667 ValueVT.getVectorElementType()) && 668 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 669 670 // Promoted vector extract 671 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 672 } else { 673 if (ValueVT.getVectorNumElements() == 1) { 674 Val = DAG.getNode( 675 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 676 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 677 } else { 678 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 679 "lossy conversion of vector to scalar type"); 680 EVT IntermediateType = 681 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 682 Val = DAG.getBitcast(IntermediateType, Val); 683 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 684 } 685 } 686 687 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 688 Parts[0] = Val; 689 return; 690 } 691 692 // Handle a multi-element vector. 693 EVT IntermediateVT; 694 MVT RegisterVT; 695 unsigned NumIntermediates; 696 unsigned NumRegs; 697 if (IsABIRegCopy) { 698 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 699 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 700 NumIntermediates, RegisterVT); 701 } else { 702 NumRegs = 703 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 704 NumIntermediates, RegisterVT); 705 } 706 707 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 708 NumParts = NumRegs; // Silence a compiler warning. 709 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 710 711 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 712 IntermediateVT.getVectorNumElements() : 1; 713 714 // Convert the vector to the appropiate type if necessary. 715 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 716 717 EVT BuiltVectorTy = EVT::getVectorVT( 718 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 719 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 720 if (ValueVT != BuiltVectorTy) { 721 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 722 Val = Widened; 723 724 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 725 } 726 727 // Split the vector into intermediate operands. 728 SmallVector<SDValue, 8> Ops(NumIntermediates); 729 for (unsigned i = 0; i != NumIntermediates; ++i) { 730 if (IntermediateVT.isVector()) { 731 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 732 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 733 } else { 734 Ops[i] = DAG.getNode( 735 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 736 DAG.getConstant(i, DL, IdxVT)); 737 } 738 } 739 740 // Split the intermediate operands into legal parts. 741 if (NumParts == NumIntermediates) { 742 // If the register was not expanded, promote or copy the value, 743 // as appropriate. 744 for (unsigned i = 0; i != NumParts; ++i) 745 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 746 } else if (NumParts > 0) { 747 // If the intermediate type was expanded, split each the value into 748 // legal parts. 749 assert(NumIntermediates != 0 && "division by zero"); 750 assert(NumParts % NumIntermediates == 0 && 751 "Must expand into a divisible number of parts!"); 752 unsigned Factor = NumParts / NumIntermediates; 753 for (unsigned i = 0; i != NumIntermediates; ++i) 754 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 755 CallConv); 756 } 757 } 758 759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 760 EVT valuevt, Optional<CallingConv::ID> CC) 761 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 762 RegCount(1, regs.size()), CallConv(CC) {} 763 764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 765 const DataLayout &DL, unsigned Reg, Type *Ty, 766 Optional<CallingConv::ID> CC) { 767 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 768 769 CallConv = CC; 770 771 for (EVT ValueVT : ValueVTs) { 772 unsigned NumRegs = 773 isABIMangled() 774 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 775 : TLI.getNumRegisters(Context, ValueVT); 776 MVT RegisterVT = 777 isABIMangled() 778 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 779 : TLI.getRegisterType(Context, ValueVT); 780 for (unsigned i = 0; i != NumRegs; ++i) 781 Regs.push_back(Reg + i); 782 RegVTs.push_back(RegisterVT); 783 RegCount.push_back(NumRegs); 784 Reg += NumRegs; 785 } 786 } 787 788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 789 FunctionLoweringInfo &FuncInfo, 790 const SDLoc &dl, SDValue &Chain, 791 SDValue *Flag, const Value *V) const { 792 // A Value with type {} or [0 x %t] needs no registers. 793 if (ValueVTs.empty()) 794 return SDValue(); 795 796 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 797 798 // Assemble the legal parts into the final values. 799 SmallVector<SDValue, 4> Values(ValueVTs.size()); 800 SmallVector<SDValue, 8> Parts; 801 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 802 // Copy the legal parts from the registers. 803 EVT ValueVT = ValueVTs[Value]; 804 unsigned NumRegs = RegCount[Value]; 805 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 806 *DAG.getContext(), 807 CallConv.getValue(), RegVTs[Value]) 808 : RegVTs[Value]; 809 810 Parts.resize(NumRegs); 811 for (unsigned i = 0; i != NumRegs; ++i) { 812 SDValue P; 813 if (!Flag) { 814 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 815 } else { 816 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 817 *Flag = P.getValue(2); 818 } 819 820 Chain = P.getValue(1); 821 Parts[i] = P; 822 823 // If the source register was virtual and if we know something about it, 824 // add an assert node. 825 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 826 !RegisterVT.isInteger()) 827 continue; 828 829 const FunctionLoweringInfo::LiveOutInfo *LOI = 830 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 831 if (!LOI) 832 continue; 833 834 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 835 unsigned NumSignBits = LOI->NumSignBits; 836 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 837 838 if (NumZeroBits == RegSize) { 839 // The current value is a zero. 840 // Explicitly express that as it would be easier for 841 // optimizations to kick in. 842 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 843 continue; 844 } 845 846 // FIXME: We capture more information than the dag can represent. For 847 // now, just use the tightest assertzext/assertsext possible. 848 bool isSExt; 849 EVT FromVT(MVT::Other); 850 if (NumZeroBits) { 851 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 852 isSExt = false; 853 } else if (NumSignBits > 1) { 854 FromVT = 855 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 856 isSExt = true; 857 } else { 858 continue; 859 } 860 // Add an assertion node. 861 assert(FromVT != MVT::Other); 862 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 863 RegisterVT, P, DAG.getValueType(FromVT)); 864 } 865 866 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 867 RegisterVT, ValueVT, V, CallConv); 868 Part += NumRegs; 869 Parts.clear(); 870 } 871 872 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 873 } 874 875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 876 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 877 const Value *V, 878 ISD::NodeType PreferredExtendType) const { 879 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 880 ISD::NodeType ExtendKind = PreferredExtendType; 881 882 // Get the list of the values's legal parts. 883 unsigned NumRegs = Regs.size(); 884 SmallVector<SDValue, 8> Parts(NumRegs); 885 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 886 unsigned NumParts = RegCount[Value]; 887 888 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 889 *DAG.getContext(), 890 CallConv.getValue(), RegVTs[Value]) 891 : RegVTs[Value]; 892 893 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 894 ExtendKind = ISD::ZERO_EXTEND; 895 896 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 897 NumParts, RegisterVT, V, CallConv, ExtendKind); 898 Part += NumParts; 899 } 900 901 // Copy the parts into the registers. 902 SmallVector<SDValue, 8> Chains(NumRegs); 903 for (unsigned i = 0; i != NumRegs; ++i) { 904 SDValue Part; 905 if (!Flag) { 906 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 907 } else { 908 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 909 *Flag = Part.getValue(1); 910 } 911 912 Chains[i] = Part.getValue(0); 913 } 914 915 if (NumRegs == 1 || Flag) 916 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 917 // flagged to it. That is the CopyToReg nodes and the user are considered 918 // a single scheduling unit. If we create a TokenFactor and return it as 919 // chain, then the TokenFactor is both a predecessor (operand) of the 920 // user as well as a successor (the TF operands are flagged to the user). 921 // c1, f1 = CopyToReg 922 // c2, f2 = CopyToReg 923 // c3 = TokenFactor c1, c2 924 // ... 925 // = op c3, ..., f2 926 Chain = Chains[NumRegs-1]; 927 else 928 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 929 } 930 931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 932 unsigned MatchingIdx, const SDLoc &dl, 933 SelectionDAG &DAG, 934 std::vector<SDValue> &Ops) const { 935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 936 937 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 938 if (HasMatching) 939 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 940 else if (!Regs.empty() && 941 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 942 // Put the register class of the virtual registers in the flag word. That 943 // way, later passes can recompute register class constraints for inline 944 // assembly as well as normal instructions. 945 // Don't do this for tied operands that can use the regclass information 946 // from the def. 947 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 948 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 949 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 950 } 951 952 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 953 Ops.push_back(Res); 954 955 if (Code == InlineAsm::Kind_Clobber) { 956 // Clobbers should always have a 1:1 mapping with registers, and may 957 // reference registers that have illegal (e.g. vector) types. Hence, we 958 // shouldn't try to apply any sort of splitting logic to them. 959 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 960 "No 1:1 mapping from clobbers to regs?"); 961 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 962 (void)SP; 963 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 964 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 965 assert( 966 (Regs[I] != SP || 967 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 968 "If we clobbered the stack pointer, MFI should know about it."); 969 } 970 return; 971 } 972 973 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 974 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 975 MVT RegisterVT = RegVTs[Value]; 976 for (unsigned i = 0; i != NumRegs; ++i) { 977 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 978 unsigned TheReg = Regs[Reg++]; 979 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 980 } 981 } 982 } 983 984 SmallVector<std::pair<unsigned, unsigned>, 4> 985 RegsForValue::getRegsAndSizes() const { 986 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 987 unsigned I = 0; 988 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 989 unsigned RegCount = std::get<0>(CountAndVT); 990 MVT RegisterVT = std::get<1>(CountAndVT); 991 unsigned RegisterSize = RegisterVT.getSizeInBits(); 992 for (unsigned E = I + RegCount; I != E; ++I) 993 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 994 } 995 return OutVec; 996 } 997 998 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 999 const TargetLibraryInfo *li) { 1000 AA = aa; 1001 GFI = gfi; 1002 LibInfo = li; 1003 DL = &DAG.getDataLayout(); 1004 Context = DAG.getContext(); 1005 LPadToCallSiteMap.clear(); 1006 } 1007 1008 void SelectionDAGBuilder::clear() { 1009 NodeMap.clear(); 1010 UnusedArgNodeMap.clear(); 1011 PendingLoads.clear(); 1012 PendingExports.clear(); 1013 CurInst = nullptr; 1014 HasTailCall = false; 1015 SDNodeOrder = LowestSDNodeOrder; 1016 StatepointLowering.clear(); 1017 } 1018 1019 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1020 DanglingDebugInfoMap.clear(); 1021 } 1022 1023 SDValue SelectionDAGBuilder::getRoot() { 1024 if (PendingLoads.empty()) 1025 return DAG.getRoot(); 1026 1027 if (PendingLoads.size() == 1) { 1028 SDValue Root = PendingLoads[0]; 1029 DAG.setRoot(Root); 1030 PendingLoads.clear(); 1031 return Root; 1032 } 1033 1034 // Otherwise, we have to make a token factor node. 1035 // If we have >= 2^16 loads then split across multiple token factors as 1036 // there's a 64k limit on the number of SDNode operands. 1037 SDValue Root; 1038 size_t Limit = (1 << 16) - 1; 1039 while (PendingLoads.size() > Limit) { 1040 unsigned SliceIdx = PendingLoads.size() - Limit; 1041 auto ExtractedTFs = ArrayRef<SDValue>(PendingLoads).slice(SliceIdx, Limit); 1042 SDValue NewTF = 1043 DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, ExtractedTFs); 1044 PendingLoads.erase(PendingLoads.begin() + SliceIdx, PendingLoads.end()); 1045 PendingLoads.emplace_back(NewTF); 1046 } 1047 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, PendingLoads); 1048 PendingLoads.clear(); 1049 DAG.setRoot(Root); 1050 return Root; 1051 } 1052 1053 SDValue SelectionDAGBuilder::getControlRoot() { 1054 SDValue Root = DAG.getRoot(); 1055 1056 if (PendingExports.empty()) 1057 return Root; 1058 1059 // Turn all of the CopyToReg chains into one factored node. 1060 if (Root.getOpcode() != ISD::EntryToken) { 1061 unsigned i = 0, e = PendingExports.size(); 1062 for (; i != e; ++i) { 1063 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1064 if (PendingExports[i].getNode()->getOperand(0) == Root) 1065 break; // Don't add the root if we already indirectly depend on it. 1066 } 1067 1068 if (i == e) 1069 PendingExports.push_back(Root); 1070 } 1071 1072 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1073 PendingExports); 1074 PendingExports.clear(); 1075 DAG.setRoot(Root); 1076 return Root; 1077 } 1078 1079 void SelectionDAGBuilder::visit(const Instruction &I) { 1080 // Set up outgoing PHI node register values before emitting the terminator. 1081 if (I.isTerminator()) { 1082 HandlePHINodesInSuccessorBlocks(I.getParent()); 1083 } 1084 1085 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1086 if (!isa<DbgInfoIntrinsic>(I)) 1087 ++SDNodeOrder; 1088 1089 CurInst = &I; 1090 1091 visit(I.getOpcode(), I); 1092 1093 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1094 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1095 // maps to this instruction. 1096 // TODO: We could handle all flags (nsw, etc) here. 1097 // TODO: If an IR instruction maps to >1 node, only the final node will have 1098 // flags set. 1099 if (SDNode *Node = getNodeForIRValue(&I)) { 1100 SDNodeFlags IncomingFlags; 1101 IncomingFlags.copyFMF(*FPMO); 1102 if (!Node->getFlags().isDefined()) 1103 Node->setFlags(IncomingFlags); 1104 else 1105 Node->intersectFlagsWith(IncomingFlags); 1106 } 1107 } 1108 1109 if (!I.isTerminator() && !HasTailCall && 1110 !isStatepoint(&I)) // statepoints handle their exports internally 1111 CopyToExportRegsIfNeeded(&I); 1112 1113 CurInst = nullptr; 1114 } 1115 1116 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1117 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1118 } 1119 1120 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1121 // Note: this doesn't use InstVisitor, because it has to work with 1122 // ConstantExpr's in addition to instructions. 1123 switch (Opcode) { 1124 default: llvm_unreachable("Unknown instruction type encountered!"); 1125 // Build the switch statement using the Instruction.def file. 1126 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1127 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1128 #include "llvm/IR/Instruction.def" 1129 } 1130 } 1131 1132 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1133 const DIExpression *Expr) { 1134 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1135 const DbgValueInst *DI = DDI.getDI(); 1136 DIVariable *DanglingVariable = DI->getVariable(); 1137 DIExpression *DanglingExpr = DI->getExpression(); 1138 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1139 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1140 return true; 1141 } 1142 return false; 1143 }; 1144 1145 for (auto &DDIMI : DanglingDebugInfoMap) { 1146 DanglingDebugInfoVector &DDIV = DDIMI.second; 1147 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1148 } 1149 } 1150 1151 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1152 // generate the debug data structures now that we've seen its definition. 1153 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1154 SDValue Val) { 1155 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1156 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1157 return; 1158 1159 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1160 for (auto &DDI : DDIV) { 1161 const DbgValueInst *DI = DDI.getDI(); 1162 assert(DI && "Ill-formed DanglingDebugInfo"); 1163 DebugLoc dl = DDI.getdl(); 1164 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1165 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1166 DILocalVariable *Variable = DI->getVariable(); 1167 DIExpression *Expr = DI->getExpression(); 1168 assert(Variable->isValidLocationForIntrinsic(dl) && 1169 "Expected inlined-at fields to agree"); 1170 SDDbgValue *SDV; 1171 if (Val.getNode()) { 1172 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1173 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1174 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1175 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1176 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1177 // inserted after the definition of Val when emitting the instructions 1178 // after ISel. An alternative could be to teach 1179 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1180 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1181 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1182 << ValSDNodeOrder << "\n"); 1183 SDV = getDbgValue(Val, Variable, Expr, dl, 1184 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1185 DAG.AddDbgValue(SDV, Val.getNode(), false); 1186 } else 1187 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1188 << "in EmitFuncArgumentDbgValue\n"); 1189 } else 1190 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1191 } 1192 DDIV.clear(); 1193 } 1194 1195 /// getCopyFromRegs - If there was virtual register allocated for the value V 1196 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1197 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1198 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1199 SDValue Result; 1200 1201 if (It != FuncInfo.ValueMap.end()) { 1202 unsigned InReg = It->second; 1203 1204 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1205 DAG.getDataLayout(), InReg, Ty, 1206 None); // This is not an ABI copy. 1207 SDValue Chain = DAG.getEntryNode(); 1208 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1209 V); 1210 resolveDanglingDebugInfo(V, Result); 1211 } 1212 1213 return Result; 1214 } 1215 1216 /// getValue - Return an SDValue for the given Value. 1217 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1218 // If we already have an SDValue for this value, use it. It's important 1219 // to do this first, so that we don't create a CopyFromReg if we already 1220 // have a regular SDValue. 1221 SDValue &N = NodeMap[V]; 1222 if (N.getNode()) return N; 1223 1224 // If there's a virtual register allocated and initialized for this 1225 // value, use it. 1226 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1227 return copyFromReg; 1228 1229 // Otherwise create a new SDValue and remember it. 1230 SDValue Val = getValueImpl(V); 1231 NodeMap[V] = Val; 1232 resolveDanglingDebugInfo(V, Val); 1233 return Val; 1234 } 1235 1236 // Return true if SDValue exists for the given Value 1237 bool SelectionDAGBuilder::findValue(const Value *V) const { 1238 return (NodeMap.find(V) != NodeMap.end()) || 1239 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1240 } 1241 1242 /// getNonRegisterValue - Return an SDValue for the given Value, but 1243 /// don't look in FuncInfo.ValueMap for a virtual register. 1244 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1245 // If we already have an SDValue for this value, use it. 1246 SDValue &N = NodeMap[V]; 1247 if (N.getNode()) { 1248 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1249 // Remove the debug location from the node as the node is about to be used 1250 // in a location which may differ from the original debug location. This 1251 // is relevant to Constant and ConstantFP nodes because they can appear 1252 // as constant expressions inside PHI nodes. 1253 N->setDebugLoc(DebugLoc()); 1254 } 1255 return N; 1256 } 1257 1258 // Otherwise create a new SDValue and remember it. 1259 SDValue Val = getValueImpl(V); 1260 NodeMap[V] = Val; 1261 resolveDanglingDebugInfo(V, Val); 1262 return Val; 1263 } 1264 1265 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1266 /// Create an SDValue for the given value. 1267 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1268 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1269 1270 if (const Constant *C = dyn_cast<Constant>(V)) { 1271 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1272 1273 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1274 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1275 1276 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1277 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1278 1279 if (isa<ConstantPointerNull>(C)) { 1280 unsigned AS = V->getType()->getPointerAddressSpace(); 1281 return DAG.getConstant(0, getCurSDLoc(), 1282 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1283 } 1284 1285 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1286 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1287 1288 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1289 return DAG.getUNDEF(VT); 1290 1291 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1292 visit(CE->getOpcode(), *CE); 1293 SDValue N1 = NodeMap[V]; 1294 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1295 return N1; 1296 } 1297 1298 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1299 SmallVector<SDValue, 4> Constants; 1300 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1301 OI != OE; ++OI) { 1302 SDNode *Val = getValue(*OI).getNode(); 1303 // If the operand is an empty aggregate, there are no values. 1304 if (!Val) continue; 1305 // Add each leaf value from the operand to the Constants list 1306 // to form a flattened list of all the values. 1307 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1308 Constants.push_back(SDValue(Val, i)); 1309 } 1310 1311 return DAG.getMergeValues(Constants, getCurSDLoc()); 1312 } 1313 1314 if (const ConstantDataSequential *CDS = 1315 dyn_cast<ConstantDataSequential>(C)) { 1316 SmallVector<SDValue, 4> Ops; 1317 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1318 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1319 // Add each leaf value from the operand to the Constants list 1320 // to form a flattened list of all the values. 1321 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1322 Ops.push_back(SDValue(Val, i)); 1323 } 1324 1325 if (isa<ArrayType>(CDS->getType())) 1326 return DAG.getMergeValues(Ops, getCurSDLoc()); 1327 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1328 } 1329 1330 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1331 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1332 "Unknown struct or array constant!"); 1333 1334 SmallVector<EVT, 4> ValueVTs; 1335 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1336 unsigned NumElts = ValueVTs.size(); 1337 if (NumElts == 0) 1338 return SDValue(); // empty struct 1339 SmallVector<SDValue, 4> Constants(NumElts); 1340 for (unsigned i = 0; i != NumElts; ++i) { 1341 EVT EltVT = ValueVTs[i]; 1342 if (isa<UndefValue>(C)) 1343 Constants[i] = DAG.getUNDEF(EltVT); 1344 else if (EltVT.isFloatingPoint()) 1345 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1346 else 1347 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1348 } 1349 1350 return DAG.getMergeValues(Constants, getCurSDLoc()); 1351 } 1352 1353 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1354 return DAG.getBlockAddress(BA, VT); 1355 1356 VectorType *VecTy = cast<VectorType>(V->getType()); 1357 unsigned NumElements = VecTy->getNumElements(); 1358 1359 // Now that we know the number and type of the elements, get that number of 1360 // elements into the Ops array based on what kind of constant it is. 1361 SmallVector<SDValue, 16> Ops; 1362 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1363 for (unsigned i = 0; i != NumElements; ++i) 1364 Ops.push_back(getValue(CV->getOperand(i))); 1365 } else { 1366 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1367 EVT EltVT = 1368 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1369 1370 SDValue Op; 1371 if (EltVT.isFloatingPoint()) 1372 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1373 else 1374 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1375 Ops.assign(NumElements, Op); 1376 } 1377 1378 // Create a BUILD_VECTOR node. 1379 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1380 } 1381 1382 // If this is a static alloca, generate it as the frameindex instead of 1383 // computation. 1384 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1385 DenseMap<const AllocaInst*, int>::iterator SI = 1386 FuncInfo.StaticAllocaMap.find(AI); 1387 if (SI != FuncInfo.StaticAllocaMap.end()) 1388 return DAG.getFrameIndex(SI->second, 1389 TLI.getFrameIndexTy(DAG.getDataLayout())); 1390 } 1391 1392 // If this is an instruction which fast-isel has deferred, select it now. 1393 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1394 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1395 1396 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1397 Inst->getType(), getABIRegCopyCC(V)); 1398 SDValue Chain = DAG.getEntryNode(); 1399 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1400 } 1401 1402 llvm_unreachable("Can't get register for value!"); 1403 } 1404 1405 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1406 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1407 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1408 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1409 bool IsSEH = isAsynchronousEHPersonality(Pers); 1410 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1411 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1412 if (!IsSEH) 1413 CatchPadMBB->setIsEHScopeEntry(); 1414 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1415 if (IsMSVCCXX || IsCoreCLR) 1416 CatchPadMBB->setIsEHFuncletEntry(); 1417 // Wasm does not need catchpads anymore 1418 if (!IsWasmCXX) 1419 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1420 getControlRoot())); 1421 } 1422 1423 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1424 // Update machine-CFG edge. 1425 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1426 FuncInfo.MBB->addSuccessor(TargetMBB); 1427 1428 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1429 bool IsSEH = isAsynchronousEHPersonality(Pers); 1430 if (IsSEH) { 1431 // If this is not a fall-through branch or optimizations are switched off, 1432 // emit the branch. 1433 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1434 TM.getOptLevel() == CodeGenOpt::None) 1435 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1436 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1437 return; 1438 } 1439 1440 // Figure out the funclet membership for the catchret's successor. 1441 // This will be used by the FuncletLayout pass to determine how to order the 1442 // BB's. 1443 // A 'catchret' returns to the outer scope's color. 1444 Value *ParentPad = I.getCatchSwitchParentPad(); 1445 const BasicBlock *SuccessorColor; 1446 if (isa<ConstantTokenNone>(ParentPad)) 1447 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1448 else 1449 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1450 assert(SuccessorColor && "No parent funclet for catchret!"); 1451 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1452 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1453 1454 // Create the terminator node. 1455 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1456 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1457 DAG.getBasicBlock(SuccessorColorMBB)); 1458 DAG.setRoot(Ret); 1459 } 1460 1461 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1462 // Don't emit any special code for the cleanuppad instruction. It just marks 1463 // the start of an EH scope/funclet. 1464 FuncInfo.MBB->setIsEHScopeEntry(); 1465 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1466 if (Pers != EHPersonality::Wasm_CXX) { 1467 FuncInfo.MBB->setIsEHFuncletEntry(); 1468 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1469 } 1470 } 1471 1472 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1473 /// many places it could ultimately go. In the IR, we have a single unwind 1474 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1475 /// This function skips over imaginary basic blocks that hold catchswitch 1476 /// instructions, and finds all the "real" machine 1477 /// basic block destinations. As those destinations may not be successors of 1478 /// EHPadBB, here we also calculate the edge probability to those destinations. 1479 /// The passed-in Prob is the edge probability to EHPadBB. 1480 static void findUnwindDestinations( 1481 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1482 BranchProbability Prob, 1483 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1484 &UnwindDests) { 1485 EHPersonality Personality = 1486 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1487 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1488 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1489 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1490 bool IsSEH = isAsynchronousEHPersonality(Personality); 1491 1492 while (EHPadBB) { 1493 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1494 BasicBlock *NewEHPadBB = nullptr; 1495 if (isa<LandingPadInst>(Pad)) { 1496 // Stop on landingpads. They are not funclets. 1497 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1498 break; 1499 } else if (isa<CleanupPadInst>(Pad)) { 1500 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1501 // personalities. 1502 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1503 UnwindDests.back().first->setIsEHScopeEntry(); 1504 if (!IsWasmCXX) 1505 UnwindDests.back().first->setIsEHFuncletEntry(); 1506 break; 1507 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1508 // Add the catchpad handlers to the possible destinations. 1509 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1510 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1511 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1512 if (IsMSVCCXX || IsCoreCLR) 1513 UnwindDests.back().first->setIsEHFuncletEntry(); 1514 if (!IsSEH) 1515 UnwindDests.back().first->setIsEHScopeEntry(); 1516 } 1517 NewEHPadBB = CatchSwitch->getUnwindDest(); 1518 } else { 1519 continue; 1520 } 1521 1522 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1523 if (BPI && NewEHPadBB) 1524 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1525 EHPadBB = NewEHPadBB; 1526 } 1527 } 1528 1529 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1530 // Update successor info. 1531 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1532 auto UnwindDest = I.getUnwindDest(); 1533 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1534 BranchProbability UnwindDestProb = 1535 (BPI && UnwindDest) 1536 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1537 : BranchProbability::getZero(); 1538 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1539 for (auto &UnwindDest : UnwindDests) { 1540 UnwindDest.first->setIsEHPad(); 1541 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1542 } 1543 FuncInfo.MBB->normalizeSuccProbs(); 1544 1545 // Create the terminator node. 1546 SDValue Ret = 1547 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1548 DAG.setRoot(Ret); 1549 } 1550 1551 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1552 report_fatal_error("visitCatchSwitch not yet implemented!"); 1553 } 1554 1555 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1556 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1557 auto &DL = DAG.getDataLayout(); 1558 SDValue Chain = getControlRoot(); 1559 SmallVector<ISD::OutputArg, 8> Outs; 1560 SmallVector<SDValue, 8> OutVals; 1561 1562 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1563 // lower 1564 // 1565 // %val = call <ty> @llvm.experimental.deoptimize() 1566 // ret <ty> %val 1567 // 1568 // differently. 1569 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1570 LowerDeoptimizingReturn(); 1571 return; 1572 } 1573 1574 if (!FuncInfo.CanLowerReturn) { 1575 unsigned DemoteReg = FuncInfo.DemoteRegister; 1576 const Function *F = I.getParent()->getParent(); 1577 1578 // Emit a store of the return value through the virtual register. 1579 // Leave Outs empty so that LowerReturn won't try to load return 1580 // registers the usual way. 1581 SmallVector<EVT, 1> PtrValueVTs; 1582 ComputeValueVTs(TLI, DL, 1583 F->getReturnType()->getPointerTo( 1584 DAG.getDataLayout().getAllocaAddrSpace()), 1585 PtrValueVTs); 1586 1587 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1588 DemoteReg, PtrValueVTs[0]); 1589 SDValue RetOp = getValue(I.getOperand(0)); 1590 1591 SmallVector<EVT, 4> ValueVTs; 1592 SmallVector<uint64_t, 4> Offsets; 1593 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1594 unsigned NumValues = ValueVTs.size(); 1595 1596 SmallVector<SDValue, 4> Chains(NumValues); 1597 for (unsigned i = 0; i != NumValues; ++i) { 1598 // An aggregate return value cannot wrap around the address space, so 1599 // offsets to its parts don't wrap either. 1600 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1601 Chains[i] = DAG.getStore( 1602 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1603 // FIXME: better loc info would be nice. 1604 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1605 } 1606 1607 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1608 MVT::Other, Chains); 1609 } else if (I.getNumOperands() != 0) { 1610 SmallVector<EVT, 4> ValueVTs; 1611 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1612 unsigned NumValues = ValueVTs.size(); 1613 if (NumValues) { 1614 SDValue RetOp = getValue(I.getOperand(0)); 1615 1616 const Function *F = I.getParent()->getParent(); 1617 1618 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1619 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1620 Attribute::SExt)) 1621 ExtendKind = ISD::SIGN_EXTEND; 1622 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1623 Attribute::ZExt)) 1624 ExtendKind = ISD::ZERO_EXTEND; 1625 1626 LLVMContext &Context = F->getContext(); 1627 bool RetInReg = F->getAttributes().hasAttribute( 1628 AttributeList::ReturnIndex, Attribute::InReg); 1629 1630 for (unsigned j = 0; j != NumValues; ++j) { 1631 EVT VT = ValueVTs[j]; 1632 1633 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1634 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1635 1636 CallingConv::ID CC = F->getCallingConv(); 1637 1638 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1639 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1640 SmallVector<SDValue, 4> Parts(NumParts); 1641 getCopyToParts(DAG, getCurSDLoc(), 1642 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1643 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1644 1645 // 'inreg' on function refers to return value 1646 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1647 if (RetInReg) 1648 Flags.setInReg(); 1649 1650 // Propagate extension type if any 1651 if (ExtendKind == ISD::SIGN_EXTEND) 1652 Flags.setSExt(); 1653 else if (ExtendKind == ISD::ZERO_EXTEND) 1654 Flags.setZExt(); 1655 1656 for (unsigned i = 0; i < NumParts; ++i) { 1657 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1658 VT, /*isfixed=*/true, 0, 0)); 1659 OutVals.push_back(Parts[i]); 1660 } 1661 } 1662 } 1663 } 1664 1665 // Push in swifterror virtual register as the last element of Outs. This makes 1666 // sure swifterror virtual register will be returned in the swifterror 1667 // physical register. 1668 const Function *F = I.getParent()->getParent(); 1669 if (TLI.supportSwiftError() && 1670 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1671 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1672 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1673 Flags.setSwiftError(); 1674 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1675 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1676 true /*isfixed*/, 1 /*origidx*/, 1677 0 /*partOffs*/)); 1678 // Create SDNode for the swifterror virtual register. 1679 OutVals.push_back( 1680 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1681 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1682 EVT(TLI.getPointerTy(DL)))); 1683 } 1684 1685 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1686 CallingConv::ID CallConv = 1687 DAG.getMachineFunction().getFunction().getCallingConv(); 1688 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1689 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1690 1691 // Verify that the target's LowerReturn behaved as expected. 1692 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1693 "LowerReturn didn't return a valid chain!"); 1694 1695 // Update the DAG with the new chain value resulting from return lowering. 1696 DAG.setRoot(Chain); 1697 } 1698 1699 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1700 /// created for it, emit nodes to copy the value into the virtual 1701 /// registers. 1702 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1703 // Skip empty types 1704 if (V->getType()->isEmptyTy()) 1705 return; 1706 1707 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1708 if (VMI != FuncInfo.ValueMap.end()) { 1709 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1710 CopyValueToVirtualRegister(V, VMI->second); 1711 } 1712 } 1713 1714 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1715 /// the current basic block, add it to ValueMap now so that we'll get a 1716 /// CopyTo/FromReg. 1717 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1718 // No need to export constants. 1719 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1720 1721 // Already exported? 1722 if (FuncInfo.isExportedInst(V)) return; 1723 1724 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1725 CopyValueToVirtualRegister(V, Reg); 1726 } 1727 1728 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1729 const BasicBlock *FromBB) { 1730 // The operands of the setcc have to be in this block. We don't know 1731 // how to export them from some other block. 1732 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1733 // Can export from current BB. 1734 if (VI->getParent() == FromBB) 1735 return true; 1736 1737 // Is already exported, noop. 1738 return FuncInfo.isExportedInst(V); 1739 } 1740 1741 // If this is an argument, we can export it if the BB is the entry block or 1742 // if it is already exported. 1743 if (isa<Argument>(V)) { 1744 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1745 return true; 1746 1747 // Otherwise, can only export this if it is already exported. 1748 return FuncInfo.isExportedInst(V); 1749 } 1750 1751 // Otherwise, constants can always be exported. 1752 return true; 1753 } 1754 1755 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1756 BranchProbability 1757 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1758 const MachineBasicBlock *Dst) const { 1759 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1760 const BasicBlock *SrcBB = Src->getBasicBlock(); 1761 const BasicBlock *DstBB = Dst->getBasicBlock(); 1762 if (!BPI) { 1763 // If BPI is not available, set the default probability as 1 / N, where N is 1764 // the number of successors. 1765 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1766 return BranchProbability(1, SuccSize); 1767 } 1768 return BPI->getEdgeProbability(SrcBB, DstBB); 1769 } 1770 1771 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1772 MachineBasicBlock *Dst, 1773 BranchProbability Prob) { 1774 if (!FuncInfo.BPI) 1775 Src->addSuccessorWithoutProb(Dst); 1776 else { 1777 if (Prob.isUnknown()) 1778 Prob = getEdgeProbability(Src, Dst); 1779 Src->addSuccessor(Dst, Prob); 1780 } 1781 } 1782 1783 static bool InBlock(const Value *V, const BasicBlock *BB) { 1784 if (const Instruction *I = dyn_cast<Instruction>(V)) 1785 return I->getParent() == BB; 1786 return true; 1787 } 1788 1789 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1790 /// This function emits a branch and is used at the leaves of an OR or an 1791 /// AND operator tree. 1792 void 1793 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1794 MachineBasicBlock *TBB, 1795 MachineBasicBlock *FBB, 1796 MachineBasicBlock *CurBB, 1797 MachineBasicBlock *SwitchBB, 1798 BranchProbability TProb, 1799 BranchProbability FProb, 1800 bool InvertCond) { 1801 const BasicBlock *BB = CurBB->getBasicBlock(); 1802 1803 // If the leaf of the tree is a comparison, merge the condition into 1804 // the caseblock. 1805 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1806 // The operands of the cmp have to be in this block. We don't know 1807 // how to export them from some other block. If this is the first block 1808 // of the sequence, no exporting is needed. 1809 if (CurBB == SwitchBB || 1810 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1811 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1812 ISD::CondCode Condition; 1813 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1814 ICmpInst::Predicate Pred = 1815 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 1816 Condition = getICmpCondCode(Pred); 1817 } else { 1818 const FCmpInst *FC = cast<FCmpInst>(Cond); 1819 FCmpInst::Predicate Pred = 1820 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 1821 Condition = getFCmpCondCode(Pred); 1822 if (TM.Options.NoNaNsFPMath) 1823 Condition = getFCmpCodeWithoutNaN(Condition); 1824 } 1825 1826 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1827 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1828 SwitchCases.push_back(CB); 1829 return; 1830 } 1831 } 1832 1833 // Create a CaseBlock record representing this branch. 1834 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 1835 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 1836 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1837 SwitchCases.push_back(CB); 1838 } 1839 1840 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1841 MachineBasicBlock *TBB, 1842 MachineBasicBlock *FBB, 1843 MachineBasicBlock *CurBB, 1844 MachineBasicBlock *SwitchBB, 1845 Instruction::BinaryOps Opc, 1846 BranchProbability TProb, 1847 BranchProbability FProb, 1848 bool InvertCond) { 1849 // Skip over not part of the tree and remember to invert op and operands at 1850 // next level. 1851 Value *NotCond; 1852 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 1853 InBlock(NotCond, CurBB->getBasicBlock())) { 1854 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 1855 !InvertCond); 1856 return; 1857 } 1858 1859 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1860 // Compute the effective opcode for Cond, taking into account whether it needs 1861 // to be inverted, e.g. 1862 // and (not (or A, B)), C 1863 // gets lowered as 1864 // and (and (not A, not B), C) 1865 unsigned BOpc = 0; 1866 if (BOp) { 1867 BOpc = BOp->getOpcode(); 1868 if (InvertCond) { 1869 if (BOpc == Instruction::And) 1870 BOpc = Instruction::Or; 1871 else if (BOpc == Instruction::Or) 1872 BOpc = Instruction::And; 1873 } 1874 } 1875 1876 // If this node is not part of the or/and tree, emit it as a branch. 1877 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1878 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 1879 BOp->getParent() != CurBB->getBasicBlock() || 1880 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1881 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1882 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1883 TProb, FProb, InvertCond); 1884 return; 1885 } 1886 1887 // Create TmpBB after CurBB. 1888 MachineFunction::iterator BBI(CurBB); 1889 MachineFunction &MF = DAG.getMachineFunction(); 1890 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1891 CurBB->getParent()->insert(++BBI, TmpBB); 1892 1893 if (Opc == Instruction::Or) { 1894 // Codegen X | Y as: 1895 // BB1: 1896 // jmp_if_X TBB 1897 // jmp TmpBB 1898 // TmpBB: 1899 // jmp_if_Y TBB 1900 // jmp FBB 1901 // 1902 1903 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1904 // The requirement is that 1905 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1906 // = TrueProb for original BB. 1907 // Assuming the original probabilities are A and B, one choice is to set 1908 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1909 // A/(1+B) and 2B/(1+B). This choice assumes that 1910 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1911 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1912 // TmpBB, but the math is more complicated. 1913 1914 auto NewTrueProb = TProb / 2; 1915 auto NewFalseProb = TProb / 2 + FProb; 1916 // Emit the LHS condition. 1917 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1918 NewTrueProb, NewFalseProb, InvertCond); 1919 1920 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1921 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 1922 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1923 // Emit the RHS condition into TmpBB. 1924 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1925 Probs[0], Probs[1], InvertCond); 1926 } else { 1927 assert(Opc == Instruction::And && "Unknown merge op!"); 1928 // Codegen X & Y as: 1929 // BB1: 1930 // jmp_if_X TmpBB 1931 // jmp FBB 1932 // TmpBB: 1933 // jmp_if_Y TBB 1934 // jmp FBB 1935 // 1936 // This requires creation of TmpBB after CurBB. 1937 1938 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1939 // The requirement is that 1940 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1941 // = FalseProb for original BB. 1942 // Assuming the original probabilities are A and B, one choice is to set 1943 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1944 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1945 // TrueProb for BB1 * FalseProb for TmpBB. 1946 1947 auto NewTrueProb = TProb + FProb / 2; 1948 auto NewFalseProb = FProb / 2; 1949 // Emit the LHS condition. 1950 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1951 NewTrueProb, NewFalseProb, InvertCond); 1952 1953 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1954 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 1955 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1956 // Emit the RHS condition into TmpBB. 1957 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1958 Probs[0], Probs[1], InvertCond); 1959 } 1960 } 1961 1962 /// If the set of cases should be emitted as a series of branches, return true. 1963 /// If we should emit this as a bunch of and/or'd together conditions, return 1964 /// false. 1965 bool 1966 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1967 if (Cases.size() != 2) return true; 1968 1969 // If this is two comparisons of the same values or'd or and'd together, they 1970 // will get folded into a single comparison, so don't emit two blocks. 1971 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1972 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1973 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1974 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1975 return false; 1976 } 1977 1978 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1979 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1980 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1981 Cases[0].CC == Cases[1].CC && 1982 isa<Constant>(Cases[0].CmpRHS) && 1983 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1984 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1985 return false; 1986 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1987 return false; 1988 } 1989 1990 return true; 1991 } 1992 1993 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1994 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1995 1996 // Update machine-CFG edges. 1997 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1998 1999 if (I.isUnconditional()) { 2000 // Update machine-CFG edges. 2001 BrMBB->addSuccessor(Succ0MBB); 2002 2003 // If this is not a fall-through branch or optimizations are switched off, 2004 // emit the branch. 2005 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2006 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2007 MVT::Other, getControlRoot(), 2008 DAG.getBasicBlock(Succ0MBB))); 2009 2010 return; 2011 } 2012 2013 // If this condition is one of the special cases we handle, do special stuff 2014 // now. 2015 const Value *CondVal = I.getCondition(); 2016 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2017 2018 // If this is a series of conditions that are or'd or and'd together, emit 2019 // this as a sequence of branches instead of setcc's with and/or operations. 2020 // As long as jumps are not expensive, this should improve performance. 2021 // For example, instead of something like: 2022 // cmp A, B 2023 // C = seteq 2024 // cmp D, E 2025 // F = setle 2026 // or C, F 2027 // jnz foo 2028 // Emit: 2029 // cmp A, B 2030 // je foo 2031 // cmp D, E 2032 // jle foo 2033 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2034 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2035 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2036 !I.getMetadata(LLVMContext::MD_unpredictable) && 2037 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2038 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2039 Opcode, 2040 getEdgeProbability(BrMBB, Succ0MBB), 2041 getEdgeProbability(BrMBB, Succ1MBB), 2042 /*InvertCond=*/false); 2043 // If the compares in later blocks need to use values not currently 2044 // exported from this block, export them now. This block should always 2045 // be the first entry. 2046 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2047 2048 // Allow some cases to be rejected. 2049 if (ShouldEmitAsBranches(SwitchCases)) { 2050 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2051 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2052 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2053 } 2054 2055 // Emit the branch for this block. 2056 visitSwitchCase(SwitchCases[0], BrMBB); 2057 SwitchCases.erase(SwitchCases.begin()); 2058 return; 2059 } 2060 2061 // Okay, we decided not to do this, remove any inserted MBB's and clear 2062 // SwitchCases. 2063 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2064 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2065 2066 SwitchCases.clear(); 2067 } 2068 } 2069 2070 // Create a CaseBlock record representing this branch. 2071 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2072 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2073 2074 // Use visitSwitchCase to actually insert the fast branch sequence for this 2075 // cond branch. 2076 visitSwitchCase(CB, BrMBB); 2077 } 2078 2079 /// visitSwitchCase - Emits the necessary code to represent a single node in 2080 /// the binary search tree resulting from lowering a switch instruction. 2081 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2082 MachineBasicBlock *SwitchBB) { 2083 SDValue Cond; 2084 SDValue CondLHS = getValue(CB.CmpLHS); 2085 SDLoc dl = CB.DL; 2086 2087 // Build the setcc now. 2088 if (!CB.CmpMHS) { 2089 // Fold "(X == true)" to X and "(X == false)" to !X to 2090 // handle common cases produced by branch lowering. 2091 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2092 CB.CC == ISD::SETEQ) 2093 Cond = CondLHS; 2094 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2095 CB.CC == ISD::SETEQ) { 2096 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2097 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2098 } else 2099 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2100 } else { 2101 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2102 2103 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2104 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2105 2106 SDValue CmpOp = getValue(CB.CmpMHS); 2107 EVT VT = CmpOp.getValueType(); 2108 2109 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2110 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2111 ISD::SETLE); 2112 } else { 2113 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2114 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2115 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2116 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2117 } 2118 } 2119 2120 // Update successor info 2121 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2122 // TrueBB and FalseBB are always different unless the incoming IR is 2123 // degenerate. This only happens when running llc on weird IR. 2124 if (CB.TrueBB != CB.FalseBB) 2125 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2126 SwitchBB->normalizeSuccProbs(); 2127 2128 // If the lhs block is the next block, invert the condition so that we can 2129 // fall through to the lhs instead of the rhs block. 2130 if (CB.TrueBB == NextBlock(SwitchBB)) { 2131 std::swap(CB.TrueBB, CB.FalseBB); 2132 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2133 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2134 } 2135 2136 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2137 MVT::Other, getControlRoot(), Cond, 2138 DAG.getBasicBlock(CB.TrueBB)); 2139 2140 // Insert the false branch. Do this even if it's a fall through branch, 2141 // this makes it easier to do DAG optimizations which require inverting 2142 // the branch condition. 2143 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2144 DAG.getBasicBlock(CB.FalseBB)); 2145 2146 DAG.setRoot(BrCond); 2147 } 2148 2149 /// visitJumpTable - Emit JumpTable node in the current MBB 2150 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2151 // Emit the code for the jump table 2152 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2153 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2154 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2155 JT.Reg, PTy); 2156 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2157 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2158 MVT::Other, Index.getValue(1), 2159 Table, Index); 2160 DAG.setRoot(BrJumpTable); 2161 } 2162 2163 /// visitJumpTableHeader - This function emits necessary code to produce index 2164 /// in the JumpTable from switch case. 2165 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2166 JumpTableHeader &JTH, 2167 MachineBasicBlock *SwitchBB) { 2168 SDLoc dl = getCurSDLoc(); 2169 2170 // Subtract the lowest switch case value from the value being switched on and 2171 // conditional branch to default mbb if the result is greater than the 2172 // difference between smallest and largest cases. 2173 SDValue SwitchOp = getValue(JTH.SValue); 2174 EVT VT = SwitchOp.getValueType(); 2175 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2176 DAG.getConstant(JTH.First, dl, VT)); 2177 2178 // The SDNode we just created, which holds the value being switched on minus 2179 // the smallest case value, needs to be copied to a virtual register so it 2180 // can be used as an index into the jump table in a subsequent basic block. 2181 // This value may be smaller or larger than the target's pointer type, and 2182 // therefore require extension or truncating. 2183 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2184 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2185 2186 unsigned JumpTableReg = 2187 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2188 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2189 JumpTableReg, SwitchOp); 2190 JT.Reg = JumpTableReg; 2191 2192 if (!JTH.OmitRangeCheck) { 2193 // Emit the range check for the jump table, and branch to the default block 2194 // for the switch statement if the value being switched on exceeds the 2195 // largest case in the switch. 2196 SDValue CMP = DAG.getSetCC( 2197 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2198 Sub.getValueType()), 2199 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2200 2201 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2202 MVT::Other, CopyTo, CMP, 2203 DAG.getBasicBlock(JT.Default)); 2204 2205 // Avoid emitting unnecessary branches to the next block. 2206 if (JT.MBB != NextBlock(SwitchBB)) 2207 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2208 DAG.getBasicBlock(JT.MBB)); 2209 2210 DAG.setRoot(BrCond); 2211 } else { 2212 SDValue BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2213 DAG.getBasicBlock(JT.MBB)); 2214 DAG.setRoot(BrCond); 2215 } 2216 } 2217 2218 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2219 /// variable if there exists one. 2220 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2221 SDValue &Chain) { 2222 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2223 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2224 MachineFunction &MF = DAG.getMachineFunction(); 2225 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2226 MachineSDNode *Node = 2227 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2228 if (Global) { 2229 MachinePointerInfo MPInfo(Global); 2230 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2231 MachineMemOperand::MODereferenceable; 2232 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2233 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2234 DAG.setNodeMemRefs(Node, {MemRef}); 2235 } 2236 return SDValue(Node, 0); 2237 } 2238 2239 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2240 /// tail spliced into a stack protector check success bb. 2241 /// 2242 /// For a high level explanation of how this fits into the stack protector 2243 /// generation see the comment on the declaration of class 2244 /// StackProtectorDescriptor. 2245 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2246 MachineBasicBlock *ParentBB) { 2247 2248 // First create the loads to the guard/stack slot for the comparison. 2249 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2250 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2251 2252 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2253 int FI = MFI.getStackProtectorIndex(); 2254 2255 SDValue Guard; 2256 SDLoc dl = getCurSDLoc(); 2257 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2258 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2259 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2260 2261 // Generate code to load the content of the guard slot. 2262 SDValue GuardVal = DAG.getLoad( 2263 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2264 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2265 MachineMemOperand::MOVolatile); 2266 2267 if (TLI.useStackGuardXorFP()) 2268 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2269 2270 // Retrieve guard check function, nullptr if instrumentation is inlined. 2271 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2272 // The target provides a guard check function to validate the guard value. 2273 // Generate a call to that function with the content of the guard slot as 2274 // argument. 2275 auto *Fn = cast<Function>(GuardCheck); 2276 FunctionType *FnTy = Fn->getFunctionType(); 2277 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2278 2279 TargetLowering::ArgListTy Args; 2280 TargetLowering::ArgListEntry Entry; 2281 Entry.Node = GuardVal; 2282 Entry.Ty = FnTy->getParamType(0); 2283 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2284 Entry.IsInReg = true; 2285 Args.push_back(Entry); 2286 2287 TargetLowering::CallLoweringInfo CLI(DAG); 2288 CLI.setDebugLoc(getCurSDLoc()) 2289 .setChain(DAG.getEntryNode()) 2290 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2291 getValue(GuardCheck), std::move(Args)); 2292 2293 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2294 DAG.setRoot(Result.second); 2295 return; 2296 } 2297 2298 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2299 // Otherwise, emit a volatile load to retrieve the stack guard value. 2300 SDValue Chain = DAG.getEntryNode(); 2301 if (TLI.useLoadStackGuardNode()) { 2302 Guard = getLoadStackGuard(DAG, dl, Chain); 2303 } else { 2304 const Value *IRGuard = TLI.getSDagStackGuard(M); 2305 SDValue GuardPtr = getValue(IRGuard); 2306 2307 Guard = 2308 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2309 Align, MachineMemOperand::MOVolatile); 2310 } 2311 2312 // Perform the comparison via a subtract/getsetcc. 2313 EVT VT = Guard.getValueType(); 2314 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2315 2316 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2317 *DAG.getContext(), 2318 Sub.getValueType()), 2319 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2320 2321 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2322 // branch to failure MBB. 2323 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2324 MVT::Other, GuardVal.getOperand(0), 2325 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2326 // Otherwise branch to success MBB. 2327 SDValue Br = DAG.getNode(ISD::BR, dl, 2328 MVT::Other, BrCond, 2329 DAG.getBasicBlock(SPD.getSuccessMBB())); 2330 2331 DAG.setRoot(Br); 2332 } 2333 2334 /// Codegen the failure basic block for a stack protector check. 2335 /// 2336 /// A failure stack protector machine basic block consists simply of a call to 2337 /// __stack_chk_fail(). 2338 /// 2339 /// For a high level explanation of how this fits into the stack protector 2340 /// generation see the comment on the declaration of class 2341 /// StackProtectorDescriptor. 2342 void 2343 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2344 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2345 SDValue Chain = 2346 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2347 None, false, getCurSDLoc(), false, false).second; 2348 DAG.setRoot(Chain); 2349 } 2350 2351 /// visitBitTestHeader - This function emits necessary code to produce value 2352 /// suitable for "bit tests" 2353 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2354 MachineBasicBlock *SwitchBB) { 2355 SDLoc dl = getCurSDLoc(); 2356 2357 // Subtract the minimum value 2358 SDValue SwitchOp = getValue(B.SValue); 2359 EVT VT = SwitchOp.getValueType(); 2360 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2361 DAG.getConstant(B.First, dl, VT)); 2362 2363 // Check range 2364 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2365 SDValue RangeCmp = DAG.getSetCC( 2366 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2367 Sub.getValueType()), 2368 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2369 2370 // Determine the type of the test operands. 2371 bool UsePtrType = false; 2372 if (!TLI.isTypeLegal(VT)) 2373 UsePtrType = true; 2374 else { 2375 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2376 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2377 // Switch table case range are encoded into series of masks. 2378 // Just use pointer type, it's guaranteed to fit. 2379 UsePtrType = true; 2380 break; 2381 } 2382 } 2383 if (UsePtrType) { 2384 VT = TLI.getPointerTy(DAG.getDataLayout()); 2385 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2386 } 2387 2388 B.RegVT = VT.getSimpleVT(); 2389 B.Reg = FuncInfo.CreateReg(B.RegVT); 2390 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2391 2392 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2393 2394 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2395 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2396 SwitchBB->normalizeSuccProbs(); 2397 2398 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2399 MVT::Other, CopyTo, RangeCmp, 2400 DAG.getBasicBlock(B.Default)); 2401 2402 // Avoid emitting unnecessary branches to the next block. 2403 if (MBB != NextBlock(SwitchBB)) 2404 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2405 DAG.getBasicBlock(MBB)); 2406 2407 DAG.setRoot(BrRange); 2408 } 2409 2410 /// visitBitTestCase - this function produces one "bit test" 2411 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2412 MachineBasicBlock* NextMBB, 2413 BranchProbability BranchProbToNext, 2414 unsigned Reg, 2415 BitTestCase &B, 2416 MachineBasicBlock *SwitchBB) { 2417 SDLoc dl = getCurSDLoc(); 2418 MVT VT = BB.RegVT; 2419 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2420 SDValue Cmp; 2421 unsigned PopCount = countPopulation(B.Mask); 2422 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2423 if (PopCount == 1) { 2424 // Testing for a single bit; just compare the shift count with what it 2425 // would need to be to shift a 1 bit in that position. 2426 Cmp = DAG.getSetCC( 2427 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2428 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2429 ISD::SETEQ); 2430 } else if (PopCount == BB.Range) { 2431 // There is only one zero bit in the range, test for it directly. 2432 Cmp = DAG.getSetCC( 2433 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2434 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2435 ISD::SETNE); 2436 } else { 2437 // Make desired shift 2438 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2439 DAG.getConstant(1, dl, VT), ShiftOp); 2440 2441 // Emit bit tests and jumps 2442 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2443 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2444 Cmp = DAG.getSetCC( 2445 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2446 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2447 } 2448 2449 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2450 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2451 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2452 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2453 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2454 // one as they are relative probabilities (and thus work more like weights), 2455 // and hence we need to normalize them to let the sum of them become one. 2456 SwitchBB->normalizeSuccProbs(); 2457 2458 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2459 MVT::Other, getControlRoot(), 2460 Cmp, DAG.getBasicBlock(B.TargetBB)); 2461 2462 // Avoid emitting unnecessary branches to the next block. 2463 if (NextMBB != NextBlock(SwitchBB)) 2464 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2465 DAG.getBasicBlock(NextMBB)); 2466 2467 DAG.setRoot(BrAnd); 2468 } 2469 2470 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2471 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2472 2473 // Retrieve successors. Look through artificial IR level blocks like 2474 // catchswitch for successors. 2475 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2476 const BasicBlock *EHPadBB = I.getSuccessor(1); 2477 2478 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2479 // have to do anything here to lower funclet bundles. 2480 assert(!I.hasOperandBundlesOtherThan( 2481 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2482 "Cannot lower invokes with arbitrary operand bundles yet!"); 2483 2484 const Value *Callee(I.getCalledValue()); 2485 const Function *Fn = dyn_cast<Function>(Callee); 2486 if (isa<InlineAsm>(Callee)) 2487 visitInlineAsm(&I); 2488 else if (Fn && Fn->isIntrinsic()) { 2489 switch (Fn->getIntrinsicID()) { 2490 default: 2491 llvm_unreachable("Cannot invoke this intrinsic"); 2492 case Intrinsic::donothing: 2493 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2494 break; 2495 case Intrinsic::experimental_patchpoint_void: 2496 case Intrinsic::experimental_patchpoint_i64: 2497 visitPatchpoint(&I, EHPadBB); 2498 break; 2499 case Intrinsic::experimental_gc_statepoint: 2500 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2501 break; 2502 } 2503 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2504 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2505 // Eventually we will support lowering the @llvm.experimental.deoptimize 2506 // intrinsic, and right now there are no plans to support other intrinsics 2507 // with deopt state. 2508 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2509 } else { 2510 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2511 } 2512 2513 // If the value of the invoke is used outside of its defining block, make it 2514 // available as a virtual register. 2515 // We already took care of the exported value for the statepoint instruction 2516 // during call to the LowerStatepoint. 2517 if (!isStatepoint(I)) { 2518 CopyToExportRegsIfNeeded(&I); 2519 } 2520 2521 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2522 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2523 BranchProbability EHPadBBProb = 2524 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2525 : BranchProbability::getZero(); 2526 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2527 2528 // Update successor info. 2529 addSuccessorWithProb(InvokeMBB, Return); 2530 for (auto &UnwindDest : UnwindDests) { 2531 UnwindDest.first->setIsEHPad(); 2532 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2533 } 2534 InvokeMBB->normalizeSuccProbs(); 2535 2536 // Drop into normal successor. 2537 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2538 MVT::Other, getControlRoot(), 2539 DAG.getBasicBlock(Return))); 2540 } 2541 2542 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2543 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2544 } 2545 2546 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2547 assert(FuncInfo.MBB->isEHPad() && 2548 "Call to landingpad not in landing pad!"); 2549 2550 // If there aren't registers to copy the values into (e.g., during SjLj 2551 // exceptions), then don't bother to create these DAG nodes. 2552 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2553 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2554 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2555 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2556 return; 2557 2558 // If landingpad's return type is token type, we don't create DAG nodes 2559 // for its exception pointer and selector value. The extraction of exception 2560 // pointer or selector value from token type landingpads is not currently 2561 // supported. 2562 if (LP.getType()->isTokenTy()) 2563 return; 2564 2565 SmallVector<EVT, 2> ValueVTs; 2566 SDLoc dl = getCurSDLoc(); 2567 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2568 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2569 2570 // Get the two live-in registers as SDValues. The physregs have already been 2571 // copied into virtual registers. 2572 SDValue Ops[2]; 2573 if (FuncInfo.ExceptionPointerVirtReg) { 2574 Ops[0] = DAG.getZExtOrTrunc( 2575 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2576 FuncInfo.ExceptionPointerVirtReg, 2577 TLI.getPointerTy(DAG.getDataLayout())), 2578 dl, ValueVTs[0]); 2579 } else { 2580 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2581 } 2582 Ops[1] = DAG.getZExtOrTrunc( 2583 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2584 FuncInfo.ExceptionSelectorVirtReg, 2585 TLI.getPointerTy(DAG.getDataLayout())), 2586 dl, ValueVTs[1]); 2587 2588 // Merge into one. 2589 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2590 DAG.getVTList(ValueVTs), Ops); 2591 setValue(&LP, Res); 2592 } 2593 2594 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2595 #ifndef NDEBUG 2596 for (const CaseCluster &CC : Clusters) 2597 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2598 #endif 2599 2600 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2601 return a.Low->getValue().slt(b.Low->getValue()); 2602 }); 2603 2604 // Merge adjacent clusters with the same destination. 2605 const unsigned N = Clusters.size(); 2606 unsigned DstIndex = 0; 2607 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2608 CaseCluster &CC = Clusters[SrcIndex]; 2609 const ConstantInt *CaseVal = CC.Low; 2610 MachineBasicBlock *Succ = CC.MBB; 2611 2612 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2613 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2614 // If this case has the same successor and is a neighbour, merge it into 2615 // the previous cluster. 2616 Clusters[DstIndex - 1].High = CaseVal; 2617 Clusters[DstIndex - 1].Prob += CC.Prob; 2618 } else { 2619 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2620 sizeof(Clusters[SrcIndex])); 2621 } 2622 } 2623 Clusters.resize(DstIndex); 2624 } 2625 2626 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2627 MachineBasicBlock *Last) { 2628 // Update JTCases. 2629 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2630 if (JTCases[i].first.HeaderBB == First) 2631 JTCases[i].first.HeaderBB = Last; 2632 2633 // Update BitTestCases. 2634 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2635 if (BitTestCases[i].Parent == First) 2636 BitTestCases[i].Parent = Last; 2637 } 2638 2639 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2640 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2641 2642 // Update machine-CFG edges with unique successors. 2643 SmallSet<BasicBlock*, 32> Done; 2644 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2645 BasicBlock *BB = I.getSuccessor(i); 2646 bool Inserted = Done.insert(BB).second; 2647 if (!Inserted) 2648 continue; 2649 2650 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2651 addSuccessorWithProb(IndirectBrMBB, Succ); 2652 } 2653 IndirectBrMBB->normalizeSuccProbs(); 2654 2655 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2656 MVT::Other, getControlRoot(), 2657 getValue(I.getAddress()))); 2658 } 2659 2660 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2661 if (!DAG.getTarget().Options.TrapUnreachable) 2662 return; 2663 2664 // We may be able to ignore unreachable behind a noreturn call. 2665 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2666 const BasicBlock &BB = *I.getParent(); 2667 if (&I != &BB.front()) { 2668 BasicBlock::const_iterator PredI = 2669 std::prev(BasicBlock::const_iterator(&I)); 2670 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2671 if (Call->doesNotReturn()) 2672 return; 2673 } 2674 } 2675 } 2676 2677 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2678 } 2679 2680 void SelectionDAGBuilder::visitFSub(const User &I) { 2681 // -0.0 - X --> fneg 2682 Type *Ty = I.getType(); 2683 if (isa<Constant>(I.getOperand(0)) && 2684 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2685 SDValue Op2 = getValue(I.getOperand(1)); 2686 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2687 Op2.getValueType(), Op2)); 2688 return; 2689 } 2690 2691 visitBinary(I, ISD::FSUB); 2692 } 2693 2694 /// Checks if the given instruction performs a vector reduction, in which case 2695 /// we have the freedom to alter the elements in the result as long as the 2696 /// reduction of them stays unchanged. 2697 static bool isVectorReductionOp(const User *I) { 2698 const Instruction *Inst = dyn_cast<Instruction>(I); 2699 if (!Inst || !Inst->getType()->isVectorTy()) 2700 return false; 2701 2702 auto OpCode = Inst->getOpcode(); 2703 switch (OpCode) { 2704 case Instruction::Add: 2705 case Instruction::Mul: 2706 case Instruction::And: 2707 case Instruction::Or: 2708 case Instruction::Xor: 2709 break; 2710 case Instruction::FAdd: 2711 case Instruction::FMul: 2712 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2713 if (FPOp->getFastMathFlags().isFast()) 2714 break; 2715 LLVM_FALLTHROUGH; 2716 default: 2717 return false; 2718 } 2719 2720 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2721 // Ensure the reduction size is a power of 2. 2722 if (!isPowerOf2_32(ElemNum)) 2723 return false; 2724 2725 unsigned ElemNumToReduce = ElemNum; 2726 2727 // Do DFS search on the def-use chain from the given instruction. We only 2728 // allow four kinds of operations during the search until we reach the 2729 // instruction that extracts the first element from the vector: 2730 // 2731 // 1. The reduction operation of the same opcode as the given instruction. 2732 // 2733 // 2. PHI node. 2734 // 2735 // 3. ShuffleVector instruction together with a reduction operation that 2736 // does a partial reduction. 2737 // 2738 // 4. ExtractElement that extracts the first element from the vector, and we 2739 // stop searching the def-use chain here. 2740 // 2741 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2742 // from 1-3 to the stack to continue the DFS. The given instruction is not 2743 // a reduction operation if we meet any other instructions other than those 2744 // listed above. 2745 2746 SmallVector<const User *, 16> UsersToVisit{Inst}; 2747 SmallPtrSet<const User *, 16> Visited; 2748 bool ReduxExtracted = false; 2749 2750 while (!UsersToVisit.empty()) { 2751 auto User = UsersToVisit.back(); 2752 UsersToVisit.pop_back(); 2753 if (!Visited.insert(User).second) 2754 continue; 2755 2756 for (const auto &U : User->users()) { 2757 auto Inst = dyn_cast<Instruction>(U); 2758 if (!Inst) 2759 return false; 2760 2761 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2762 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2763 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2764 return false; 2765 UsersToVisit.push_back(U); 2766 } else if (const ShuffleVectorInst *ShufInst = 2767 dyn_cast<ShuffleVectorInst>(U)) { 2768 // Detect the following pattern: A ShuffleVector instruction together 2769 // with a reduction that do partial reduction on the first and second 2770 // ElemNumToReduce / 2 elements, and store the result in 2771 // ElemNumToReduce / 2 elements in another vector. 2772 2773 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2774 if (ResultElements < ElemNum) 2775 return false; 2776 2777 if (ElemNumToReduce == 1) 2778 return false; 2779 if (!isa<UndefValue>(U->getOperand(1))) 2780 return false; 2781 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2782 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2783 return false; 2784 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2785 if (ShufInst->getMaskValue(i) != -1) 2786 return false; 2787 2788 // There is only one user of this ShuffleVector instruction, which 2789 // must be a reduction operation. 2790 if (!U->hasOneUse()) 2791 return false; 2792 2793 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2794 if (!U2 || U2->getOpcode() != OpCode) 2795 return false; 2796 2797 // Check operands of the reduction operation. 2798 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2799 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2800 UsersToVisit.push_back(U2); 2801 ElemNumToReduce /= 2; 2802 } else 2803 return false; 2804 } else if (isa<ExtractElementInst>(U)) { 2805 // At this moment we should have reduced all elements in the vector. 2806 if (ElemNumToReduce != 1) 2807 return false; 2808 2809 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2810 if (!Val || !Val->isZero()) 2811 return false; 2812 2813 ReduxExtracted = true; 2814 } else 2815 return false; 2816 } 2817 } 2818 return ReduxExtracted; 2819 } 2820 2821 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 2822 SDNodeFlags Flags; 2823 2824 SDValue Op = getValue(I.getOperand(0)); 2825 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 2826 Op, Flags); 2827 setValue(&I, UnNodeValue); 2828 } 2829 2830 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2831 SDNodeFlags Flags; 2832 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2833 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2834 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2835 } 2836 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2837 Flags.setExact(ExactOp->isExact()); 2838 } 2839 if (isVectorReductionOp(&I)) { 2840 Flags.setVectorReduction(true); 2841 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2842 } 2843 2844 SDValue Op1 = getValue(I.getOperand(0)); 2845 SDValue Op2 = getValue(I.getOperand(1)); 2846 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2847 Op1, Op2, Flags); 2848 setValue(&I, BinNodeValue); 2849 } 2850 2851 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2852 SDValue Op1 = getValue(I.getOperand(0)); 2853 SDValue Op2 = getValue(I.getOperand(1)); 2854 2855 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2856 Op1.getValueType(), DAG.getDataLayout()); 2857 2858 // Coerce the shift amount to the right type if we can. 2859 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2860 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2861 unsigned Op2Size = Op2.getValueSizeInBits(); 2862 SDLoc DL = getCurSDLoc(); 2863 2864 // If the operand is smaller than the shift count type, promote it. 2865 if (ShiftSize > Op2Size) 2866 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2867 2868 // If the operand is larger than the shift count type but the shift 2869 // count type has enough bits to represent any shift value, truncate 2870 // it now. This is a common case and it exposes the truncate to 2871 // optimization early. 2872 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2873 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2874 // Otherwise we'll need to temporarily settle for some other convenient 2875 // type. Type legalization will make adjustments once the shiftee is split. 2876 else 2877 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2878 } 2879 2880 bool nuw = false; 2881 bool nsw = false; 2882 bool exact = false; 2883 2884 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2885 2886 if (const OverflowingBinaryOperator *OFBinOp = 2887 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2888 nuw = OFBinOp->hasNoUnsignedWrap(); 2889 nsw = OFBinOp->hasNoSignedWrap(); 2890 } 2891 if (const PossiblyExactOperator *ExactOp = 2892 dyn_cast<const PossiblyExactOperator>(&I)) 2893 exact = ExactOp->isExact(); 2894 } 2895 SDNodeFlags Flags; 2896 Flags.setExact(exact); 2897 Flags.setNoSignedWrap(nsw); 2898 Flags.setNoUnsignedWrap(nuw); 2899 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2900 Flags); 2901 setValue(&I, Res); 2902 } 2903 2904 void SelectionDAGBuilder::visitSDiv(const User &I) { 2905 SDValue Op1 = getValue(I.getOperand(0)); 2906 SDValue Op2 = getValue(I.getOperand(1)); 2907 2908 SDNodeFlags Flags; 2909 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2910 cast<PossiblyExactOperator>(&I)->isExact()); 2911 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2912 Op2, Flags)); 2913 } 2914 2915 void SelectionDAGBuilder::visitICmp(const User &I) { 2916 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2917 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2918 predicate = IC->getPredicate(); 2919 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2920 predicate = ICmpInst::Predicate(IC->getPredicate()); 2921 SDValue Op1 = getValue(I.getOperand(0)); 2922 SDValue Op2 = getValue(I.getOperand(1)); 2923 ISD::CondCode Opcode = getICmpCondCode(predicate); 2924 2925 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2926 I.getType()); 2927 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2928 } 2929 2930 void SelectionDAGBuilder::visitFCmp(const User &I) { 2931 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2932 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2933 predicate = FC->getPredicate(); 2934 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2935 predicate = FCmpInst::Predicate(FC->getPredicate()); 2936 SDValue Op1 = getValue(I.getOperand(0)); 2937 SDValue Op2 = getValue(I.getOperand(1)); 2938 2939 ISD::CondCode Condition = getFCmpCondCode(predicate); 2940 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2941 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2942 Condition = getFCmpCodeWithoutNaN(Condition); 2943 2944 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2945 I.getType()); 2946 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2947 } 2948 2949 // Check if the condition of the select has one use or two users that are both 2950 // selects with the same condition. 2951 static bool hasOnlySelectUsers(const Value *Cond) { 2952 return llvm::all_of(Cond->users(), [](const Value *V) { 2953 return isa<SelectInst>(V); 2954 }); 2955 } 2956 2957 void SelectionDAGBuilder::visitSelect(const User &I) { 2958 SmallVector<EVT, 4> ValueVTs; 2959 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2960 ValueVTs); 2961 unsigned NumValues = ValueVTs.size(); 2962 if (NumValues == 0) return; 2963 2964 SmallVector<SDValue, 4> Values(NumValues); 2965 SDValue Cond = getValue(I.getOperand(0)); 2966 SDValue LHSVal = getValue(I.getOperand(1)); 2967 SDValue RHSVal = getValue(I.getOperand(2)); 2968 auto BaseOps = {Cond}; 2969 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2970 ISD::VSELECT : ISD::SELECT; 2971 2972 // Min/max matching is only viable if all output VTs are the same. 2973 if (is_splat(ValueVTs)) { 2974 EVT VT = ValueVTs[0]; 2975 LLVMContext &Ctx = *DAG.getContext(); 2976 auto &TLI = DAG.getTargetLoweringInfo(); 2977 2978 // We care about the legality of the operation after it has been type 2979 // legalized. 2980 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2981 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2982 VT = TLI.getTypeToTransformTo(Ctx, VT); 2983 2984 // If the vselect is legal, assume we want to leave this as a vector setcc + 2985 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2986 // min/max is legal on the scalar type. 2987 bool UseScalarMinMax = VT.isVector() && 2988 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2989 2990 Value *LHS, *RHS; 2991 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2992 ISD::NodeType Opc = ISD::DELETED_NODE; 2993 switch (SPR.Flavor) { 2994 case SPF_UMAX: Opc = ISD::UMAX; break; 2995 case SPF_UMIN: Opc = ISD::UMIN; break; 2996 case SPF_SMAX: Opc = ISD::SMAX; break; 2997 case SPF_SMIN: Opc = ISD::SMIN; break; 2998 case SPF_FMINNUM: 2999 switch (SPR.NaNBehavior) { 3000 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3001 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3002 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3003 case SPNB_RETURNS_ANY: { 3004 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3005 Opc = ISD::FMINNUM; 3006 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3007 Opc = ISD::FMINIMUM; 3008 else if (UseScalarMinMax) 3009 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3010 ISD::FMINNUM : ISD::FMINIMUM; 3011 break; 3012 } 3013 } 3014 break; 3015 case SPF_FMAXNUM: 3016 switch (SPR.NaNBehavior) { 3017 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3018 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3019 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3020 case SPNB_RETURNS_ANY: 3021 3022 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3023 Opc = ISD::FMAXNUM; 3024 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3025 Opc = ISD::FMAXIMUM; 3026 else if (UseScalarMinMax) 3027 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3028 ISD::FMAXNUM : ISD::FMAXIMUM; 3029 break; 3030 } 3031 break; 3032 default: break; 3033 } 3034 3035 if (Opc != ISD::DELETED_NODE && 3036 (TLI.isOperationLegalOrCustom(Opc, VT) || 3037 (UseScalarMinMax && 3038 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3039 // If the underlying comparison instruction is used by any other 3040 // instruction, the consumed instructions won't be destroyed, so it is 3041 // not profitable to convert to a min/max. 3042 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3043 OpCode = Opc; 3044 LHSVal = getValue(LHS); 3045 RHSVal = getValue(RHS); 3046 BaseOps = {}; 3047 } 3048 } 3049 3050 for (unsigned i = 0; i != NumValues; ++i) { 3051 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3052 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3053 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3054 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3055 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3056 Ops); 3057 } 3058 3059 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3060 DAG.getVTList(ValueVTs), Values)); 3061 } 3062 3063 void SelectionDAGBuilder::visitTrunc(const User &I) { 3064 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3065 SDValue N = getValue(I.getOperand(0)); 3066 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3067 I.getType()); 3068 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3069 } 3070 3071 void SelectionDAGBuilder::visitZExt(const User &I) { 3072 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3073 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3074 SDValue N = getValue(I.getOperand(0)); 3075 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3076 I.getType()); 3077 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3078 } 3079 3080 void SelectionDAGBuilder::visitSExt(const User &I) { 3081 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3082 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3083 SDValue N = getValue(I.getOperand(0)); 3084 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3085 I.getType()); 3086 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3087 } 3088 3089 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3090 // FPTrunc is never a no-op cast, no need to check 3091 SDValue N = getValue(I.getOperand(0)); 3092 SDLoc dl = getCurSDLoc(); 3093 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3094 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3095 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3096 DAG.getTargetConstant( 3097 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3098 } 3099 3100 void SelectionDAGBuilder::visitFPExt(const User &I) { 3101 // FPExt is never a no-op cast, no need to check 3102 SDValue N = getValue(I.getOperand(0)); 3103 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3104 I.getType()); 3105 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3106 } 3107 3108 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3109 // FPToUI is never a no-op cast, no need to check 3110 SDValue N = getValue(I.getOperand(0)); 3111 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3112 I.getType()); 3113 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3114 } 3115 3116 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3117 // FPToSI is never a no-op cast, no need to check 3118 SDValue N = getValue(I.getOperand(0)); 3119 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3120 I.getType()); 3121 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3122 } 3123 3124 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3125 // UIToFP is never a no-op cast, no need to check 3126 SDValue N = getValue(I.getOperand(0)); 3127 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3128 I.getType()); 3129 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3130 } 3131 3132 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3133 // SIToFP is never a no-op cast, no need to check 3134 SDValue N = getValue(I.getOperand(0)); 3135 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3136 I.getType()); 3137 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3138 } 3139 3140 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3141 // What to do depends on the size of the integer and the size of the pointer. 3142 // We can either truncate, zero extend, or no-op, accordingly. 3143 SDValue N = getValue(I.getOperand(0)); 3144 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3145 I.getType()); 3146 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3147 } 3148 3149 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3150 // What to do depends on the size of the integer and the size of the pointer. 3151 // We can either truncate, zero extend, or no-op, accordingly. 3152 SDValue N = getValue(I.getOperand(0)); 3153 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3154 I.getType()); 3155 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3156 } 3157 3158 void SelectionDAGBuilder::visitBitCast(const User &I) { 3159 SDValue N = getValue(I.getOperand(0)); 3160 SDLoc dl = getCurSDLoc(); 3161 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3162 I.getType()); 3163 3164 // BitCast assures us that source and destination are the same size so this is 3165 // either a BITCAST or a no-op. 3166 if (DestVT != N.getValueType()) 3167 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3168 DestVT, N)); // convert types. 3169 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3170 // might fold any kind of constant expression to an integer constant and that 3171 // is not what we are looking for. Only recognize a bitcast of a genuine 3172 // constant integer as an opaque constant. 3173 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3174 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3175 /*isOpaque*/true)); 3176 else 3177 setValue(&I, N); // noop cast. 3178 } 3179 3180 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3181 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3182 const Value *SV = I.getOperand(0); 3183 SDValue N = getValue(SV); 3184 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3185 3186 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3187 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3188 3189 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3190 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3191 3192 setValue(&I, N); 3193 } 3194 3195 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3196 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3197 SDValue InVec = getValue(I.getOperand(0)); 3198 SDValue InVal = getValue(I.getOperand(1)); 3199 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3200 TLI.getVectorIdxTy(DAG.getDataLayout())); 3201 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3202 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3203 InVec, InVal, InIdx)); 3204 } 3205 3206 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3207 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3208 SDValue InVec = getValue(I.getOperand(0)); 3209 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3210 TLI.getVectorIdxTy(DAG.getDataLayout())); 3211 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3212 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3213 InVec, InIdx)); 3214 } 3215 3216 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3217 SDValue Src1 = getValue(I.getOperand(0)); 3218 SDValue Src2 = getValue(I.getOperand(1)); 3219 SDLoc DL = getCurSDLoc(); 3220 3221 SmallVector<int, 8> Mask; 3222 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3223 unsigned MaskNumElts = Mask.size(); 3224 3225 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3226 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3227 EVT SrcVT = Src1.getValueType(); 3228 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3229 3230 if (SrcNumElts == MaskNumElts) { 3231 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3232 return; 3233 } 3234 3235 // Normalize the shuffle vector since mask and vector length don't match. 3236 if (SrcNumElts < MaskNumElts) { 3237 // Mask is longer than the source vectors. We can use concatenate vector to 3238 // make the mask and vectors lengths match. 3239 3240 if (MaskNumElts % SrcNumElts == 0) { 3241 // Mask length is a multiple of the source vector length. 3242 // Check if the shuffle is some kind of concatenation of the input 3243 // vectors. 3244 unsigned NumConcat = MaskNumElts / SrcNumElts; 3245 bool IsConcat = true; 3246 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3247 for (unsigned i = 0; i != MaskNumElts; ++i) { 3248 int Idx = Mask[i]; 3249 if (Idx < 0) 3250 continue; 3251 // Ensure the indices in each SrcVT sized piece are sequential and that 3252 // the same source is used for the whole piece. 3253 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3254 (ConcatSrcs[i / SrcNumElts] >= 0 && 3255 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3256 IsConcat = false; 3257 break; 3258 } 3259 // Remember which source this index came from. 3260 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3261 } 3262 3263 // The shuffle is concatenating multiple vectors together. Just emit 3264 // a CONCAT_VECTORS operation. 3265 if (IsConcat) { 3266 SmallVector<SDValue, 8> ConcatOps; 3267 for (auto Src : ConcatSrcs) { 3268 if (Src < 0) 3269 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3270 else if (Src == 0) 3271 ConcatOps.push_back(Src1); 3272 else 3273 ConcatOps.push_back(Src2); 3274 } 3275 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3276 return; 3277 } 3278 } 3279 3280 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3281 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3282 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3283 PaddedMaskNumElts); 3284 3285 // Pad both vectors with undefs to make them the same length as the mask. 3286 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3287 3288 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3289 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3290 MOps1[0] = Src1; 3291 MOps2[0] = Src2; 3292 3293 Src1 = Src1.isUndef() 3294 ? DAG.getUNDEF(PaddedVT) 3295 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3296 Src2 = Src2.isUndef() 3297 ? DAG.getUNDEF(PaddedVT) 3298 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3299 3300 // Readjust mask for new input vector length. 3301 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3302 for (unsigned i = 0; i != MaskNumElts; ++i) { 3303 int Idx = Mask[i]; 3304 if (Idx >= (int)SrcNumElts) 3305 Idx -= SrcNumElts - PaddedMaskNumElts; 3306 MappedOps[i] = Idx; 3307 } 3308 3309 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3310 3311 // If the concatenated vector was padded, extract a subvector with the 3312 // correct number of elements. 3313 if (MaskNumElts != PaddedMaskNumElts) 3314 Result = DAG.getNode( 3315 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3316 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3317 3318 setValue(&I, Result); 3319 return; 3320 } 3321 3322 if (SrcNumElts > MaskNumElts) { 3323 // Analyze the access pattern of the vector to see if we can extract 3324 // two subvectors and do the shuffle. 3325 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3326 bool CanExtract = true; 3327 for (int Idx : Mask) { 3328 unsigned Input = 0; 3329 if (Idx < 0) 3330 continue; 3331 3332 if (Idx >= (int)SrcNumElts) { 3333 Input = 1; 3334 Idx -= SrcNumElts; 3335 } 3336 3337 // If all the indices come from the same MaskNumElts sized portion of 3338 // the sources we can use extract. Also make sure the extract wouldn't 3339 // extract past the end of the source. 3340 int NewStartIdx = alignDown(Idx, MaskNumElts); 3341 if (NewStartIdx + MaskNumElts > SrcNumElts || 3342 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3343 CanExtract = false; 3344 // Make sure we always update StartIdx as we use it to track if all 3345 // elements are undef. 3346 StartIdx[Input] = NewStartIdx; 3347 } 3348 3349 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3350 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3351 return; 3352 } 3353 if (CanExtract) { 3354 // Extract appropriate subvector and generate a vector shuffle 3355 for (unsigned Input = 0; Input < 2; ++Input) { 3356 SDValue &Src = Input == 0 ? Src1 : Src2; 3357 if (StartIdx[Input] < 0) 3358 Src = DAG.getUNDEF(VT); 3359 else { 3360 Src = DAG.getNode( 3361 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3362 DAG.getConstant(StartIdx[Input], DL, 3363 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3364 } 3365 } 3366 3367 // Calculate new mask. 3368 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3369 for (int &Idx : MappedOps) { 3370 if (Idx >= (int)SrcNumElts) 3371 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3372 else if (Idx >= 0) 3373 Idx -= StartIdx[0]; 3374 } 3375 3376 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3377 return; 3378 } 3379 } 3380 3381 // We can't use either concat vectors or extract subvectors so fall back to 3382 // replacing the shuffle with extract and build vector. 3383 // to insert and build vector. 3384 EVT EltVT = VT.getVectorElementType(); 3385 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3386 SmallVector<SDValue,8> Ops; 3387 for (int Idx : Mask) { 3388 SDValue Res; 3389 3390 if (Idx < 0) { 3391 Res = DAG.getUNDEF(EltVT); 3392 } else { 3393 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3394 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3395 3396 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3397 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3398 } 3399 3400 Ops.push_back(Res); 3401 } 3402 3403 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3404 } 3405 3406 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3407 ArrayRef<unsigned> Indices; 3408 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3409 Indices = IV->getIndices(); 3410 else 3411 Indices = cast<ConstantExpr>(&I)->getIndices(); 3412 3413 const Value *Op0 = I.getOperand(0); 3414 const Value *Op1 = I.getOperand(1); 3415 Type *AggTy = I.getType(); 3416 Type *ValTy = Op1->getType(); 3417 bool IntoUndef = isa<UndefValue>(Op0); 3418 bool FromUndef = isa<UndefValue>(Op1); 3419 3420 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3421 3422 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3423 SmallVector<EVT, 4> AggValueVTs; 3424 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3425 SmallVector<EVT, 4> ValValueVTs; 3426 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3427 3428 unsigned NumAggValues = AggValueVTs.size(); 3429 unsigned NumValValues = ValValueVTs.size(); 3430 SmallVector<SDValue, 4> Values(NumAggValues); 3431 3432 // Ignore an insertvalue that produces an empty object 3433 if (!NumAggValues) { 3434 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3435 return; 3436 } 3437 3438 SDValue Agg = getValue(Op0); 3439 unsigned i = 0; 3440 // Copy the beginning value(s) from the original aggregate. 3441 for (; i != LinearIndex; ++i) 3442 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3443 SDValue(Agg.getNode(), Agg.getResNo() + i); 3444 // Copy values from the inserted value(s). 3445 if (NumValValues) { 3446 SDValue Val = getValue(Op1); 3447 for (; i != LinearIndex + NumValValues; ++i) 3448 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3449 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3450 } 3451 // Copy remaining value(s) from the original aggregate. 3452 for (; i != NumAggValues; ++i) 3453 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3454 SDValue(Agg.getNode(), Agg.getResNo() + i); 3455 3456 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3457 DAG.getVTList(AggValueVTs), Values)); 3458 } 3459 3460 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3461 ArrayRef<unsigned> Indices; 3462 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3463 Indices = EV->getIndices(); 3464 else 3465 Indices = cast<ConstantExpr>(&I)->getIndices(); 3466 3467 const Value *Op0 = I.getOperand(0); 3468 Type *AggTy = Op0->getType(); 3469 Type *ValTy = I.getType(); 3470 bool OutOfUndef = isa<UndefValue>(Op0); 3471 3472 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3473 3474 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3475 SmallVector<EVT, 4> ValValueVTs; 3476 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3477 3478 unsigned NumValValues = ValValueVTs.size(); 3479 3480 // Ignore a extractvalue that produces an empty object 3481 if (!NumValValues) { 3482 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3483 return; 3484 } 3485 3486 SmallVector<SDValue, 4> Values(NumValValues); 3487 3488 SDValue Agg = getValue(Op0); 3489 // Copy out the selected value(s). 3490 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3491 Values[i - LinearIndex] = 3492 OutOfUndef ? 3493 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3494 SDValue(Agg.getNode(), Agg.getResNo() + i); 3495 3496 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3497 DAG.getVTList(ValValueVTs), Values)); 3498 } 3499 3500 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3501 Value *Op0 = I.getOperand(0); 3502 // Note that the pointer operand may be a vector of pointers. Take the scalar 3503 // element which holds a pointer. 3504 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3505 SDValue N = getValue(Op0); 3506 SDLoc dl = getCurSDLoc(); 3507 3508 // Normalize Vector GEP - all scalar operands should be converted to the 3509 // splat vector. 3510 unsigned VectorWidth = I.getType()->isVectorTy() ? 3511 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3512 3513 if (VectorWidth && !N.getValueType().isVector()) { 3514 LLVMContext &Context = *DAG.getContext(); 3515 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3516 N = DAG.getSplatBuildVector(VT, dl, N); 3517 } 3518 3519 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3520 GTI != E; ++GTI) { 3521 const Value *Idx = GTI.getOperand(); 3522 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3523 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3524 if (Field) { 3525 // N = N + Offset 3526 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3527 3528 // In an inbounds GEP with an offset that is nonnegative even when 3529 // interpreted as signed, assume there is no unsigned overflow. 3530 SDNodeFlags Flags; 3531 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3532 Flags.setNoUnsignedWrap(true); 3533 3534 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3535 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3536 } 3537 } else { 3538 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3539 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3540 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3541 3542 // If this is a scalar constant or a splat vector of constants, 3543 // handle it quickly. 3544 const auto *CI = dyn_cast<ConstantInt>(Idx); 3545 if (!CI && isa<ConstantDataVector>(Idx) && 3546 cast<ConstantDataVector>(Idx)->getSplatValue()) 3547 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3548 3549 if (CI) { 3550 if (CI->isZero()) 3551 continue; 3552 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3553 LLVMContext &Context = *DAG.getContext(); 3554 SDValue OffsVal = VectorWidth ? 3555 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3556 DAG.getConstant(Offs, dl, IdxTy); 3557 3558 // In an inbouds GEP with an offset that is nonnegative even when 3559 // interpreted as signed, assume there is no unsigned overflow. 3560 SDNodeFlags Flags; 3561 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3562 Flags.setNoUnsignedWrap(true); 3563 3564 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3565 continue; 3566 } 3567 3568 // N = N + Idx * ElementSize; 3569 SDValue IdxN = getValue(Idx); 3570 3571 if (!IdxN.getValueType().isVector() && VectorWidth) { 3572 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3573 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3574 } 3575 3576 // If the index is smaller or larger than intptr_t, truncate or extend 3577 // it. 3578 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3579 3580 // If this is a multiply by a power of two, turn it into a shl 3581 // immediately. This is a very common case. 3582 if (ElementSize != 1) { 3583 if (ElementSize.isPowerOf2()) { 3584 unsigned Amt = ElementSize.logBase2(); 3585 IdxN = DAG.getNode(ISD::SHL, dl, 3586 N.getValueType(), IdxN, 3587 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3588 } else { 3589 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3590 IdxN = DAG.getNode(ISD::MUL, dl, 3591 N.getValueType(), IdxN, Scale); 3592 } 3593 } 3594 3595 N = DAG.getNode(ISD::ADD, dl, 3596 N.getValueType(), N, IdxN); 3597 } 3598 } 3599 3600 setValue(&I, N); 3601 } 3602 3603 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3604 // If this is a fixed sized alloca in the entry block of the function, 3605 // allocate it statically on the stack. 3606 if (FuncInfo.StaticAllocaMap.count(&I)) 3607 return; // getValue will auto-populate this. 3608 3609 SDLoc dl = getCurSDLoc(); 3610 Type *Ty = I.getAllocatedType(); 3611 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3612 auto &DL = DAG.getDataLayout(); 3613 uint64_t TySize = DL.getTypeAllocSize(Ty); 3614 unsigned Align = 3615 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3616 3617 SDValue AllocSize = getValue(I.getArraySize()); 3618 3619 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3620 if (AllocSize.getValueType() != IntPtr) 3621 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3622 3623 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3624 AllocSize, 3625 DAG.getConstant(TySize, dl, IntPtr)); 3626 3627 // Handle alignment. If the requested alignment is less than or equal to 3628 // the stack alignment, ignore it. If the size is greater than or equal to 3629 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3630 unsigned StackAlign = 3631 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3632 if (Align <= StackAlign) 3633 Align = 0; 3634 3635 // Round the size of the allocation up to the stack alignment size 3636 // by add SA-1 to the size. This doesn't overflow because we're computing 3637 // an address inside an alloca. 3638 SDNodeFlags Flags; 3639 Flags.setNoUnsignedWrap(true); 3640 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3641 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3642 3643 // Mask out the low bits for alignment purposes. 3644 AllocSize = 3645 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3646 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3647 3648 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3649 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3650 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3651 setValue(&I, DSA); 3652 DAG.setRoot(DSA.getValue(1)); 3653 3654 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3655 } 3656 3657 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3658 if (I.isAtomic()) 3659 return visitAtomicLoad(I); 3660 3661 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3662 const Value *SV = I.getOperand(0); 3663 if (TLI.supportSwiftError()) { 3664 // Swifterror values can come from either a function parameter with 3665 // swifterror attribute or an alloca with swifterror attribute. 3666 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3667 if (Arg->hasSwiftErrorAttr()) 3668 return visitLoadFromSwiftError(I); 3669 } 3670 3671 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3672 if (Alloca->isSwiftError()) 3673 return visitLoadFromSwiftError(I); 3674 } 3675 } 3676 3677 SDValue Ptr = getValue(SV); 3678 3679 Type *Ty = I.getType(); 3680 3681 bool isVolatile = I.isVolatile(); 3682 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3683 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3684 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3685 unsigned Alignment = I.getAlignment(); 3686 3687 AAMDNodes AAInfo; 3688 I.getAAMetadata(AAInfo); 3689 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3690 3691 SmallVector<EVT, 4> ValueVTs; 3692 SmallVector<uint64_t, 4> Offsets; 3693 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3694 unsigned NumValues = ValueVTs.size(); 3695 if (NumValues == 0) 3696 return; 3697 3698 SDValue Root; 3699 bool ConstantMemory = false; 3700 if (isVolatile || NumValues > MaxParallelChains) 3701 // Serialize volatile loads with other side effects. 3702 Root = getRoot(); 3703 else if (AA && 3704 AA->pointsToConstantMemory(MemoryLocation( 3705 SV, 3706 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3707 AAInfo))) { 3708 // Do not serialize (non-volatile) loads of constant memory with anything. 3709 Root = DAG.getEntryNode(); 3710 ConstantMemory = true; 3711 } else { 3712 // Do not serialize non-volatile loads against each other. 3713 Root = DAG.getRoot(); 3714 } 3715 3716 SDLoc dl = getCurSDLoc(); 3717 3718 if (isVolatile) 3719 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3720 3721 // An aggregate load cannot wrap around the address space, so offsets to its 3722 // parts don't wrap either. 3723 SDNodeFlags Flags; 3724 Flags.setNoUnsignedWrap(true); 3725 3726 SmallVector<SDValue, 4> Values(NumValues); 3727 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3728 EVT PtrVT = Ptr.getValueType(); 3729 unsigned ChainI = 0; 3730 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3731 // Serializing loads here may result in excessive register pressure, and 3732 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3733 // could recover a bit by hoisting nodes upward in the chain by recognizing 3734 // they are side-effect free or do not alias. The optimizer should really 3735 // avoid this case by converting large object/array copies to llvm.memcpy 3736 // (MaxParallelChains should always remain as failsafe). 3737 if (ChainI == MaxParallelChains) { 3738 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3739 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3740 makeArrayRef(Chains.data(), ChainI)); 3741 Root = Chain; 3742 ChainI = 0; 3743 } 3744 SDValue A = DAG.getNode(ISD::ADD, dl, 3745 PtrVT, Ptr, 3746 DAG.getConstant(Offsets[i], dl, PtrVT), 3747 Flags); 3748 auto MMOFlags = MachineMemOperand::MONone; 3749 if (isVolatile) 3750 MMOFlags |= MachineMemOperand::MOVolatile; 3751 if (isNonTemporal) 3752 MMOFlags |= MachineMemOperand::MONonTemporal; 3753 if (isInvariant) 3754 MMOFlags |= MachineMemOperand::MOInvariant; 3755 if (isDereferenceable) 3756 MMOFlags |= MachineMemOperand::MODereferenceable; 3757 MMOFlags |= TLI.getMMOFlags(I); 3758 3759 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3760 MachinePointerInfo(SV, Offsets[i]), Alignment, 3761 MMOFlags, AAInfo, Ranges); 3762 3763 Values[i] = L; 3764 Chains[ChainI] = L.getValue(1); 3765 } 3766 3767 if (!ConstantMemory) { 3768 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3769 makeArrayRef(Chains.data(), ChainI)); 3770 if (isVolatile) 3771 DAG.setRoot(Chain); 3772 else 3773 PendingLoads.push_back(Chain); 3774 } 3775 3776 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3777 DAG.getVTList(ValueVTs), Values)); 3778 } 3779 3780 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3781 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3782 "call visitStoreToSwiftError when backend supports swifterror"); 3783 3784 SmallVector<EVT, 4> ValueVTs; 3785 SmallVector<uint64_t, 4> Offsets; 3786 const Value *SrcV = I.getOperand(0); 3787 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3788 SrcV->getType(), ValueVTs, &Offsets); 3789 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3790 "expect a single EVT for swifterror"); 3791 3792 SDValue Src = getValue(SrcV); 3793 // Create a virtual register, then update the virtual register. 3794 unsigned VReg; bool CreatedVReg; 3795 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3796 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3797 // Chain can be getRoot or getControlRoot. 3798 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3799 SDValue(Src.getNode(), Src.getResNo())); 3800 DAG.setRoot(CopyNode); 3801 if (CreatedVReg) 3802 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3803 } 3804 3805 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3806 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3807 "call visitLoadFromSwiftError when backend supports swifterror"); 3808 3809 assert(!I.isVolatile() && 3810 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3811 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3812 "Support volatile, non temporal, invariant for load_from_swift_error"); 3813 3814 const Value *SV = I.getOperand(0); 3815 Type *Ty = I.getType(); 3816 AAMDNodes AAInfo; 3817 I.getAAMetadata(AAInfo); 3818 assert( 3819 (!AA || 3820 !AA->pointsToConstantMemory(MemoryLocation( 3821 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3822 AAInfo))) && 3823 "load_from_swift_error should not be constant memory"); 3824 3825 SmallVector<EVT, 4> ValueVTs; 3826 SmallVector<uint64_t, 4> Offsets; 3827 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3828 ValueVTs, &Offsets); 3829 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3830 "expect a single EVT for swifterror"); 3831 3832 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3833 SDValue L = DAG.getCopyFromReg( 3834 getRoot(), getCurSDLoc(), 3835 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3836 ValueVTs[0]); 3837 3838 setValue(&I, L); 3839 } 3840 3841 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3842 if (I.isAtomic()) 3843 return visitAtomicStore(I); 3844 3845 const Value *SrcV = I.getOperand(0); 3846 const Value *PtrV = I.getOperand(1); 3847 3848 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3849 if (TLI.supportSwiftError()) { 3850 // Swifterror values can come from either a function parameter with 3851 // swifterror attribute or an alloca with swifterror attribute. 3852 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3853 if (Arg->hasSwiftErrorAttr()) 3854 return visitStoreToSwiftError(I); 3855 } 3856 3857 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3858 if (Alloca->isSwiftError()) 3859 return visitStoreToSwiftError(I); 3860 } 3861 } 3862 3863 SmallVector<EVT, 4> ValueVTs; 3864 SmallVector<uint64_t, 4> Offsets; 3865 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3866 SrcV->getType(), ValueVTs, &Offsets); 3867 unsigned NumValues = ValueVTs.size(); 3868 if (NumValues == 0) 3869 return; 3870 3871 // Get the lowered operands. Note that we do this after 3872 // checking if NumResults is zero, because with zero results 3873 // the operands won't have values in the map. 3874 SDValue Src = getValue(SrcV); 3875 SDValue Ptr = getValue(PtrV); 3876 3877 SDValue Root = getRoot(); 3878 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3879 SDLoc dl = getCurSDLoc(); 3880 EVT PtrVT = Ptr.getValueType(); 3881 unsigned Alignment = I.getAlignment(); 3882 AAMDNodes AAInfo; 3883 I.getAAMetadata(AAInfo); 3884 3885 auto MMOFlags = MachineMemOperand::MONone; 3886 if (I.isVolatile()) 3887 MMOFlags |= MachineMemOperand::MOVolatile; 3888 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3889 MMOFlags |= MachineMemOperand::MONonTemporal; 3890 MMOFlags |= TLI.getMMOFlags(I); 3891 3892 // An aggregate load cannot wrap around the address space, so offsets to its 3893 // parts don't wrap either. 3894 SDNodeFlags Flags; 3895 Flags.setNoUnsignedWrap(true); 3896 3897 unsigned ChainI = 0; 3898 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3899 // See visitLoad comments. 3900 if (ChainI == MaxParallelChains) { 3901 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3902 makeArrayRef(Chains.data(), ChainI)); 3903 Root = Chain; 3904 ChainI = 0; 3905 } 3906 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3907 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3908 SDValue St = DAG.getStore( 3909 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3910 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3911 Chains[ChainI] = St; 3912 } 3913 3914 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3915 makeArrayRef(Chains.data(), ChainI)); 3916 DAG.setRoot(StoreNode); 3917 } 3918 3919 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3920 bool IsCompressing) { 3921 SDLoc sdl = getCurSDLoc(); 3922 3923 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3924 unsigned& Alignment) { 3925 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3926 Src0 = I.getArgOperand(0); 3927 Ptr = I.getArgOperand(1); 3928 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3929 Mask = I.getArgOperand(3); 3930 }; 3931 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3932 unsigned& Alignment) { 3933 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3934 Src0 = I.getArgOperand(0); 3935 Ptr = I.getArgOperand(1); 3936 Mask = I.getArgOperand(2); 3937 Alignment = 0; 3938 }; 3939 3940 Value *PtrOperand, *MaskOperand, *Src0Operand; 3941 unsigned Alignment; 3942 if (IsCompressing) 3943 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3944 else 3945 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3946 3947 SDValue Ptr = getValue(PtrOperand); 3948 SDValue Src0 = getValue(Src0Operand); 3949 SDValue Mask = getValue(MaskOperand); 3950 3951 EVT VT = Src0.getValueType(); 3952 if (!Alignment) 3953 Alignment = DAG.getEVTAlignment(VT); 3954 3955 AAMDNodes AAInfo; 3956 I.getAAMetadata(AAInfo); 3957 3958 MachineMemOperand *MMO = 3959 DAG.getMachineFunction(). 3960 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3961 MachineMemOperand::MOStore, VT.getStoreSize(), 3962 Alignment, AAInfo); 3963 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3964 MMO, false /* Truncating */, 3965 IsCompressing); 3966 DAG.setRoot(StoreNode); 3967 setValue(&I, StoreNode); 3968 } 3969 3970 // Get a uniform base for the Gather/Scatter intrinsic. 3971 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3972 // We try to represent it as a base pointer + vector of indices. 3973 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3974 // The first operand of the GEP may be a single pointer or a vector of pointers 3975 // Example: 3976 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3977 // or 3978 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3979 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3980 // 3981 // When the first GEP operand is a single pointer - it is the uniform base we 3982 // are looking for. If first operand of the GEP is a splat vector - we 3983 // extract the splat value and use it as a uniform base. 3984 // In all other cases the function returns 'false'. 3985 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3986 SDValue &Scale, SelectionDAGBuilder* SDB) { 3987 SelectionDAG& DAG = SDB->DAG; 3988 LLVMContext &Context = *DAG.getContext(); 3989 3990 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3991 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3992 if (!GEP) 3993 return false; 3994 3995 const Value *GEPPtr = GEP->getPointerOperand(); 3996 if (!GEPPtr->getType()->isVectorTy()) 3997 Ptr = GEPPtr; 3998 else if (!(Ptr = getSplatValue(GEPPtr))) 3999 return false; 4000 4001 unsigned FinalIndex = GEP->getNumOperands() - 1; 4002 Value *IndexVal = GEP->getOperand(FinalIndex); 4003 4004 // Ensure all the other indices are 0. 4005 for (unsigned i = 1; i < FinalIndex; ++i) { 4006 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 4007 if (!C || !C->isZero()) 4008 return false; 4009 } 4010 4011 // The operands of the GEP may be defined in another basic block. 4012 // In this case we'll not find nodes for the operands. 4013 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4014 return false; 4015 4016 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4017 const DataLayout &DL = DAG.getDataLayout(); 4018 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4019 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4020 Base = SDB->getValue(Ptr); 4021 Index = SDB->getValue(IndexVal); 4022 4023 if (!Index.getValueType().isVector()) { 4024 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4025 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4026 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4027 } 4028 return true; 4029 } 4030 4031 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4032 SDLoc sdl = getCurSDLoc(); 4033 4034 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4035 const Value *Ptr = I.getArgOperand(1); 4036 SDValue Src0 = getValue(I.getArgOperand(0)); 4037 SDValue Mask = getValue(I.getArgOperand(3)); 4038 EVT VT = Src0.getValueType(); 4039 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4040 if (!Alignment) 4041 Alignment = DAG.getEVTAlignment(VT); 4042 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4043 4044 AAMDNodes AAInfo; 4045 I.getAAMetadata(AAInfo); 4046 4047 SDValue Base; 4048 SDValue Index; 4049 SDValue Scale; 4050 const Value *BasePtr = Ptr; 4051 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4052 4053 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4054 MachineMemOperand *MMO = DAG.getMachineFunction(). 4055 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4056 MachineMemOperand::MOStore, VT.getStoreSize(), 4057 Alignment, AAInfo); 4058 if (!UniformBase) { 4059 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4060 Index = getValue(Ptr); 4061 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4062 } 4063 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4064 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4065 Ops, MMO); 4066 DAG.setRoot(Scatter); 4067 setValue(&I, Scatter); 4068 } 4069 4070 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4071 SDLoc sdl = getCurSDLoc(); 4072 4073 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4074 unsigned& Alignment) { 4075 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4076 Ptr = I.getArgOperand(0); 4077 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4078 Mask = I.getArgOperand(2); 4079 Src0 = I.getArgOperand(3); 4080 }; 4081 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4082 unsigned& Alignment) { 4083 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4084 Ptr = I.getArgOperand(0); 4085 Alignment = 0; 4086 Mask = I.getArgOperand(1); 4087 Src0 = I.getArgOperand(2); 4088 }; 4089 4090 Value *PtrOperand, *MaskOperand, *Src0Operand; 4091 unsigned Alignment; 4092 if (IsExpanding) 4093 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4094 else 4095 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4096 4097 SDValue Ptr = getValue(PtrOperand); 4098 SDValue Src0 = getValue(Src0Operand); 4099 SDValue Mask = getValue(MaskOperand); 4100 4101 EVT VT = Src0.getValueType(); 4102 if (!Alignment) 4103 Alignment = DAG.getEVTAlignment(VT); 4104 4105 AAMDNodes AAInfo; 4106 I.getAAMetadata(AAInfo); 4107 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4108 4109 // Do not serialize masked loads of constant memory with anything. 4110 bool AddToChain = 4111 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4112 PtrOperand, 4113 LocationSize::precise( 4114 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4115 AAInfo)); 4116 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4117 4118 MachineMemOperand *MMO = 4119 DAG.getMachineFunction(). 4120 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4121 MachineMemOperand::MOLoad, VT.getStoreSize(), 4122 Alignment, AAInfo, Ranges); 4123 4124 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4125 ISD::NON_EXTLOAD, IsExpanding); 4126 if (AddToChain) 4127 PendingLoads.push_back(Load.getValue(1)); 4128 setValue(&I, Load); 4129 } 4130 4131 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4132 SDLoc sdl = getCurSDLoc(); 4133 4134 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4135 const Value *Ptr = I.getArgOperand(0); 4136 SDValue Src0 = getValue(I.getArgOperand(3)); 4137 SDValue Mask = getValue(I.getArgOperand(2)); 4138 4139 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4140 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4141 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4142 if (!Alignment) 4143 Alignment = DAG.getEVTAlignment(VT); 4144 4145 AAMDNodes AAInfo; 4146 I.getAAMetadata(AAInfo); 4147 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4148 4149 SDValue Root = DAG.getRoot(); 4150 SDValue Base; 4151 SDValue Index; 4152 SDValue Scale; 4153 const Value *BasePtr = Ptr; 4154 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4155 bool ConstantMemory = false; 4156 if (UniformBase && AA && 4157 AA->pointsToConstantMemory( 4158 MemoryLocation(BasePtr, 4159 LocationSize::precise( 4160 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4161 AAInfo))) { 4162 // Do not serialize (non-volatile) loads of constant memory with anything. 4163 Root = DAG.getEntryNode(); 4164 ConstantMemory = true; 4165 } 4166 4167 MachineMemOperand *MMO = 4168 DAG.getMachineFunction(). 4169 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4170 MachineMemOperand::MOLoad, VT.getStoreSize(), 4171 Alignment, AAInfo, Ranges); 4172 4173 if (!UniformBase) { 4174 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4175 Index = getValue(Ptr); 4176 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4177 } 4178 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4179 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4180 Ops, MMO); 4181 4182 SDValue OutChain = Gather.getValue(1); 4183 if (!ConstantMemory) 4184 PendingLoads.push_back(OutChain); 4185 setValue(&I, Gather); 4186 } 4187 4188 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4189 SDLoc dl = getCurSDLoc(); 4190 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4191 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4192 SyncScope::ID SSID = I.getSyncScopeID(); 4193 4194 SDValue InChain = getRoot(); 4195 4196 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4197 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4198 SDValue L = DAG.getAtomicCmpSwap( 4199 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4200 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4201 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4202 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4203 4204 SDValue OutChain = L.getValue(2); 4205 4206 setValue(&I, L); 4207 DAG.setRoot(OutChain); 4208 } 4209 4210 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4211 SDLoc dl = getCurSDLoc(); 4212 ISD::NodeType NT; 4213 switch (I.getOperation()) { 4214 default: llvm_unreachable("Unknown atomicrmw operation"); 4215 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4216 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4217 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4218 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4219 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4220 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4221 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4222 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4223 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4224 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4225 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4226 } 4227 AtomicOrdering Order = I.getOrdering(); 4228 SyncScope::ID SSID = I.getSyncScopeID(); 4229 4230 SDValue InChain = getRoot(); 4231 4232 SDValue L = 4233 DAG.getAtomic(NT, dl, 4234 getValue(I.getValOperand()).getSimpleValueType(), 4235 InChain, 4236 getValue(I.getPointerOperand()), 4237 getValue(I.getValOperand()), 4238 I.getPointerOperand(), 4239 /* Alignment=*/ 0, Order, SSID); 4240 4241 SDValue OutChain = L.getValue(1); 4242 4243 setValue(&I, L); 4244 DAG.setRoot(OutChain); 4245 } 4246 4247 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4248 SDLoc dl = getCurSDLoc(); 4249 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4250 SDValue Ops[3]; 4251 Ops[0] = getRoot(); 4252 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4253 TLI.getFenceOperandTy(DAG.getDataLayout())); 4254 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4255 TLI.getFenceOperandTy(DAG.getDataLayout())); 4256 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4257 } 4258 4259 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4260 SDLoc dl = getCurSDLoc(); 4261 AtomicOrdering Order = I.getOrdering(); 4262 SyncScope::ID SSID = I.getSyncScopeID(); 4263 4264 SDValue InChain = getRoot(); 4265 4266 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4267 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4268 4269 if (!TLI.supportsUnalignedAtomics() && 4270 I.getAlignment() < VT.getStoreSize()) 4271 report_fatal_error("Cannot generate unaligned atomic load"); 4272 4273 MachineMemOperand *MMO = 4274 DAG.getMachineFunction(). 4275 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4276 MachineMemOperand::MOVolatile | 4277 MachineMemOperand::MOLoad, 4278 VT.getStoreSize(), 4279 I.getAlignment() ? I.getAlignment() : 4280 DAG.getEVTAlignment(VT), 4281 AAMDNodes(), nullptr, SSID, Order); 4282 4283 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4284 SDValue L = 4285 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4286 getValue(I.getPointerOperand()), MMO); 4287 4288 SDValue OutChain = L.getValue(1); 4289 4290 setValue(&I, L); 4291 DAG.setRoot(OutChain); 4292 } 4293 4294 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4295 SDLoc dl = getCurSDLoc(); 4296 4297 AtomicOrdering Order = I.getOrdering(); 4298 SyncScope::ID SSID = I.getSyncScopeID(); 4299 4300 SDValue InChain = getRoot(); 4301 4302 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4303 EVT VT = 4304 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4305 4306 if (I.getAlignment() < VT.getStoreSize()) 4307 report_fatal_error("Cannot generate unaligned atomic store"); 4308 4309 SDValue OutChain = 4310 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4311 InChain, 4312 getValue(I.getPointerOperand()), 4313 getValue(I.getValueOperand()), 4314 I.getPointerOperand(), I.getAlignment(), 4315 Order, SSID); 4316 4317 DAG.setRoot(OutChain); 4318 } 4319 4320 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4321 /// node. 4322 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4323 unsigned Intrinsic) { 4324 // Ignore the callsite's attributes. A specific call site may be marked with 4325 // readnone, but the lowering code will expect the chain based on the 4326 // definition. 4327 const Function *F = I.getCalledFunction(); 4328 bool HasChain = !F->doesNotAccessMemory(); 4329 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4330 4331 // Build the operand list. 4332 SmallVector<SDValue, 8> Ops; 4333 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4334 if (OnlyLoad) { 4335 // We don't need to serialize loads against other loads. 4336 Ops.push_back(DAG.getRoot()); 4337 } else { 4338 Ops.push_back(getRoot()); 4339 } 4340 } 4341 4342 // Info is set by getTgtMemInstrinsic 4343 TargetLowering::IntrinsicInfo Info; 4344 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4345 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4346 DAG.getMachineFunction(), 4347 Intrinsic); 4348 4349 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4350 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4351 Info.opc == ISD::INTRINSIC_W_CHAIN) 4352 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4353 TLI.getPointerTy(DAG.getDataLayout()))); 4354 4355 // Add all operands of the call to the operand list. 4356 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4357 SDValue Op = getValue(I.getArgOperand(i)); 4358 Ops.push_back(Op); 4359 } 4360 4361 SmallVector<EVT, 4> ValueVTs; 4362 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4363 4364 if (HasChain) 4365 ValueVTs.push_back(MVT::Other); 4366 4367 SDVTList VTs = DAG.getVTList(ValueVTs); 4368 4369 // Create the node. 4370 SDValue Result; 4371 if (IsTgtIntrinsic) { 4372 // This is target intrinsic that touches memory 4373 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4374 Ops, Info.memVT, 4375 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4376 Info.flags, Info.size); 4377 } else if (!HasChain) { 4378 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4379 } else if (!I.getType()->isVoidTy()) { 4380 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4381 } else { 4382 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4383 } 4384 4385 if (HasChain) { 4386 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4387 if (OnlyLoad) 4388 PendingLoads.push_back(Chain); 4389 else 4390 DAG.setRoot(Chain); 4391 } 4392 4393 if (!I.getType()->isVoidTy()) { 4394 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4395 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4396 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4397 } else 4398 Result = lowerRangeToAssertZExt(DAG, I, Result); 4399 4400 setValue(&I, Result); 4401 } 4402 } 4403 4404 /// GetSignificand - Get the significand and build it into a floating-point 4405 /// number with exponent of 1: 4406 /// 4407 /// Op = (Op & 0x007fffff) | 0x3f800000; 4408 /// 4409 /// where Op is the hexadecimal representation of floating point value. 4410 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4411 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4412 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4413 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4414 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4415 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4416 } 4417 4418 /// GetExponent - Get the exponent: 4419 /// 4420 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4421 /// 4422 /// where Op is the hexadecimal representation of floating point value. 4423 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4424 const TargetLowering &TLI, const SDLoc &dl) { 4425 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4426 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4427 SDValue t1 = DAG.getNode( 4428 ISD::SRL, dl, MVT::i32, t0, 4429 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4430 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4431 DAG.getConstant(127, dl, MVT::i32)); 4432 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4433 } 4434 4435 /// getF32Constant - Get 32-bit floating point constant. 4436 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4437 const SDLoc &dl) { 4438 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4439 MVT::f32); 4440 } 4441 4442 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4443 SelectionDAG &DAG) { 4444 // TODO: What fast-math-flags should be set on the floating-point nodes? 4445 4446 // IntegerPartOfX = ((int32_t)(t0); 4447 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4448 4449 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4450 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4451 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4452 4453 // IntegerPartOfX <<= 23; 4454 IntegerPartOfX = DAG.getNode( 4455 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4456 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4457 DAG.getDataLayout()))); 4458 4459 SDValue TwoToFractionalPartOfX; 4460 if (LimitFloatPrecision <= 6) { 4461 // For floating-point precision of 6: 4462 // 4463 // TwoToFractionalPartOfX = 4464 // 0.997535578f + 4465 // (0.735607626f + 0.252464424f * x) * x; 4466 // 4467 // error 0.0144103317, which is 6 bits 4468 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4469 getF32Constant(DAG, 0x3e814304, dl)); 4470 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4471 getF32Constant(DAG, 0x3f3c50c8, dl)); 4472 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4473 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4474 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4475 } else if (LimitFloatPrecision <= 12) { 4476 // For floating-point precision of 12: 4477 // 4478 // TwoToFractionalPartOfX = 4479 // 0.999892986f + 4480 // (0.696457318f + 4481 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4482 // 4483 // error 0.000107046256, which is 13 to 14 bits 4484 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4485 getF32Constant(DAG, 0x3da235e3, dl)); 4486 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4487 getF32Constant(DAG, 0x3e65b8f3, dl)); 4488 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4489 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4490 getF32Constant(DAG, 0x3f324b07, dl)); 4491 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4492 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4493 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4494 } else { // LimitFloatPrecision <= 18 4495 // For floating-point precision of 18: 4496 // 4497 // TwoToFractionalPartOfX = 4498 // 0.999999982f + 4499 // (0.693148872f + 4500 // (0.240227044f + 4501 // (0.554906021e-1f + 4502 // (0.961591928e-2f + 4503 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4504 // error 2.47208000*10^(-7), which is better than 18 bits 4505 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4506 getF32Constant(DAG, 0x3924b03e, dl)); 4507 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4508 getF32Constant(DAG, 0x3ab24b87, dl)); 4509 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4510 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4511 getF32Constant(DAG, 0x3c1d8c17, dl)); 4512 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4513 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4514 getF32Constant(DAG, 0x3d634a1d, dl)); 4515 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4516 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4517 getF32Constant(DAG, 0x3e75fe14, dl)); 4518 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4519 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4520 getF32Constant(DAG, 0x3f317234, dl)); 4521 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4522 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4523 getF32Constant(DAG, 0x3f800000, dl)); 4524 } 4525 4526 // Add the exponent into the result in integer domain. 4527 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4528 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4529 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4530 } 4531 4532 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4533 /// limited-precision mode. 4534 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4535 const TargetLowering &TLI) { 4536 if (Op.getValueType() == MVT::f32 && 4537 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4538 4539 // Put the exponent in the right bit position for later addition to the 4540 // final result: 4541 // 4542 // #define LOG2OFe 1.4426950f 4543 // t0 = Op * LOG2OFe 4544 4545 // TODO: What fast-math-flags should be set here? 4546 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4547 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4548 return getLimitedPrecisionExp2(t0, dl, DAG); 4549 } 4550 4551 // No special expansion. 4552 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4553 } 4554 4555 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4556 /// limited-precision mode. 4557 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4558 const TargetLowering &TLI) { 4559 // TODO: What fast-math-flags should be set on the floating-point nodes? 4560 4561 if (Op.getValueType() == MVT::f32 && 4562 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4563 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4564 4565 // Scale the exponent by log(2) [0.69314718f]. 4566 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4567 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4568 getF32Constant(DAG, 0x3f317218, dl)); 4569 4570 // Get the significand and build it into a floating-point number with 4571 // exponent of 1. 4572 SDValue X = GetSignificand(DAG, Op1, dl); 4573 4574 SDValue LogOfMantissa; 4575 if (LimitFloatPrecision <= 6) { 4576 // For floating-point precision of 6: 4577 // 4578 // LogofMantissa = 4579 // -1.1609546f + 4580 // (1.4034025f - 0.23903021f * x) * x; 4581 // 4582 // error 0.0034276066, which is better than 8 bits 4583 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4584 getF32Constant(DAG, 0xbe74c456, dl)); 4585 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4586 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4587 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4588 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4589 getF32Constant(DAG, 0x3f949a29, dl)); 4590 } else if (LimitFloatPrecision <= 12) { 4591 // For floating-point precision of 12: 4592 // 4593 // LogOfMantissa = 4594 // -1.7417939f + 4595 // (2.8212026f + 4596 // (-1.4699568f + 4597 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4598 // 4599 // error 0.000061011436, which is 14 bits 4600 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4601 getF32Constant(DAG, 0xbd67b6d6, dl)); 4602 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4603 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4604 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4605 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4606 getF32Constant(DAG, 0x3fbc278b, dl)); 4607 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4608 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4609 getF32Constant(DAG, 0x40348e95, dl)); 4610 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4611 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4612 getF32Constant(DAG, 0x3fdef31a, dl)); 4613 } else { // LimitFloatPrecision <= 18 4614 // For floating-point precision of 18: 4615 // 4616 // LogOfMantissa = 4617 // -2.1072184f + 4618 // (4.2372794f + 4619 // (-3.7029485f + 4620 // (2.2781945f + 4621 // (-0.87823314f + 4622 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4623 // 4624 // error 0.0000023660568, which is better than 18 bits 4625 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4626 getF32Constant(DAG, 0xbc91e5ac, dl)); 4627 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4628 getF32Constant(DAG, 0x3e4350aa, dl)); 4629 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4630 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4631 getF32Constant(DAG, 0x3f60d3e3, dl)); 4632 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4633 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4634 getF32Constant(DAG, 0x4011cdf0, dl)); 4635 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4636 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4637 getF32Constant(DAG, 0x406cfd1c, dl)); 4638 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4639 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4640 getF32Constant(DAG, 0x408797cb, dl)); 4641 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4642 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4643 getF32Constant(DAG, 0x4006dcab, dl)); 4644 } 4645 4646 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4647 } 4648 4649 // No special expansion. 4650 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4651 } 4652 4653 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4654 /// limited-precision mode. 4655 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4656 const TargetLowering &TLI) { 4657 // TODO: What fast-math-flags should be set on the floating-point nodes? 4658 4659 if (Op.getValueType() == MVT::f32 && 4660 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4661 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4662 4663 // Get the exponent. 4664 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4665 4666 // Get the significand and build it into a floating-point number with 4667 // exponent of 1. 4668 SDValue X = GetSignificand(DAG, Op1, dl); 4669 4670 // Different possible minimax approximations of significand in 4671 // floating-point for various degrees of accuracy over [1,2]. 4672 SDValue Log2ofMantissa; 4673 if (LimitFloatPrecision <= 6) { 4674 // For floating-point precision of 6: 4675 // 4676 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4677 // 4678 // error 0.0049451742, which is more than 7 bits 4679 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4680 getF32Constant(DAG, 0xbeb08fe0, dl)); 4681 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4682 getF32Constant(DAG, 0x40019463, dl)); 4683 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4684 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4685 getF32Constant(DAG, 0x3fd6633d, dl)); 4686 } else if (LimitFloatPrecision <= 12) { 4687 // For floating-point precision of 12: 4688 // 4689 // Log2ofMantissa = 4690 // -2.51285454f + 4691 // (4.07009056f + 4692 // (-2.12067489f + 4693 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4694 // 4695 // error 0.0000876136000, which is better than 13 bits 4696 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4697 getF32Constant(DAG, 0xbda7262e, dl)); 4698 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4699 getF32Constant(DAG, 0x3f25280b, dl)); 4700 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4701 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4702 getF32Constant(DAG, 0x4007b923, dl)); 4703 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4704 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4705 getF32Constant(DAG, 0x40823e2f, dl)); 4706 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4707 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4708 getF32Constant(DAG, 0x4020d29c, dl)); 4709 } else { // LimitFloatPrecision <= 18 4710 // For floating-point precision of 18: 4711 // 4712 // Log2ofMantissa = 4713 // -3.0400495f + 4714 // (6.1129976f + 4715 // (-5.3420409f + 4716 // (3.2865683f + 4717 // (-1.2669343f + 4718 // (0.27515199f - 4719 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4720 // 4721 // error 0.0000018516, which is better than 18 bits 4722 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4723 getF32Constant(DAG, 0xbcd2769e, dl)); 4724 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4725 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4726 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4727 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4728 getF32Constant(DAG, 0x3fa22ae7, dl)); 4729 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4730 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4731 getF32Constant(DAG, 0x40525723, dl)); 4732 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4733 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4734 getF32Constant(DAG, 0x40aaf200, dl)); 4735 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4736 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4737 getF32Constant(DAG, 0x40c39dad, dl)); 4738 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4739 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4740 getF32Constant(DAG, 0x4042902c, dl)); 4741 } 4742 4743 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4744 } 4745 4746 // No special expansion. 4747 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4748 } 4749 4750 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4751 /// limited-precision mode. 4752 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4753 const TargetLowering &TLI) { 4754 // TODO: What fast-math-flags should be set on the floating-point nodes? 4755 4756 if (Op.getValueType() == MVT::f32 && 4757 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4758 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4759 4760 // Scale the exponent by log10(2) [0.30102999f]. 4761 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4762 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4763 getF32Constant(DAG, 0x3e9a209a, dl)); 4764 4765 // Get the significand and build it into a floating-point number with 4766 // exponent of 1. 4767 SDValue X = GetSignificand(DAG, Op1, dl); 4768 4769 SDValue Log10ofMantissa; 4770 if (LimitFloatPrecision <= 6) { 4771 // For floating-point precision of 6: 4772 // 4773 // Log10ofMantissa = 4774 // -0.50419619f + 4775 // (0.60948995f - 0.10380950f * x) * x; 4776 // 4777 // error 0.0014886165, which is 6 bits 4778 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4779 getF32Constant(DAG, 0xbdd49a13, dl)); 4780 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4781 getF32Constant(DAG, 0x3f1c0789, dl)); 4782 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4783 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4784 getF32Constant(DAG, 0x3f011300, dl)); 4785 } else if (LimitFloatPrecision <= 12) { 4786 // For floating-point precision of 12: 4787 // 4788 // Log10ofMantissa = 4789 // -0.64831180f + 4790 // (0.91751397f + 4791 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4792 // 4793 // error 0.00019228036, which is better than 12 bits 4794 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4795 getF32Constant(DAG, 0x3d431f31, dl)); 4796 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4797 getF32Constant(DAG, 0x3ea21fb2, dl)); 4798 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4799 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4800 getF32Constant(DAG, 0x3f6ae232, dl)); 4801 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4802 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4803 getF32Constant(DAG, 0x3f25f7c3, dl)); 4804 } else { // LimitFloatPrecision <= 18 4805 // For floating-point precision of 18: 4806 // 4807 // Log10ofMantissa = 4808 // -0.84299375f + 4809 // (1.5327582f + 4810 // (-1.0688956f + 4811 // (0.49102474f + 4812 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4813 // 4814 // error 0.0000037995730, which is better than 18 bits 4815 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4816 getF32Constant(DAG, 0x3c5d51ce, dl)); 4817 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4818 getF32Constant(DAG, 0x3e00685a, dl)); 4819 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4820 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4821 getF32Constant(DAG, 0x3efb6798, dl)); 4822 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4823 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4824 getF32Constant(DAG, 0x3f88d192, dl)); 4825 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4826 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4827 getF32Constant(DAG, 0x3fc4316c, dl)); 4828 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4829 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4830 getF32Constant(DAG, 0x3f57ce70, dl)); 4831 } 4832 4833 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4834 } 4835 4836 // No special expansion. 4837 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4838 } 4839 4840 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4841 /// limited-precision mode. 4842 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4843 const TargetLowering &TLI) { 4844 if (Op.getValueType() == MVT::f32 && 4845 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4846 return getLimitedPrecisionExp2(Op, dl, DAG); 4847 4848 // No special expansion. 4849 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4850 } 4851 4852 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4853 /// limited-precision mode with x == 10.0f. 4854 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4855 SelectionDAG &DAG, const TargetLowering &TLI) { 4856 bool IsExp10 = false; 4857 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4858 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4859 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4860 APFloat Ten(10.0f); 4861 IsExp10 = LHSC->isExactlyValue(Ten); 4862 } 4863 } 4864 4865 // TODO: What fast-math-flags should be set on the FMUL node? 4866 if (IsExp10) { 4867 // Put the exponent in the right bit position for later addition to the 4868 // final result: 4869 // 4870 // #define LOG2OF10 3.3219281f 4871 // t0 = Op * LOG2OF10; 4872 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4873 getF32Constant(DAG, 0x40549a78, dl)); 4874 return getLimitedPrecisionExp2(t0, dl, DAG); 4875 } 4876 4877 // No special expansion. 4878 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4879 } 4880 4881 /// ExpandPowI - Expand a llvm.powi intrinsic. 4882 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4883 SelectionDAG &DAG) { 4884 // If RHS is a constant, we can expand this out to a multiplication tree, 4885 // otherwise we end up lowering to a call to __powidf2 (for example). When 4886 // optimizing for size, we only want to do this if the expansion would produce 4887 // a small number of multiplies, otherwise we do the full expansion. 4888 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4889 // Get the exponent as a positive value. 4890 unsigned Val = RHSC->getSExtValue(); 4891 if ((int)Val < 0) Val = -Val; 4892 4893 // powi(x, 0) -> 1.0 4894 if (Val == 0) 4895 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4896 4897 const Function &F = DAG.getMachineFunction().getFunction(); 4898 if (!F.optForSize() || 4899 // If optimizing for size, don't insert too many multiplies. 4900 // This inserts up to 5 multiplies. 4901 countPopulation(Val) + Log2_32(Val) < 7) { 4902 // We use the simple binary decomposition method to generate the multiply 4903 // sequence. There are more optimal ways to do this (for example, 4904 // powi(x,15) generates one more multiply than it should), but this has 4905 // the benefit of being both really simple and much better than a libcall. 4906 SDValue Res; // Logically starts equal to 1.0 4907 SDValue CurSquare = LHS; 4908 // TODO: Intrinsics should have fast-math-flags that propagate to these 4909 // nodes. 4910 while (Val) { 4911 if (Val & 1) { 4912 if (Res.getNode()) 4913 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4914 else 4915 Res = CurSquare; // 1.0*CurSquare. 4916 } 4917 4918 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4919 CurSquare, CurSquare); 4920 Val >>= 1; 4921 } 4922 4923 // If the original was negative, invert the result, producing 1/(x*x*x). 4924 if (RHSC->getSExtValue() < 0) 4925 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4926 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4927 return Res; 4928 } 4929 } 4930 4931 // Otherwise, expand to a libcall. 4932 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4933 } 4934 4935 // getUnderlyingArgReg - Find underlying register used for a truncated or 4936 // bitcasted argument. 4937 static unsigned getUnderlyingArgReg(const SDValue &N) { 4938 switch (N.getOpcode()) { 4939 case ISD::CopyFromReg: 4940 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4941 case ISD::BITCAST: 4942 case ISD::AssertZext: 4943 case ISD::AssertSext: 4944 case ISD::TRUNCATE: 4945 return getUnderlyingArgReg(N.getOperand(0)); 4946 default: 4947 return 0; 4948 } 4949 } 4950 4951 /// If the DbgValueInst is a dbg_value of a function argument, create the 4952 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4953 /// instruction selection, they will be inserted to the entry BB. 4954 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4955 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4956 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4957 const Argument *Arg = dyn_cast<Argument>(V); 4958 if (!Arg) 4959 return false; 4960 4961 MachineFunction &MF = DAG.getMachineFunction(); 4962 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4963 4964 bool IsIndirect = false; 4965 Optional<MachineOperand> Op; 4966 // Some arguments' frame index is recorded during argument lowering. 4967 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4968 if (FI != std::numeric_limits<int>::max()) 4969 Op = MachineOperand::CreateFI(FI); 4970 4971 if (!Op && N.getNode()) { 4972 unsigned Reg = getUnderlyingArgReg(N); 4973 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4974 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4975 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4976 if (PR) 4977 Reg = PR; 4978 } 4979 if (Reg) { 4980 Op = MachineOperand::CreateReg(Reg, false); 4981 IsIndirect = IsDbgDeclare; 4982 } 4983 } 4984 4985 if (!Op && N.getNode()) 4986 // Check if frame index is available. 4987 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4988 if (FrameIndexSDNode *FINode = 4989 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4990 Op = MachineOperand::CreateFI(FINode->getIndex()); 4991 4992 if (!Op) { 4993 // Check if ValueMap has reg number. 4994 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4995 if (VMI != FuncInfo.ValueMap.end()) { 4996 const auto &TLI = DAG.getTargetLoweringInfo(); 4997 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4998 V->getType(), getABIRegCopyCC(V)); 4999 if (RFV.occupiesMultipleRegs()) { 5000 unsigned Offset = 0; 5001 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5002 Op = MachineOperand::CreateReg(RegAndSize.first, false); 5003 auto FragmentExpr = DIExpression::createFragmentExpression( 5004 Expr, Offset, RegAndSize.second); 5005 if (!FragmentExpr) 5006 continue; 5007 FuncInfo.ArgDbgValues.push_back( 5008 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5009 Op->getReg(), Variable, *FragmentExpr)); 5010 Offset += RegAndSize.second; 5011 } 5012 return true; 5013 } 5014 Op = MachineOperand::CreateReg(VMI->second, false); 5015 IsIndirect = IsDbgDeclare; 5016 } 5017 } 5018 5019 if (!Op) 5020 return false; 5021 5022 assert(Variable->isValidLocationForIntrinsic(DL) && 5023 "Expected inlined-at fields to agree"); 5024 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5025 FuncInfo.ArgDbgValues.push_back( 5026 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5027 *Op, Variable, Expr)); 5028 5029 return true; 5030 } 5031 5032 /// Return the appropriate SDDbgValue based on N. 5033 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5034 DILocalVariable *Variable, 5035 DIExpression *Expr, 5036 const DebugLoc &dl, 5037 unsigned DbgSDNodeOrder) { 5038 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5039 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5040 // stack slot locations. 5041 // 5042 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5043 // debug values here after optimization: 5044 // 5045 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5046 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5047 // 5048 // Both describe the direct values of their associated variables. 5049 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5050 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5051 } 5052 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5053 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5054 } 5055 5056 // VisualStudio defines setjmp as _setjmp 5057 #if defined(_MSC_VER) && defined(setjmp) && \ 5058 !defined(setjmp_undefined_for_msvc) 5059 # pragma push_macro("setjmp") 5060 # undef setjmp 5061 # define setjmp_undefined_for_msvc 5062 #endif 5063 5064 /// Lower the call to the specified intrinsic function. If we want to emit this 5065 /// as a call to a named external function, return the name. Otherwise, lower it 5066 /// and return null. 5067 const char * 5068 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5069 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5070 SDLoc sdl = getCurSDLoc(); 5071 DebugLoc dl = getCurDebugLoc(); 5072 SDValue Res; 5073 5074 switch (Intrinsic) { 5075 default: 5076 // By default, turn this into a target intrinsic node. 5077 visitTargetIntrinsic(I, Intrinsic); 5078 return nullptr; 5079 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5080 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5081 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5082 case Intrinsic::returnaddress: 5083 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5084 TLI.getPointerTy(DAG.getDataLayout()), 5085 getValue(I.getArgOperand(0)))); 5086 return nullptr; 5087 case Intrinsic::addressofreturnaddress: 5088 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5089 TLI.getPointerTy(DAG.getDataLayout()))); 5090 return nullptr; 5091 case Intrinsic::sponentry: 5092 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5093 TLI.getPointerTy(DAG.getDataLayout()))); 5094 return nullptr; 5095 case Intrinsic::frameaddress: 5096 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5097 TLI.getPointerTy(DAG.getDataLayout()), 5098 getValue(I.getArgOperand(0)))); 5099 return nullptr; 5100 case Intrinsic::read_register: { 5101 Value *Reg = I.getArgOperand(0); 5102 SDValue Chain = getRoot(); 5103 SDValue RegName = 5104 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5105 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5106 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5107 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5108 setValue(&I, Res); 5109 DAG.setRoot(Res.getValue(1)); 5110 return nullptr; 5111 } 5112 case Intrinsic::write_register: { 5113 Value *Reg = I.getArgOperand(0); 5114 Value *RegValue = I.getArgOperand(1); 5115 SDValue Chain = getRoot(); 5116 SDValue RegName = 5117 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5118 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5119 RegName, getValue(RegValue))); 5120 return nullptr; 5121 } 5122 case Intrinsic::setjmp: 5123 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5124 case Intrinsic::longjmp: 5125 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5126 case Intrinsic::memcpy: { 5127 const auto &MCI = cast<MemCpyInst>(I); 5128 SDValue Op1 = getValue(I.getArgOperand(0)); 5129 SDValue Op2 = getValue(I.getArgOperand(1)); 5130 SDValue Op3 = getValue(I.getArgOperand(2)); 5131 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5132 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5133 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5134 unsigned Align = MinAlign(DstAlign, SrcAlign); 5135 bool isVol = MCI.isVolatile(); 5136 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5137 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5138 // node. 5139 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5140 false, isTC, 5141 MachinePointerInfo(I.getArgOperand(0)), 5142 MachinePointerInfo(I.getArgOperand(1))); 5143 updateDAGForMaybeTailCall(MC); 5144 return nullptr; 5145 } 5146 case Intrinsic::memset: { 5147 const auto &MSI = cast<MemSetInst>(I); 5148 SDValue Op1 = getValue(I.getArgOperand(0)); 5149 SDValue Op2 = getValue(I.getArgOperand(1)); 5150 SDValue Op3 = getValue(I.getArgOperand(2)); 5151 // @llvm.memset defines 0 and 1 to both mean no alignment. 5152 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5153 bool isVol = MSI.isVolatile(); 5154 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5155 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5156 isTC, MachinePointerInfo(I.getArgOperand(0))); 5157 updateDAGForMaybeTailCall(MS); 5158 return nullptr; 5159 } 5160 case Intrinsic::memmove: { 5161 const auto &MMI = cast<MemMoveInst>(I); 5162 SDValue Op1 = getValue(I.getArgOperand(0)); 5163 SDValue Op2 = getValue(I.getArgOperand(1)); 5164 SDValue Op3 = getValue(I.getArgOperand(2)); 5165 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5166 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5167 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5168 unsigned Align = MinAlign(DstAlign, SrcAlign); 5169 bool isVol = MMI.isVolatile(); 5170 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5171 // FIXME: Support passing different dest/src alignments to the memmove DAG 5172 // node. 5173 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5174 isTC, MachinePointerInfo(I.getArgOperand(0)), 5175 MachinePointerInfo(I.getArgOperand(1))); 5176 updateDAGForMaybeTailCall(MM); 5177 return nullptr; 5178 } 5179 case Intrinsic::memcpy_element_unordered_atomic: { 5180 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5181 SDValue Dst = getValue(MI.getRawDest()); 5182 SDValue Src = getValue(MI.getRawSource()); 5183 SDValue Length = getValue(MI.getLength()); 5184 5185 unsigned DstAlign = MI.getDestAlignment(); 5186 unsigned SrcAlign = MI.getSourceAlignment(); 5187 Type *LengthTy = MI.getLength()->getType(); 5188 unsigned ElemSz = MI.getElementSizeInBytes(); 5189 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5190 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5191 SrcAlign, Length, LengthTy, ElemSz, isTC, 5192 MachinePointerInfo(MI.getRawDest()), 5193 MachinePointerInfo(MI.getRawSource())); 5194 updateDAGForMaybeTailCall(MC); 5195 return nullptr; 5196 } 5197 case Intrinsic::memmove_element_unordered_atomic: { 5198 auto &MI = cast<AtomicMemMoveInst>(I); 5199 SDValue Dst = getValue(MI.getRawDest()); 5200 SDValue Src = getValue(MI.getRawSource()); 5201 SDValue Length = getValue(MI.getLength()); 5202 5203 unsigned DstAlign = MI.getDestAlignment(); 5204 unsigned SrcAlign = MI.getSourceAlignment(); 5205 Type *LengthTy = MI.getLength()->getType(); 5206 unsigned ElemSz = MI.getElementSizeInBytes(); 5207 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5208 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5209 SrcAlign, Length, LengthTy, ElemSz, isTC, 5210 MachinePointerInfo(MI.getRawDest()), 5211 MachinePointerInfo(MI.getRawSource())); 5212 updateDAGForMaybeTailCall(MC); 5213 return nullptr; 5214 } 5215 case Intrinsic::memset_element_unordered_atomic: { 5216 auto &MI = cast<AtomicMemSetInst>(I); 5217 SDValue Dst = getValue(MI.getRawDest()); 5218 SDValue Val = getValue(MI.getValue()); 5219 SDValue Length = getValue(MI.getLength()); 5220 5221 unsigned DstAlign = MI.getDestAlignment(); 5222 Type *LengthTy = MI.getLength()->getType(); 5223 unsigned ElemSz = MI.getElementSizeInBytes(); 5224 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5225 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5226 LengthTy, ElemSz, isTC, 5227 MachinePointerInfo(MI.getRawDest())); 5228 updateDAGForMaybeTailCall(MC); 5229 return nullptr; 5230 } 5231 case Intrinsic::dbg_addr: 5232 case Intrinsic::dbg_declare: { 5233 const auto &DI = cast<DbgVariableIntrinsic>(I); 5234 DILocalVariable *Variable = DI.getVariable(); 5235 DIExpression *Expression = DI.getExpression(); 5236 dropDanglingDebugInfo(Variable, Expression); 5237 assert(Variable && "Missing variable"); 5238 5239 // Check if address has undef value. 5240 const Value *Address = DI.getVariableLocation(); 5241 if (!Address || isa<UndefValue>(Address) || 5242 (Address->use_empty() && !isa<Argument>(Address))) { 5243 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5244 return nullptr; 5245 } 5246 5247 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5248 5249 // Check if this variable can be described by a frame index, typically 5250 // either as a static alloca or a byval parameter. 5251 int FI = std::numeric_limits<int>::max(); 5252 if (const auto *AI = 5253 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5254 if (AI->isStaticAlloca()) { 5255 auto I = FuncInfo.StaticAllocaMap.find(AI); 5256 if (I != FuncInfo.StaticAllocaMap.end()) 5257 FI = I->second; 5258 } 5259 } else if (const auto *Arg = dyn_cast<Argument>( 5260 Address->stripInBoundsConstantOffsets())) { 5261 FI = FuncInfo.getArgumentFrameIndex(Arg); 5262 } 5263 5264 // llvm.dbg.addr is control dependent and always generates indirect 5265 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5266 // the MachineFunction variable table. 5267 if (FI != std::numeric_limits<int>::max()) { 5268 if (Intrinsic == Intrinsic::dbg_addr) { 5269 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5270 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5271 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5272 } 5273 return nullptr; 5274 } 5275 5276 SDValue &N = NodeMap[Address]; 5277 if (!N.getNode() && isa<Argument>(Address)) 5278 // Check unused arguments map. 5279 N = UnusedArgNodeMap[Address]; 5280 SDDbgValue *SDV; 5281 if (N.getNode()) { 5282 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5283 Address = BCI->getOperand(0); 5284 // Parameters are handled specially. 5285 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5286 if (isParameter && FINode) { 5287 // Byval parameter. We have a frame index at this point. 5288 SDV = 5289 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5290 /*IsIndirect*/ true, dl, SDNodeOrder); 5291 } else if (isa<Argument>(Address)) { 5292 // Address is an argument, so try to emit its dbg value using 5293 // virtual register info from the FuncInfo.ValueMap. 5294 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5295 return nullptr; 5296 } else { 5297 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5298 true, dl, SDNodeOrder); 5299 } 5300 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5301 } else { 5302 // If Address is an argument then try to emit its dbg value using 5303 // virtual register info from the FuncInfo.ValueMap. 5304 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5305 N)) { 5306 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5307 } 5308 } 5309 return nullptr; 5310 } 5311 case Intrinsic::dbg_label: { 5312 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5313 DILabel *Label = DI.getLabel(); 5314 assert(Label && "Missing label"); 5315 5316 SDDbgLabel *SDV; 5317 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5318 DAG.AddDbgLabel(SDV); 5319 return nullptr; 5320 } 5321 case Intrinsic::dbg_value: { 5322 const DbgValueInst &DI = cast<DbgValueInst>(I); 5323 assert(DI.getVariable() && "Missing variable"); 5324 5325 DILocalVariable *Variable = DI.getVariable(); 5326 DIExpression *Expression = DI.getExpression(); 5327 dropDanglingDebugInfo(Variable, Expression); 5328 const Value *V = DI.getValue(); 5329 if (!V) 5330 return nullptr; 5331 5332 SDDbgValue *SDV; 5333 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 5334 isa<ConstantPointerNull>(V)) { 5335 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5336 DAG.AddDbgValue(SDV, nullptr, false); 5337 return nullptr; 5338 } 5339 5340 // Do not use getValue() in here; we don't want to generate code at 5341 // this point if it hasn't been done yet. 5342 SDValue N = NodeMap[V]; 5343 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5344 N = UnusedArgNodeMap[V]; 5345 if (N.getNode()) { 5346 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5347 return nullptr; 5348 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5349 DAG.AddDbgValue(SDV, N.getNode(), false); 5350 return nullptr; 5351 } 5352 5353 // PHI nodes have already been selected, so we should know which VReg that 5354 // is assigns to already. 5355 if (isa<PHINode>(V)) { 5356 auto VMI = FuncInfo.ValueMap.find(V); 5357 if (VMI != FuncInfo.ValueMap.end()) { 5358 unsigned Reg = VMI->second; 5359 // The PHI node may be split up into several MI PHI nodes (in 5360 // FunctionLoweringInfo::set). 5361 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5362 V->getType(), None); 5363 if (RFV.occupiesMultipleRegs()) { 5364 unsigned Offset = 0; 5365 unsigned BitsToDescribe = 0; 5366 if (auto VarSize = Variable->getSizeInBits()) 5367 BitsToDescribe = *VarSize; 5368 if (auto Fragment = Expression->getFragmentInfo()) 5369 BitsToDescribe = Fragment->SizeInBits; 5370 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5371 unsigned RegisterSize = RegAndSize.second; 5372 // Bail out if all bits are described already. 5373 if (Offset >= BitsToDescribe) 5374 break; 5375 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5376 ? BitsToDescribe - Offset 5377 : RegisterSize; 5378 auto FragmentExpr = DIExpression::createFragmentExpression( 5379 Expression, Offset, FragmentSize); 5380 if (!FragmentExpr) 5381 continue; 5382 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5383 false, dl, SDNodeOrder); 5384 DAG.AddDbgValue(SDV, nullptr, false); 5385 Offset += RegisterSize; 5386 } 5387 } else { 5388 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5389 SDNodeOrder); 5390 DAG.AddDbgValue(SDV, nullptr, false); 5391 } 5392 return nullptr; 5393 } 5394 } 5395 5396 // TODO: When we get here we will either drop the dbg.value completely, or 5397 // we try to move it forward by letting it dangle for awhile. So we should 5398 // probably add an extra DbgValue to the DAG here, with a reference to 5399 // "noreg", to indicate that we have lost the debug location for the 5400 // variable. 5401 5402 if (!V->use_empty() ) { 5403 // Do not call getValue(V) yet, as we don't want to generate code. 5404 // Remember it for later. 5405 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5406 return nullptr; 5407 } 5408 5409 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5410 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5411 return nullptr; 5412 } 5413 5414 case Intrinsic::eh_typeid_for: { 5415 // Find the type id for the given typeinfo. 5416 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5417 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5418 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5419 setValue(&I, Res); 5420 return nullptr; 5421 } 5422 5423 case Intrinsic::eh_return_i32: 5424 case Intrinsic::eh_return_i64: 5425 DAG.getMachineFunction().setCallsEHReturn(true); 5426 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5427 MVT::Other, 5428 getControlRoot(), 5429 getValue(I.getArgOperand(0)), 5430 getValue(I.getArgOperand(1)))); 5431 return nullptr; 5432 case Intrinsic::eh_unwind_init: 5433 DAG.getMachineFunction().setCallsUnwindInit(true); 5434 return nullptr; 5435 case Intrinsic::eh_dwarf_cfa: 5436 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5437 TLI.getPointerTy(DAG.getDataLayout()), 5438 getValue(I.getArgOperand(0)))); 5439 return nullptr; 5440 case Intrinsic::eh_sjlj_callsite: { 5441 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5442 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5443 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5444 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5445 5446 MMI.setCurrentCallSite(CI->getZExtValue()); 5447 return nullptr; 5448 } 5449 case Intrinsic::eh_sjlj_functioncontext: { 5450 // Get and store the index of the function context. 5451 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5452 AllocaInst *FnCtx = 5453 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5454 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5455 MFI.setFunctionContextIndex(FI); 5456 return nullptr; 5457 } 5458 case Intrinsic::eh_sjlj_setjmp: { 5459 SDValue Ops[2]; 5460 Ops[0] = getRoot(); 5461 Ops[1] = getValue(I.getArgOperand(0)); 5462 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5463 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5464 setValue(&I, Op.getValue(0)); 5465 DAG.setRoot(Op.getValue(1)); 5466 return nullptr; 5467 } 5468 case Intrinsic::eh_sjlj_longjmp: 5469 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5470 getRoot(), getValue(I.getArgOperand(0)))); 5471 return nullptr; 5472 case Intrinsic::eh_sjlj_setup_dispatch: 5473 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5474 getRoot())); 5475 return nullptr; 5476 case Intrinsic::masked_gather: 5477 visitMaskedGather(I); 5478 return nullptr; 5479 case Intrinsic::masked_load: 5480 visitMaskedLoad(I); 5481 return nullptr; 5482 case Intrinsic::masked_scatter: 5483 visitMaskedScatter(I); 5484 return nullptr; 5485 case Intrinsic::masked_store: 5486 visitMaskedStore(I); 5487 return nullptr; 5488 case Intrinsic::masked_expandload: 5489 visitMaskedLoad(I, true /* IsExpanding */); 5490 return nullptr; 5491 case Intrinsic::masked_compressstore: 5492 visitMaskedStore(I, true /* IsCompressing */); 5493 return nullptr; 5494 case Intrinsic::x86_mmx_pslli_w: 5495 case Intrinsic::x86_mmx_pslli_d: 5496 case Intrinsic::x86_mmx_pslli_q: 5497 case Intrinsic::x86_mmx_psrli_w: 5498 case Intrinsic::x86_mmx_psrli_d: 5499 case Intrinsic::x86_mmx_psrli_q: 5500 case Intrinsic::x86_mmx_psrai_w: 5501 case Intrinsic::x86_mmx_psrai_d: { 5502 SDValue ShAmt = getValue(I.getArgOperand(1)); 5503 if (isa<ConstantSDNode>(ShAmt)) { 5504 visitTargetIntrinsic(I, Intrinsic); 5505 return nullptr; 5506 } 5507 unsigned NewIntrinsic = 0; 5508 EVT ShAmtVT = MVT::v2i32; 5509 switch (Intrinsic) { 5510 case Intrinsic::x86_mmx_pslli_w: 5511 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5512 break; 5513 case Intrinsic::x86_mmx_pslli_d: 5514 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5515 break; 5516 case Intrinsic::x86_mmx_pslli_q: 5517 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5518 break; 5519 case Intrinsic::x86_mmx_psrli_w: 5520 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5521 break; 5522 case Intrinsic::x86_mmx_psrli_d: 5523 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5524 break; 5525 case Intrinsic::x86_mmx_psrli_q: 5526 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5527 break; 5528 case Intrinsic::x86_mmx_psrai_w: 5529 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5530 break; 5531 case Intrinsic::x86_mmx_psrai_d: 5532 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5533 break; 5534 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5535 } 5536 5537 // The vector shift intrinsics with scalars uses 32b shift amounts but 5538 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5539 // to be zero. 5540 // We must do this early because v2i32 is not a legal type. 5541 SDValue ShOps[2]; 5542 ShOps[0] = ShAmt; 5543 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5544 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5545 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5546 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5547 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5548 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5549 getValue(I.getArgOperand(0)), ShAmt); 5550 setValue(&I, Res); 5551 return nullptr; 5552 } 5553 case Intrinsic::powi: 5554 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5555 getValue(I.getArgOperand(1)), DAG)); 5556 return nullptr; 5557 case Intrinsic::log: 5558 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5559 return nullptr; 5560 case Intrinsic::log2: 5561 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5562 return nullptr; 5563 case Intrinsic::log10: 5564 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5565 return nullptr; 5566 case Intrinsic::exp: 5567 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5568 return nullptr; 5569 case Intrinsic::exp2: 5570 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5571 return nullptr; 5572 case Intrinsic::pow: 5573 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5574 getValue(I.getArgOperand(1)), DAG, TLI)); 5575 return nullptr; 5576 case Intrinsic::sqrt: 5577 case Intrinsic::fabs: 5578 case Intrinsic::sin: 5579 case Intrinsic::cos: 5580 case Intrinsic::floor: 5581 case Intrinsic::ceil: 5582 case Intrinsic::trunc: 5583 case Intrinsic::rint: 5584 case Intrinsic::nearbyint: 5585 case Intrinsic::round: 5586 case Intrinsic::canonicalize: { 5587 unsigned Opcode; 5588 switch (Intrinsic) { 5589 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5590 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5591 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5592 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5593 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5594 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5595 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5596 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5597 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5598 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5599 case Intrinsic::round: Opcode = ISD::FROUND; break; 5600 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5601 } 5602 5603 setValue(&I, DAG.getNode(Opcode, sdl, 5604 getValue(I.getArgOperand(0)).getValueType(), 5605 getValue(I.getArgOperand(0)))); 5606 return nullptr; 5607 } 5608 case Intrinsic::minnum: { 5609 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5610 unsigned Opc = 5611 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 5612 ? ISD::FMINIMUM 5613 : ISD::FMINNUM; 5614 setValue(&I, DAG.getNode(Opc, sdl, VT, 5615 getValue(I.getArgOperand(0)), 5616 getValue(I.getArgOperand(1)))); 5617 return nullptr; 5618 } 5619 case Intrinsic::maxnum: { 5620 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5621 unsigned Opc = 5622 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 5623 ? ISD::FMAXIMUM 5624 : ISD::FMAXNUM; 5625 setValue(&I, DAG.getNode(Opc, sdl, VT, 5626 getValue(I.getArgOperand(0)), 5627 getValue(I.getArgOperand(1)))); 5628 return nullptr; 5629 } 5630 case Intrinsic::minimum: 5631 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 5632 getValue(I.getArgOperand(0)).getValueType(), 5633 getValue(I.getArgOperand(0)), 5634 getValue(I.getArgOperand(1)))); 5635 return nullptr; 5636 case Intrinsic::maximum: 5637 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 5638 getValue(I.getArgOperand(0)).getValueType(), 5639 getValue(I.getArgOperand(0)), 5640 getValue(I.getArgOperand(1)))); 5641 return nullptr; 5642 case Intrinsic::copysign: 5643 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5644 getValue(I.getArgOperand(0)).getValueType(), 5645 getValue(I.getArgOperand(0)), 5646 getValue(I.getArgOperand(1)))); 5647 return nullptr; 5648 case Intrinsic::fma: 5649 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5650 getValue(I.getArgOperand(0)).getValueType(), 5651 getValue(I.getArgOperand(0)), 5652 getValue(I.getArgOperand(1)), 5653 getValue(I.getArgOperand(2)))); 5654 return nullptr; 5655 case Intrinsic::experimental_constrained_fadd: 5656 case Intrinsic::experimental_constrained_fsub: 5657 case Intrinsic::experimental_constrained_fmul: 5658 case Intrinsic::experimental_constrained_fdiv: 5659 case Intrinsic::experimental_constrained_frem: 5660 case Intrinsic::experimental_constrained_fma: 5661 case Intrinsic::experimental_constrained_sqrt: 5662 case Intrinsic::experimental_constrained_pow: 5663 case Intrinsic::experimental_constrained_powi: 5664 case Intrinsic::experimental_constrained_sin: 5665 case Intrinsic::experimental_constrained_cos: 5666 case Intrinsic::experimental_constrained_exp: 5667 case Intrinsic::experimental_constrained_exp2: 5668 case Intrinsic::experimental_constrained_log: 5669 case Intrinsic::experimental_constrained_log10: 5670 case Intrinsic::experimental_constrained_log2: 5671 case Intrinsic::experimental_constrained_rint: 5672 case Intrinsic::experimental_constrained_nearbyint: 5673 case Intrinsic::experimental_constrained_maxnum: 5674 case Intrinsic::experimental_constrained_minnum: 5675 case Intrinsic::experimental_constrained_ceil: 5676 case Intrinsic::experimental_constrained_floor: 5677 case Intrinsic::experimental_constrained_round: 5678 case Intrinsic::experimental_constrained_trunc: 5679 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5680 return nullptr; 5681 case Intrinsic::fmuladd: { 5682 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5683 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5684 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5685 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5686 getValue(I.getArgOperand(0)).getValueType(), 5687 getValue(I.getArgOperand(0)), 5688 getValue(I.getArgOperand(1)), 5689 getValue(I.getArgOperand(2)))); 5690 } else { 5691 // TODO: Intrinsic calls should have fast-math-flags. 5692 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5693 getValue(I.getArgOperand(0)).getValueType(), 5694 getValue(I.getArgOperand(0)), 5695 getValue(I.getArgOperand(1))); 5696 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5697 getValue(I.getArgOperand(0)).getValueType(), 5698 Mul, 5699 getValue(I.getArgOperand(2))); 5700 setValue(&I, Add); 5701 } 5702 return nullptr; 5703 } 5704 case Intrinsic::convert_to_fp16: 5705 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5706 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5707 getValue(I.getArgOperand(0)), 5708 DAG.getTargetConstant(0, sdl, 5709 MVT::i32)))); 5710 return nullptr; 5711 case Intrinsic::convert_from_fp16: 5712 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5713 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5714 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5715 getValue(I.getArgOperand(0))))); 5716 return nullptr; 5717 case Intrinsic::pcmarker: { 5718 SDValue Tmp = getValue(I.getArgOperand(0)); 5719 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5720 return nullptr; 5721 } 5722 case Intrinsic::readcyclecounter: { 5723 SDValue Op = getRoot(); 5724 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5725 DAG.getVTList(MVT::i64, MVT::Other), Op); 5726 setValue(&I, Res); 5727 DAG.setRoot(Res.getValue(1)); 5728 return nullptr; 5729 } 5730 case Intrinsic::bitreverse: 5731 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5732 getValue(I.getArgOperand(0)).getValueType(), 5733 getValue(I.getArgOperand(0)))); 5734 return nullptr; 5735 case Intrinsic::bswap: 5736 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5737 getValue(I.getArgOperand(0)).getValueType(), 5738 getValue(I.getArgOperand(0)))); 5739 return nullptr; 5740 case Intrinsic::cttz: { 5741 SDValue Arg = getValue(I.getArgOperand(0)); 5742 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5743 EVT Ty = Arg.getValueType(); 5744 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5745 sdl, Ty, Arg)); 5746 return nullptr; 5747 } 5748 case Intrinsic::ctlz: { 5749 SDValue Arg = getValue(I.getArgOperand(0)); 5750 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5751 EVT Ty = Arg.getValueType(); 5752 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5753 sdl, Ty, Arg)); 5754 return nullptr; 5755 } 5756 case Intrinsic::ctpop: { 5757 SDValue Arg = getValue(I.getArgOperand(0)); 5758 EVT Ty = Arg.getValueType(); 5759 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5760 return nullptr; 5761 } 5762 case Intrinsic::fshl: 5763 case Intrinsic::fshr: { 5764 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5765 SDValue X = getValue(I.getArgOperand(0)); 5766 SDValue Y = getValue(I.getArgOperand(1)); 5767 SDValue Z = getValue(I.getArgOperand(2)); 5768 EVT VT = X.getValueType(); 5769 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5770 SDValue Zero = DAG.getConstant(0, sdl, VT); 5771 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5772 5773 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 5774 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 5775 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 5776 return nullptr; 5777 } 5778 5779 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 5780 // avoid the select that is necessary in the general case to filter out 5781 // the 0-shift possibility that leads to UB. 5782 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 5783 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5784 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5785 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5786 return nullptr; 5787 } 5788 5789 // Some targets only rotate one way. Try the opposite direction. 5790 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 5791 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5792 // Negate the shift amount because it is safe to ignore the high bits. 5793 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5794 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 5795 return nullptr; 5796 } 5797 5798 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 5799 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 5800 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5801 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5802 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 5803 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 5804 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 5805 return nullptr; 5806 } 5807 5808 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5809 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5810 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 5811 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5812 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5813 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5814 5815 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5816 // and that is undefined. We must compare and select to avoid UB. 5817 EVT CCVT = MVT::i1; 5818 if (VT.isVector()) 5819 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5820 5821 // For fshl, 0-shift returns the 1st arg (X). 5822 // For fshr, 0-shift returns the 2nd arg (Y). 5823 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5824 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 5825 return nullptr; 5826 } 5827 case Intrinsic::sadd_sat: { 5828 SDValue Op1 = getValue(I.getArgOperand(0)); 5829 SDValue Op2 = getValue(I.getArgOperand(1)); 5830 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5831 return nullptr; 5832 } 5833 case Intrinsic::uadd_sat: { 5834 SDValue Op1 = getValue(I.getArgOperand(0)); 5835 SDValue Op2 = getValue(I.getArgOperand(1)); 5836 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5837 return nullptr; 5838 } 5839 case Intrinsic::ssub_sat: { 5840 SDValue Op1 = getValue(I.getArgOperand(0)); 5841 SDValue Op2 = getValue(I.getArgOperand(1)); 5842 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5843 return nullptr; 5844 } 5845 case Intrinsic::usub_sat: { 5846 SDValue Op1 = getValue(I.getArgOperand(0)); 5847 SDValue Op2 = getValue(I.getArgOperand(1)); 5848 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5849 return nullptr; 5850 } 5851 case Intrinsic::smul_fix: { 5852 SDValue Op1 = getValue(I.getArgOperand(0)); 5853 SDValue Op2 = getValue(I.getArgOperand(1)); 5854 SDValue Op3 = getValue(I.getArgOperand(2)); 5855 setValue(&I, 5856 DAG.getNode(ISD::SMULFIX, sdl, Op1.getValueType(), Op1, Op2, Op3)); 5857 return nullptr; 5858 } 5859 case Intrinsic::stacksave: { 5860 SDValue Op = getRoot(); 5861 Res = DAG.getNode( 5862 ISD::STACKSAVE, sdl, 5863 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5864 setValue(&I, Res); 5865 DAG.setRoot(Res.getValue(1)); 5866 return nullptr; 5867 } 5868 case Intrinsic::stackrestore: 5869 Res = getValue(I.getArgOperand(0)); 5870 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5871 return nullptr; 5872 case Intrinsic::get_dynamic_area_offset: { 5873 SDValue Op = getRoot(); 5874 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5875 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5876 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5877 // target. 5878 if (PtrTy != ResTy) 5879 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5880 " intrinsic!"); 5881 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5882 Op); 5883 DAG.setRoot(Op); 5884 setValue(&I, Res); 5885 return nullptr; 5886 } 5887 case Intrinsic::stackguard: { 5888 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5889 MachineFunction &MF = DAG.getMachineFunction(); 5890 const Module &M = *MF.getFunction().getParent(); 5891 SDValue Chain = getRoot(); 5892 if (TLI.useLoadStackGuardNode()) { 5893 Res = getLoadStackGuard(DAG, sdl, Chain); 5894 } else { 5895 const Value *Global = TLI.getSDagStackGuard(M); 5896 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5897 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5898 MachinePointerInfo(Global, 0), Align, 5899 MachineMemOperand::MOVolatile); 5900 } 5901 if (TLI.useStackGuardXorFP()) 5902 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5903 DAG.setRoot(Chain); 5904 setValue(&I, Res); 5905 return nullptr; 5906 } 5907 case Intrinsic::stackprotector: { 5908 // Emit code into the DAG to store the stack guard onto the stack. 5909 MachineFunction &MF = DAG.getMachineFunction(); 5910 MachineFrameInfo &MFI = MF.getFrameInfo(); 5911 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5912 SDValue Src, Chain = getRoot(); 5913 5914 if (TLI.useLoadStackGuardNode()) 5915 Src = getLoadStackGuard(DAG, sdl, Chain); 5916 else 5917 Src = getValue(I.getArgOperand(0)); // The guard's value. 5918 5919 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5920 5921 int FI = FuncInfo.StaticAllocaMap[Slot]; 5922 MFI.setStackProtectorIndex(FI); 5923 5924 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5925 5926 // Store the stack protector onto the stack. 5927 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5928 DAG.getMachineFunction(), FI), 5929 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5930 setValue(&I, Res); 5931 DAG.setRoot(Res); 5932 return nullptr; 5933 } 5934 case Intrinsic::objectsize: { 5935 // If we don't know by now, we're never going to know. 5936 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5937 5938 assert(CI && "Non-constant type in __builtin_object_size?"); 5939 5940 SDValue Arg = getValue(I.getCalledValue()); 5941 EVT Ty = Arg.getValueType(); 5942 5943 if (CI->isZero()) 5944 Res = DAG.getConstant(-1ULL, sdl, Ty); 5945 else 5946 Res = DAG.getConstant(0, sdl, Ty); 5947 5948 setValue(&I, Res); 5949 return nullptr; 5950 } 5951 5952 case Intrinsic::is_constant: 5953 // If this wasn't constant-folded away by now, then it's not a 5954 // constant. 5955 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 5956 return nullptr; 5957 5958 case Intrinsic::annotation: 5959 case Intrinsic::ptr_annotation: 5960 case Intrinsic::launder_invariant_group: 5961 case Intrinsic::strip_invariant_group: 5962 // Drop the intrinsic, but forward the value 5963 setValue(&I, getValue(I.getOperand(0))); 5964 return nullptr; 5965 case Intrinsic::assume: 5966 case Intrinsic::var_annotation: 5967 case Intrinsic::sideeffect: 5968 // Discard annotate attributes, assumptions, and artificial side-effects. 5969 return nullptr; 5970 5971 case Intrinsic::codeview_annotation: { 5972 // Emit a label associated with this metadata. 5973 MachineFunction &MF = DAG.getMachineFunction(); 5974 MCSymbol *Label = 5975 MF.getMMI().getContext().createTempSymbol("annotation", true); 5976 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5977 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5978 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5979 DAG.setRoot(Res); 5980 return nullptr; 5981 } 5982 5983 case Intrinsic::init_trampoline: { 5984 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5985 5986 SDValue Ops[6]; 5987 Ops[0] = getRoot(); 5988 Ops[1] = getValue(I.getArgOperand(0)); 5989 Ops[2] = getValue(I.getArgOperand(1)); 5990 Ops[3] = getValue(I.getArgOperand(2)); 5991 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5992 Ops[5] = DAG.getSrcValue(F); 5993 5994 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5995 5996 DAG.setRoot(Res); 5997 return nullptr; 5998 } 5999 case Intrinsic::adjust_trampoline: 6000 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6001 TLI.getPointerTy(DAG.getDataLayout()), 6002 getValue(I.getArgOperand(0)))); 6003 return nullptr; 6004 case Intrinsic::gcroot: { 6005 assert(DAG.getMachineFunction().getFunction().hasGC() && 6006 "only valid in functions with gc specified, enforced by Verifier"); 6007 assert(GFI && "implied by previous"); 6008 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6009 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6010 6011 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6012 GFI->addStackRoot(FI->getIndex(), TypeMap); 6013 return nullptr; 6014 } 6015 case Intrinsic::gcread: 6016 case Intrinsic::gcwrite: 6017 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6018 case Intrinsic::flt_rounds: 6019 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6020 return nullptr; 6021 6022 case Intrinsic::expect: 6023 // Just replace __builtin_expect(exp, c) with EXP. 6024 setValue(&I, getValue(I.getArgOperand(0))); 6025 return nullptr; 6026 6027 case Intrinsic::debugtrap: 6028 case Intrinsic::trap: { 6029 StringRef TrapFuncName = 6030 I.getAttributes() 6031 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6032 .getValueAsString(); 6033 if (TrapFuncName.empty()) { 6034 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6035 ISD::TRAP : ISD::DEBUGTRAP; 6036 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6037 return nullptr; 6038 } 6039 TargetLowering::ArgListTy Args; 6040 6041 TargetLowering::CallLoweringInfo CLI(DAG); 6042 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6043 CallingConv::C, I.getType(), 6044 DAG.getExternalSymbol(TrapFuncName.data(), 6045 TLI.getPointerTy(DAG.getDataLayout())), 6046 std::move(Args)); 6047 6048 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6049 DAG.setRoot(Result.second); 6050 return nullptr; 6051 } 6052 6053 case Intrinsic::uadd_with_overflow: 6054 case Intrinsic::sadd_with_overflow: 6055 case Intrinsic::usub_with_overflow: 6056 case Intrinsic::ssub_with_overflow: 6057 case Intrinsic::umul_with_overflow: 6058 case Intrinsic::smul_with_overflow: { 6059 ISD::NodeType Op; 6060 switch (Intrinsic) { 6061 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6062 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6063 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6064 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6065 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6066 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6067 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6068 } 6069 SDValue Op1 = getValue(I.getArgOperand(0)); 6070 SDValue Op2 = getValue(I.getArgOperand(1)); 6071 6072 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 6073 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6074 return nullptr; 6075 } 6076 case Intrinsic::prefetch: { 6077 SDValue Ops[5]; 6078 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6079 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6080 Ops[0] = DAG.getRoot(); 6081 Ops[1] = getValue(I.getArgOperand(0)); 6082 Ops[2] = getValue(I.getArgOperand(1)); 6083 Ops[3] = getValue(I.getArgOperand(2)); 6084 Ops[4] = getValue(I.getArgOperand(3)); 6085 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6086 DAG.getVTList(MVT::Other), Ops, 6087 EVT::getIntegerVT(*Context, 8), 6088 MachinePointerInfo(I.getArgOperand(0)), 6089 0, /* align */ 6090 Flags); 6091 6092 // Chain the prefetch in parallell with any pending loads, to stay out of 6093 // the way of later optimizations. 6094 PendingLoads.push_back(Result); 6095 Result = getRoot(); 6096 DAG.setRoot(Result); 6097 return nullptr; 6098 } 6099 case Intrinsic::lifetime_start: 6100 case Intrinsic::lifetime_end: { 6101 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6102 // Stack coloring is not enabled in O0, discard region information. 6103 if (TM.getOptLevel() == CodeGenOpt::None) 6104 return nullptr; 6105 6106 SmallVector<Value *, 4> Allocas; 6107 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 6108 6109 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 6110 E = Allocas.end(); Object != E; ++Object) { 6111 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6112 6113 // Could not find an Alloca. 6114 if (!LifetimeObject) 6115 continue; 6116 6117 // First check that the Alloca is static, otherwise it won't have a 6118 // valid frame index. 6119 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6120 if (SI == FuncInfo.StaticAllocaMap.end()) 6121 return nullptr; 6122 6123 int FI = SI->second; 6124 6125 SDValue Ops[2]; 6126 Ops[0] = getRoot(); 6127 Ops[1] = 6128 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 6129 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 6130 6131 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 6132 DAG.setRoot(Res); 6133 } 6134 return nullptr; 6135 } 6136 case Intrinsic::invariant_start: 6137 // Discard region information. 6138 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6139 return nullptr; 6140 case Intrinsic::invariant_end: 6141 // Discard region information. 6142 return nullptr; 6143 case Intrinsic::clear_cache: 6144 return TLI.getClearCacheBuiltinName(); 6145 case Intrinsic::donothing: 6146 // ignore 6147 return nullptr; 6148 case Intrinsic::experimental_stackmap: 6149 visitStackmap(I); 6150 return nullptr; 6151 case Intrinsic::experimental_patchpoint_void: 6152 case Intrinsic::experimental_patchpoint_i64: 6153 visitPatchpoint(&I); 6154 return nullptr; 6155 case Intrinsic::experimental_gc_statepoint: 6156 LowerStatepoint(ImmutableStatepoint(&I)); 6157 return nullptr; 6158 case Intrinsic::experimental_gc_result: 6159 visitGCResult(cast<GCResultInst>(I)); 6160 return nullptr; 6161 case Intrinsic::experimental_gc_relocate: 6162 visitGCRelocate(cast<GCRelocateInst>(I)); 6163 return nullptr; 6164 case Intrinsic::instrprof_increment: 6165 llvm_unreachable("instrprof failed to lower an increment"); 6166 case Intrinsic::instrprof_value_profile: 6167 llvm_unreachable("instrprof failed to lower a value profiling call"); 6168 case Intrinsic::localescape: { 6169 MachineFunction &MF = DAG.getMachineFunction(); 6170 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6171 6172 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6173 // is the same on all targets. 6174 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6175 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6176 if (isa<ConstantPointerNull>(Arg)) 6177 continue; // Skip null pointers. They represent a hole in index space. 6178 AllocaInst *Slot = cast<AllocaInst>(Arg); 6179 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6180 "can only escape static allocas"); 6181 int FI = FuncInfo.StaticAllocaMap[Slot]; 6182 MCSymbol *FrameAllocSym = 6183 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6184 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6185 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6186 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6187 .addSym(FrameAllocSym) 6188 .addFrameIndex(FI); 6189 } 6190 6191 return nullptr; 6192 } 6193 6194 case Intrinsic::localrecover: { 6195 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6196 MachineFunction &MF = DAG.getMachineFunction(); 6197 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6198 6199 // Get the symbol that defines the frame offset. 6200 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6201 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6202 unsigned IdxVal = 6203 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6204 MCSymbol *FrameAllocSym = 6205 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6206 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6207 6208 // Create a MCSymbol for the label to avoid any target lowering 6209 // that would make this PC relative. 6210 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6211 SDValue OffsetVal = 6212 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6213 6214 // Add the offset to the FP. 6215 Value *FP = I.getArgOperand(1); 6216 SDValue FPVal = getValue(FP); 6217 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6218 setValue(&I, Add); 6219 6220 return nullptr; 6221 } 6222 6223 case Intrinsic::eh_exceptionpointer: 6224 case Intrinsic::eh_exceptioncode: { 6225 // Get the exception pointer vreg, copy from it, and resize it to fit. 6226 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6227 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6228 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6229 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6230 SDValue N = 6231 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6232 if (Intrinsic == Intrinsic::eh_exceptioncode) 6233 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6234 setValue(&I, N); 6235 return nullptr; 6236 } 6237 case Intrinsic::xray_customevent: { 6238 // Here we want to make sure that the intrinsic behaves as if it has a 6239 // specific calling convention, and only for x86_64. 6240 // FIXME: Support other platforms later. 6241 const auto &Triple = DAG.getTarget().getTargetTriple(); 6242 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6243 return nullptr; 6244 6245 SDLoc DL = getCurSDLoc(); 6246 SmallVector<SDValue, 8> Ops; 6247 6248 // We want to say that we always want the arguments in registers. 6249 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6250 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6251 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6252 SDValue Chain = getRoot(); 6253 Ops.push_back(LogEntryVal); 6254 Ops.push_back(StrSizeVal); 6255 Ops.push_back(Chain); 6256 6257 // We need to enforce the calling convention for the callsite, so that 6258 // argument ordering is enforced correctly, and that register allocation can 6259 // see that some registers may be assumed clobbered and have to preserve 6260 // them across calls to the intrinsic. 6261 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6262 DL, NodeTys, Ops); 6263 SDValue patchableNode = SDValue(MN, 0); 6264 DAG.setRoot(patchableNode); 6265 setValue(&I, patchableNode); 6266 return nullptr; 6267 } 6268 case Intrinsic::xray_typedevent: { 6269 // Here we want to make sure that the intrinsic behaves as if it has a 6270 // specific calling convention, and only for x86_64. 6271 // FIXME: Support other platforms later. 6272 const auto &Triple = DAG.getTarget().getTargetTriple(); 6273 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6274 return nullptr; 6275 6276 SDLoc DL = getCurSDLoc(); 6277 SmallVector<SDValue, 8> Ops; 6278 6279 // We want to say that we always want the arguments in registers. 6280 // It's unclear to me how manipulating the selection DAG here forces callers 6281 // to provide arguments in registers instead of on the stack. 6282 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6283 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6284 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6285 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6286 SDValue Chain = getRoot(); 6287 Ops.push_back(LogTypeId); 6288 Ops.push_back(LogEntryVal); 6289 Ops.push_back(StrSizeVal); 6290 Ops.push_back(Chain); 6291 6292 // We need to enforce the calling convention for the callsite, so that 6293 // argument ordering is enforced correctly, and that register allocation can 6294 // see that some registers may be assumed clobbered and have to preserve 6295 // them across calls to the intrinsic. 6296 MachineSDNode *MN = DAG.getMachineNode( 6297 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6298 SDValue patchableNode = SDValue(MN, 0); 6299 DAG.setRoot(patchableNode); 6300 setValue(&I, patchableNode); 6301 return nullptr; 6302 } 6303 case Intrinsic::experimental_deoptimize: 6304 LowerDeoptimizeCall(&I); 6305 return nullptr; 6306 6307 case Intrinsic::experimental_vector_reduce_fadd: 6308 case Intrinsic::experimental_vector_reduce_fmul: 6309 case Intrinsic::experimental_vector_reduce_add: 6310 case Intrinsic::experimental_vector_reduce_mul: 6311 case Intrinsic::experimental_vector_reduce_and: 6312 case Intrinsic::experimental_vector_reduce_or: 6313 case Intrinsic::experimental_vector_reduce_xor: 6314 case Intrinsic::experimental_vector_reduce_smax: 6315 case Intrinsic::experimental_vector_reduce_smin: 6316 case Intrinsic::experimental_vector_reduce_umax: 6317 case Intrinsic::experimental_vector_reduce_umin: 6318 case Intrinsic::experimental_vector_reduce_fmax: 6319 case Intrinsic::experimental_vector_reduce_fmin: 6320 visitVectorReduce(I, Intrinsic); 6321 return nullptr; 6322 6323 case Intrinsic::icall_branch_funnel: { 6324 SmallVector<SDValue, 16> Ops; 6325 Ops.push_back(DAG.getRoot()); 6326 Ops.push_back(getValue(I.getArgOperand(0))); 6327 6328 int64_t Offset; 6329 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6330 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6331 if (!Base) 6332 report_fatal_error( 6333 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6334 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6335 6336 struct BranchFunnelTarget { 6337 int64_t Offset; 6338 SDValue Target; 6339 }; 6340 SmallVector<BranchFunnelTarget, 8> Targets; 6341 6342 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6343 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6344 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6345 if (ElemBase != Base) 6346 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6347 "to the same GlobalValue"); 6348 6349 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6350 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6351 if (!GA) 6352 report_fatal_error( 6353 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6354 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6355 GA->getGlobal(), getCurSDLoc(), 6356 Val.getValueType(), GA->getOffset())}); 6357 } 6358 llvm::sort(Targets, 6359 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6360 return T1.Offset < T2.Offset; 6361 }); 6362 6363 for (auto &T : Targets) { 6364 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6365 Ops.push_back(T.Target); 6366 } 6367 6368 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6369 getCurSDLoc(), MVT::Other, Ops), 6370 0); 6371 DAG.setRoot(N); 6372 setValue(&I, N); 6373 HasTailCall = true; 6374 return nullptr; 6375 } 6376 6377 case Intrinsic::wasm_landingpad_index: 6378 // Information this intrinsic contained has been transferred to 6379 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6380 // delete it now. 6381 return nullptr; 6382 } 6383 } 6384 6385 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6386 const ConstrainedFPIntrinsic &FPI) { 6387 SDLoc sdl = getCurSDLoc(); 6388 unsigned Opcode; 6389 switch (FPI.getIntrinsicID()) { 6390 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6391 case Intrinsic::experimental_constrained_fadd: 6392 Opcode = ISD::STRICT_FADD; 6393 break; 6394 case Intrinsic::experimental_constrained_fsub: 6395 Opcode = ISD::STRICT_FSUB; 6396 break; 6397 case Intrinsic::experimental_constrained_fmul: 6398 Opcode = ISD::STRICT_FMUL; 6399 break; 6400 case Intrinsic::experimental_constrained_fdiv: 6401 Opcode = ISD::STRICT_FDIV; 6402 break; 6403 case Intrinsic::experimental_constrained_frem: 6404 Opcode = ISD::STRICT_FREM; 6405 break; 6406 case Intrinsic::experimental_constrained_fma: 6407 Opcode = ISD::STRICT_FMA; 6408 break; 6409 case Intrinsic::experimental_constrained_sqrt: 6410 Opcode = ISD::STRICT_FSQRT; 6411 break; 6412 case Intrinsic::experimental_constrained_pow: 6413 Opcode = ISD::STRICT_FPOW; 6414 break; 6415 case Intrinsic::experimental_constrained_powi: 6416 Opcode = ISD::STRICT_FPOWI; 6417 break; 6418 case Intrinsic::experimental_constrained_sin: 6419 Opcode = ISD::STRICT_FSIN; 6420 break; 6421 case Intrinsic::experimental_constrained_cos: 6422 Opcode = ISD::STRICT_FCOS; 6423 break; 6424 case Intrinsic::experimental_constrained_exp: 6425 Opcode = ISD::STRICT_FEXP; 6426 break; 6427 case Intrinsic::experimental_constrained_exp2: 6428 Opcode = ISD::STRICT_FEXP2; 6429 break; 6430 case Intrinsic::experimental_constrained_log: 6431 Opcode = ISD::STRICT_FLOG; 6432 break; 6433 case Intrinsic::experimental_constrained_log10: 6434 Opcode = ISD::STRICT_FLOG10; 6435 break; 6436 case Intrinsic::experimental_constrained_log2: 6437 Opcode = ISD::STRICT_FLOG2; 6438 break; 6439 case Intrinsic::experimental_constrained_rint: 6440 Opcode = ISD::STRICT_FRINT; 6441 break; 6442 case Intrinsic::experimental_constrained_nearbyint: 6443 Opcode = ISD::STRICT_FNEARBYINT; 6444 break; 6445 case Intrinsic::experimental_constrained_maxnum: 6446 Opcode = ISD::STRICT_FMAXNUM; 6447 break; 6448 case Intrinsic::experimental_constrained_minnum: 6449 Opcode = ISD::STRICT_FMINNUM; 6450 break; 6451 case Intrinsic::experimental_constrained_ceil: 6452 Opcode = ISD::STRICT_FCEIL; 6453 break; 6454 case Intrinsic::experimental_constrained_floor: 6455 Opcode = ISD::STRICT_FFLOOR; 6456 break; 6457 case Intrinsic::experimental_constrained_round: 6458 Opcode = ISD::STRICT_FROUND; 6459 break; 6460 case Intrinsic::experimental_constrained_trunc: 6461 Opcode = ISD::STRICT_FTRUNC; 6462 break; 6463 } 6464 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6465 SDValue Chain = getRoot(); 6466 SmallVector<EVT, 4> ValueVTs; 6467 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6468 ValueVTs.push_back(MVT::Other); // Out chain 6469 6470 SDVTList VTs = DAG.getVTList(ValueVTs); 6471 SDValue Result; 6472 if (FPI.isUnaryOp()) 6473 Result = DAG.getNode(Opcode, sdl, VTs, 6474 { Chain, getValue(FPI.getArgOperand(0)) }); 6475 else if (FPI.isTernaryOp()) 6476 Result = DAG.getNode(Opcode, sdl, VTs, 6477 { Chain, getValue(FPI.getArgOperand(0)), 6478 getValue(FPI.getArgOperand(1)), 6479 getValue(FPI.getArgOperand(2)) }); 6480 else 6481 Result = DAG.getNode(Opcode, sdl, VTs, 6482 { Chain, getValue(FPI.getArgOperand(0)), 6483 getValue(FPI.getArgOperand(1)) }); 6484 6485 assert(Result.getNode()->getNumValues() == 2); 6486 SDValue OutChain = Result.getValue(1); 6487 DAG.setRoot(OutChain); 6488 SDValue FPResult = Result.getValue(0); 6489 setValue(&FPI, FPResult); 6490 } 6491 6492 std::pair<SDValue, SDValue> 6493 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6494 const BasicBlock *EHPadBB) { 6495 MachineFunction &MF = DAG.getMachineFunction(); 6496 MachineModuleInfo &MMI = MF.getMMI(); 6497 MCSymbol *BeginLabel = nullptr; 6498 6499 if (EHPadBB) { 6500 // Insert a label before the invoke call to mark the try range. This can be 6501 // used to detect deletion of the invoke via the MachineModuleInfo. 6502 BeginLabel = MMI.getContext().createTempSymbol(); 6503 6504 // For SjLj, keep track of which landing pads go with which invokes 6505 // so as to maintain the ordering of pads in the LSDA. 6506 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6507 if (CallSiteIndex) { 6508 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6509 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6510 6511 // Now that the call site is handled, stop tracking it. 6512 MMI.setCurrentCallSite(0); 6513 } 6514 6515 // Both PendingLoads and PendingExports must be flushed here; 6516 // this call might not return. 6517 (void)getRoot(); 6518 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6519 6520 CLI.setChain(getRoot()); 6521 } 6522 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6523 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6524 6525 assert((CLI.IsTailCall || Result.second.getNode()) && 6526 "Non-null chain expected with non-tail call!"); 6527 assert((Result.second.getNode() || !Result.first.getNode()) && 6528 "Null value expected with tail call!"); 6529 6530 if (!Result.second.getNode()) { 6531 // As a special case, a null chain means that a tail call has been emitted 6532 // and the DAG root is already updated. 6533 HasTailCall = true; 6534 6535 // Since there's no actual continuation from this block, nothing can be 6536 // relying on us setting vregs for them. 6537 PendingExports.clear(); 6538 } else { 6539 DAG.setRoot(Result.second); 6540 } 6541 6542 if (EHPadBB) { 6543 // Insert a label at the end of the invoke call to mark the try range. This 6544 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6545 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6546 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6547 6548 // Inform MachineModuleInfo of range. 6549 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6550 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6551 // actually use outlined funclets and their LSDA info style. 6552 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6553 assert(CLI.CS); 6554 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6555 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6556 BeginLabel, EndLabel); 6557 } else if (!isScopedEHPersonality(Pers)) { 6558 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6559 } 6560 } 6561 6562 return Result; 6563 } 6564 6565 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6566 bool isTailCall, 6567 const BasicBlock *EHPadBB) { 6568 auto &DL = DAG.getDataLayout(); 6569 FunctionType *FTy = CS.getFunctionType(); 6570 Type *RetTy = CS.getType(); 6571 6572 TargetLowering::ArgListTy Args; 6573 Args.reserve(CS.arg_size()); 6574 6575 const Value *SwiftErrorVal = nullptr; 6576 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6577 6578 // We can't tail call inside a function with a swifterror argument. Lowering 6579 // does not support this yet. It would have to move into the swifterror 6580 // register before the call. 6581 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6582 if (TLI.supportSwiftError() && 6583 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6584 isTailCall = false; 6585 6586 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6587 i != e; ++i) { 6588 TargetLowering::ArgListEntry Entry; 6589 const Value *V = *i; 6590 6591 // Skip empty types 6592 if (V->getType()->isEmptyTy()) 6593 continue; 6594 6595 SDValue ArgNode = getValue(V); 6596 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6597 6598 Entry.setAttributes(&CS, i - CS.arg_begin()); 6599 6600 // Use swifterror virtual register as input to the call. 6601 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6602 SwiftErrorVal = V; 6603 // We find the virtual register for the actual swifterror argument. 6604 // Instead of using the Value, we use the virtual register instead. 6605 Entry.Node = DAG.getRegister(FuncInfo 6606 .getOrCreateSwiftErrorVRegUseAt( 6607 CS.getInstruction(), FuncInfo.MBB, V) 6608 .first, 6609 EVT(TLI.getPointerTy(DL))); 6610 } 6611 6612 Args.push_back(Entry); 6613 6614 // If we have an explicit sret argument that is an Instruction, (i.e., it 6615 // might point to function-local memory), we can't meaningfully tail-call. 6616 if (Entry.IsSRet && isa<Instruction>(V)) 6617 isTailCall = false; 6618 } 6619 6620 // Check if target-independent constraints permit a tail call here. 6621 // Target-dependent constraints are checked within TLI->LowerCallTo. 6622 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6623 isTailCall = false; 6624 6625 // Disable tail calls if there is an swifterror argument. Targets have not 6626 // been updated to support tail calls. 6627 if (TLI.supportSwiftError() && SwiftErrorVal) 6628 isTailCall = false; 6629 6630 TargetLowering::CallLoweringInfo CLI(DAG); 6631 CLI.setDebugLoc(getCurSDLoc()) 6632 .setChain(getRoot()) 6633 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6634 .setTailCall(isTailCall) 6635 .setConvergent(CS.isConvergent()); 6636 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6637 6638 if (Result.first.getNode()) { 6639 const Instruction *Inst = CS.getInstruction(); 6640 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6641 setValue(Inst, Result.first); 6642 } 6643 6644 // The last element of CLI.InVals has the SDValue for swifterror return. 6645 // Here we copy it to a virtual register and update SwiftErrorMap for 6646 // book-keeping. 6647 if (SwiftErrorVal && TLI.supportSwiftError()) { 6648 // Get the last element of InVals. 6649 SDValue Src = CLI.InVals.back(); 6650 unsigned VReg; bool CreatedVReg; 6651 std::tie(VReg, CreatedVReg) = 6652 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6653 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6654 // We update the virtual register for the actual swifterror argument. 6655 if (CreatedVReg) 6656 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6657 DAG.setRoot(CopyNode); 6658 } 6659 } 6660 6661 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6662 SelectionDAGBuilder &Builder) { 6663 // Check to see if this load can be trivially constant folded, e.g. if the 6664 // input is from a string literal. 6665 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6666 // Cast pointer to the type we really want to load. 6667 Type *LoadTy = 6668 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6669 if (LoadVT.isVector()) 6670 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6671 6672 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6673 PointerType::getUnqual(LoadTy)); 6674 6675 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6676 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6677 return Builder.getValue(LoadCst); 6678 } 6679 6680 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6681 // still constant memory, the input chain can be the entry node. 6682 SDValue Root; 6683 bool ConstantMemory = false; 6684 6685 // Do not serialize (non-volatile) loads of constant memory with anything. 6686 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6687 Root = Builder.DAG.getEntryNode(); 6688 ConstantMemory = true; 6689 } else { 6690 // Do not serialize non-volatile loads against each other. 6691 Root = Builder.DAG.getRoot(); 6692 } 6693 6694 SDValue Ptr = Builder.getValue(PtrVal); 6695 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6696 Ptr, MachinePointerInfo(PtrVal), 6697 /* Alignment = */ 1); 6698 6699 if (!ConstantMemory) 6700 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6701 return LoadVal; 6702 } 6703 6704 /// Record the value for an instruction that produces an integer result, 6705 /// converting the type where necessary. 6706 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6707 SDValue Value, 6708 bool IsSigned) { 6709 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6710 I.getType(), true); 6711 if (IsSigned) 6712 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6713 else 6714 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6715 setValue(&I, Value); 6716 } 6717 6718 /// See if we can lower a memcmp call into an optimized form. If so, return 6719 /// true and lower it. Otherwise return false, and it will be lowered like a 6720 /// normal call. 6721 /// The caller already checked that \p I calls the appropriate LibFunc with a 6722 /// correct prototype. 6723 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6724 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6725 const Value *Size = I.getArgOperand(2); 6726 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6727 if (CSize && CSize->getZExtValue() == 0) { 6728 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6729 I.getType(), true); 6730 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6731 return true; 6732 } 6733 6734 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6735 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6736 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6737 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6738 if (Res.first.getNode()) { 6739 processIntegerCallValue(I, Res.first, true); 6740 PendingLoads.push_back(Res.second); 6741 return true; 6742 } 6743 6744 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6745 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6746 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6747 return false; 6748 6749 // If the target has a fast compare for the given size, it will return a 6750 // preferred load type for that size. Require that the load VT is legal and 6751 // that the target supports unaligned loads of that type. Otherwise, return 6752 // INVALID. 6753 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6754 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6755 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6756 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6757 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6758 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6759 // TODO: Check alignment of src and dest ptrs. 6760 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6761 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6762 if (!TLI.isTypeLegal(LVT) || 6763 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6764 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6765 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6766 } 6767 6768 return LVT; 6769 }; 6770 6771 // This turns into unaligned loads. We only do this if the target natively 6772 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6773 // we'll only produce a small number of byte loads. 6774 MVT LoadVT; 6775 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6776 switch (NumBitsToCompare) { 6777 default: 6778 return false; 6779 case 16: 6780 LoadVT = MVT::i16; 6781 break; 6782 case 32: 6783 LoadVT = MVT::i32; 6784 break; 6785 case 64: 6786 case 128: 6787 case 256: 6788 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6789 break; 6790 } 6791 6792 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6793 return false; 6794 6795 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6796 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6797 6798 // Bitcast to a wide integer type if the loads are vectors. 6799 if (LoadVT.isVector()) { 6800 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6801 LoadL = DAG.getBitcast(CmpVT, LoadL); 6802 LoadR = DAG.getBitcast(CmpVT, LoadR); 6803 } 6804 6805 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6806 processIntegerCallValue(I, Cmp, false); 6807 return true; 6808 } 6809 6810 /// See if we can lower a memchr call into an optimized form. If so, return 6811 /// true and lower it. Otherwise return false, and it will be lowered like a 6812 /// normal call. 6813 /// The caller already checked that \p I calls the appropriate LibFunc with a 6814 /// correct prototype. 6815 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6816 const Value *Src = I.getArgOperand(0); 6817 const Value *Char = I.getArgOperand(1); 6818 const Value *Length = I.getArgOperand(2); 6819 6820 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6821 std::pair<SDValue, SDValue> Res = 6822 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6823 getValue(Src), getValue(Char), getValue(Length), 6824 MachinePointerInfo(Src)); 6825 if (Res.first.getNode()) { 6826 setValue(&I, Res.first); 6827 PendingLoads.push_back(Res.second); 6828 return true; 6829 } 6830 6831 return false; 6832 } 6833 6834 /// See if we can lower a mempcpy call into an optimized form. If so, return 6835 /// true and lower it. Otherwise return false, and it will be lowered like a 6836 /// normal call. 6837 /// The caller already checked that \p I calls the appropriate LibFunc with a 6838 /// correct prototype. 6839 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6840 SDValue Dst = getValue(I.getArgOperand(0)); 6841 SDValue Src = getValue(I.getArgOperand(1)); 6842 SDValue Size = getValue(I.getArgOperand(2)); 6843 6844 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6845 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6846 unsigned Align = std::min(DstAlign, SrcAlign); 6847 if (Align == 0) // Alignment of one or both could not be inferred. 6848 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6849 6850 bool isVol = false; 6851 SDLoc sdl = getCurSDLoc(); 6852 6853 // In the mempcpy context we need to pass in a false value for isTailCall 6854 // because the return pointer needs to be adjusted by the size of 6855 // the copied memory. 6856 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6857 false, /*isTailCall=*/false, 6858 MachinePointerInfo(I.getArgOperand(0)), 6859 MachinePointerInfo(I.getArgOperand(1))); 6860 assert(MC.getNode() != nullptr && 6861 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6862 DAG.setRoot(MC); 6863 6864 // Check if Size needs to be truncated or extended. 6865 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6866 6867 // Adjust return pointer to point just past the last dst byte. 6868 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6869 Dst, Size); 6870 setValue(&I, DstPlusSize); 6871 return true; 6872 } 6873 6874 /// See if we can lower a strcpy call into an optimized form. If so, return 6875 /// true and lower it, otherwise return false and it will be lowered like a 6876 /// normal call. 6877 /// The caller already checked that \p I calls the appropriate LibFunc with a 6878 /// correct prototype. 6879 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6880 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6881 6882 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6883 std::pair<SDValue, SDValue> Res = 6884 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6885 getValue(Arg0), getValue(Arg1), 6886 MachinePointerInfo(Arg0), 6887 MachinePointerInfo(Arg1), isStpcpy); 6888 if (Res.first.getNode()) { 6889 setValue(&I, Res.first); 6890 DAG.setRoot(Res.second); 6891 return true; 6892 } 6893 6894 return false; 6895 } 6896 6897 /// See if we can lower a strcmp call into an optimized form. If so, return 6898 /// true and lower it, otherwise return false and it will be lowered like a 6899 /// normal call. 6900 /// The caller already checked that \p I calls the appropriate LibFunc with a 6901 /// correct prototype. 6902 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6903 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6904 6905 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6906 std::pair<SDValue, SDValue> Res = 6907 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6908 getValue(Arg0), getValue(Arg1), 6909 MachinePointerInfo(Arg0), 6910 MachinePointerInfo(Arg1)); 6911 if (Res.first.getNode()) { 6912 processIntegerCallValue(I, Res.first, true); 6913 PendingLoads.push_back(Res.second); 6914 return true; 6915 } 6916 6917 return false; 6918 } 6919 6920 /// See if we can lower a strlen call into an optimized form. If so, return 6921 /// true and lower it, otherwise return false and it will be lowered like a 6922 /// normal call. 6923 /// The caller already checked that \p I calls the appropriate LibFunc with a 6924 /// correct prototype. 6925 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6926 const Value *Arg0 = I.getArgOperand(0); 6927 6928 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6929 std::pair<SDValue, SDValue> Res = 6930 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6931 getValue(Arg0), MachinePointerInfo(Arg0)); 6932 if (Res.first.getNode()) { 6933 processIntegerCallValue(I, Res.first, false); 6934 PendingLoads.push_back(Res.second); 6935 return true; 6936 } 6937 6938 return false; 6939 } 6940 6941 /// See if we can lower a strnlen call into an optimized form. If so, return 6942 /// true and lower it, otherwise return false and it will be lowered like a 6943 /// normal call. 6944 /// The caller already checked that \p I calls the appropriate LibFunc with a 6945 /// correct prototype. 6946 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6947 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6948 6949 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6950 std::pair<SDValue, SDValue> Res = 6951 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6952 getValue(Arg0), getValue(Arg1), 6953 MachinePointerInfo(Arg0)); 6954 if (Res.first.getNode()) { 6955 processIntegerCallValue(I, Res.first, false); 6956 PendingLoads.push_back(Res.second); 6957 return true; 6958 } 6959 6960 return false; 6961 } 6962 6963 /// See if we can lower a unary floating-point operation into an SDNode with 6964 /// the specified Opcode. If so, return true and lower it, otherwise return 6965 /// false and it will be lowered like a normal call. 6966 /// The caller already checked that \p I calls the appropriate LibFunc with a 6967 /// correct prototype. 6968 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6969 unsigned Opcode) { 6970 // We already checked this call's prototype; verify it doesn't modify errno. 6971 if (!I.onlyReadsMemory()) 6972 return false; 6973 6974 SDValue Tmp = getValue(I.getArgOperand(0)); 6975 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6976 return true; 6977 } 6978 6979 /// See if we can lower a binary floating-point operation into an SDNode with 6980 /// the specified Opcode. If so, return true and lower it. Otherwise return 6981 /// false, and it will be lowered like a normal call. 6982 /// The caller already checked that \p I calls the appropriate LibFunc with a 6983 /// correct prototype. 6984 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6985 unsigned Opcode) { 6986 // We already checked this call's prototype; verify it doesn't modify errno. 6987 if (!I.onlyReadsMemory()) 6988 return false; 6989 6990 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6991 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6992 EVT VT = Tmp0.getValueType(); 6993 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6994 return true; 6995 } 6996 6997 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6998 // Handle inline assembly differently. 6999 if (isa<InlineAsm>(I.getCalledValue())) { 7000 visitInlineAsm(&I); 7001 return; 7002 } 7003 7004 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 7005 computeUsesVAFloatArgument(I, MMI); 7006 7007 const char *RenameFn = nullptr; 7008 if (Function *F = I.getCalledFunction()) { 7009 if (F->isDeclaration()) { 7010 // Is this an LLVM intrinsic or a target-specific intrinsic? 7011 unsigned IID = F->getIntrinsicID(); 7012 if (!IID) 7013 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7014 IID = II->getIntrinsicID(F); 7015 7016 if (IID) { 7017 RenameFn = visitIntrinsicCall(I, IID); 7018 if (!RenameFn) 7019 return; 7020 } 7021 } 7022 7023 // Check for well-known libc/libm calls. If the function is internal, it 7024 // can't be a library call. Don't do the check if marked as nobuiltin for 7025 // some reason or the call site requires strict floating point semantics. 7026 LibFunc Func; 7027 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7028 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7029 LibInfo->hasOptimizedCodeGen(Func)) { 7030 switch (Func) { 7031 default: break; 7032 case LibFunc_copysign: 7033 case LibFunc_copysignf: 7034 case LibFunc_copysignl: 7035 // We already checked this call's prototype; verify it doesn't modify 7036 // errno. 7037 if (I.onlyReadsMemory()) { 7038 SDValue LHS = getValue(I.getArgOperand(0)); 7039 SDValue RHS = getValue(I.getArgOperand(1)); 7040 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7041 LHS.getValueType(), LHS, RHS)); 7042 return; 7043 } 7044 break; 7045 case LibFunc_fabs: 7046 case LibFunc_fabsf: 7047 case LibFunc_fabsl: 7048 if (visitUnaryFloatCall(I, ISD::FABS)) 7049 return; 7050 break; 7051 case LibFunc_fmin: 7052 case LibFunc_fminf: 7053 case LibFunc_fminl: 7054 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7055 return; 7056 break; 7057 case LibFunc_fmax: 7058 case LibFunc_fmaxf: 7059 case LibFunc_fmaxl: 7060 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7061 return; 7062 break; 7063 case LibFunc_sin: 7064 case LibFunc_sinf: 7065 case LibFunc_sinl: 7066 if (visitUnaryFloatCall(I, ISD::FSIN)) 7067 return; 7068 break; 7069 case LibFunc_cos: 7070 case LibFunc_cosf: 7071 case LibFunc_cosl: 7072 if (visitUnaryFloatCall(I, ISD::FCOS)) 7073 return; 7074 break; 7075 case LibFunc_sqrt: 7076 case LibFunc_sqrtf: 7077 case LibFunc_sqrtl: 7078 case LibFunc_sqrt_finite: 7079 case LibFunc_sqrtf_finite: 7080 case LibFunc_sqrtl_finite: 7081 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7082 return; 7083 break; 7084 case LibFunc_floor: 7085 case LibFunc_floorf: 7086 case LibFunc_floorl: 7087 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7088 return; 7089 break; 7090 case LibFunc_nearbyint: 7091 case LibFunc_nearbyintf: 7092 case LibFunc_nearbyintl: 7093 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7094 return; 7095 break; 7096 case LibFunc_ceil: 7097 case LibFunc_ceilf: 7098 case LibFunc_ceill: 7099 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7100 return; 7101 break; 7102 case LibFunc_rint: 7103 case LibFunc_rintf: 7104 case LibFunc_rintl: 7105 if (visitUnaryFloatCall(I, ISD::FRINT)) 7106 return; 7107 break; 7108 case LibFunc_round: 7109 case LibFunc_roundf: 7110 case LibFunc_roundl: 7111 if (visitUnaryFloatCall(I, ISD::FROUND)) 7112 return; 7113 break; 7114 case LibFunc_trunc: 7115 case LibFunc_truncf: 7116 case LibFunc_truncl: 7117 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7118 return; 7119 break; 7120 case LibFunc_log2: 7121 case LibFunc_log2f: 7122 case LibFunc_log2l: 7123 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7124 return; 7125 break; 7126 case LibFunc_exp2: 7127 case LibFunc_exp2f: 7128 case LibFunc_exp2l: 7129 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7130 return; 7131 break; 7132 case LibFunc_memcmp: 7133 if (visitMemCmpCall(I)) 7134 return; 7135 break; 7136 case LibFunc_mempcpy: 7137 if (visitMemPCpyCall(I)) 7138 return; 7139 break; 7140 case LibFunc_memchr: 7141 if (visitMemChrCall(I)) 7142 return; 7143 break; 7144 case LibFunc_strcpy: 7145 if (visitStrCpyCall(I, false)) 7146 return; 7147 break; 7148 case LibFunc_stpcpy: 7149 if (visitStrCpyCall(I, true)) 7150 return; 7151 break; 7152 case LibFunc_strcmp: 7153 if (visitStrCmpCall(I)) 7154 return; 7155 break; 7156 case LibFunc_strlen: 7157 if (visitStrLenCall(I)) 7158 return; 7159 break; 7160 case LibFunc_strnlen: 7161 if (visitStrNLenCall(I)) 7162 return; 7163 break; 7164 } 7165 } 7166 } 7167 7168 SDValue Callee; 7169 if (!RenameFn) 7170 Callee = getValue(I.getCalledValue()); 7171 else 7172 Callee = DAG.getExternalSymbol( 7173 RenameFn, 7174 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7175 7176 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7177 // have to do anything here to lower funclet bundles. 7178 assert(!I.hasOperandBundlesOtherThan( 7179 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7180 "Cannot lower calls with arbitrary operand bundles!"); 7181 7182 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7183 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7184 else 7185 // Check if we can potentially perform a tail call. More detailed checking 7186 // is be done within LowerCallTo, after more information about the call is 7187 // known. 7188 LowerCallTo(&I, Callee, I.isTailCall()); 7189 } 7190 7191 namespace { 7192 7193 /// AsmOperandInfo - This contains information for each constraint that we are 7194 /// lowering. 7195 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7196 public: 7197 /// CallOperand - If this is the result output operand or a clobber 7198 /// this is null, otherwise it is the incoming operand to the CallInst. 7199 /// This gets modified as the asm is processed. 7200 SDValue CallOperand; 7201 7202 /// AssignedRegs - If this is a register or register class operand, this 7203 /// contains the set of register corresponding to the operand. 7204 RegsForValue AssignedRegs; 7205 7206 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7207 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7208 } 7209 7210 /// Whether or not this operand accesses memory 7211 bool hasMemory(const TargetLowering &TLI) const { 7212 // Indirect operand accesses access memory. 7213 if (isIndirect) 7214 return true; 7215 7216 for (const auto &Code : Codes) 7217 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7218 return true; 7219 7220 return false; 7221 } 7222 7223 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7224 /// corresponds to. If there is no Value* for this operand, it returns 7225 /// MVT::Other. 7226 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7227 const DataLayout &DL) const { 7228 if (!CallOperandVal) return MVT::Other; 7229 7230 if (isa<BasicBlock>(CallOperandVal)) 7231 return TLI.getPointerTy(DL); 7232 7233 llvm::Type *OpTy = CallOperandVal->getType(); 7234 7235 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7236 // If this is an indirect operand, the operand is a pointer to the 7237 // accessed type. 7238 if (isIndirect) { 7239 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7240 if (!PtrTy) 7241 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7242 OpTy = PtrTy->getElementType(); 7243 } 7244 7245 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7246 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7247 if (STy->getNumElements() == 1) 7248 OpTy = STy->getElementType(0); 7249 7250 // If OpTy is not a single value, it may be a struct/union that we 7251 // can tile with integers. 7252 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7253 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7254 switch (BitSize) { 7255 default: break; 7256 case 1: 7257 case 8: 7258 case 16: 7259 case 32: 7260 case 64: 7261 case 128: 7262 OpTy = IntegerType::get(Context, BitSize); 7263 break; 7264 } 7265 } 7266 7267 return TLI.getValueType(DL, OpTy, true); 7268 } 7269 }; 7270 7271 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7272 7273 } // end anonymous namespace 7274 7275 /// Make sure that the output operand \p OpInfo and its corresponding input 7276 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7277 /// out). 7278 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7279 SDISelAsmOperandInfo &MatchingOpInfo, 7280 SelectionDAG &DAG) { 7281 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7282 return; 7283 7284 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7285 const auto &TLI = DAG.getTargetLoweringInfo(); 7286 7287 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7288 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7289 OpInfo.ConstraintVT); 7290 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7291 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7292 MatchingOpInfo.ConstraintVT); 7293 if ((OpInfo.ConstraintVT.isInteger() != 7294 MatchingOpInfo.ConstraintVT.isInteger()) || 7295 (MatchRC.second != InputRC.second)) { 7296 // FIXME: error out in a more elegant fashion 7297 report_fatal_error("Unsupported asm: input constraint" 7298 " with a matching output constraint of" 7299 " incompatible type!"); 7300 } 7301 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7302 } 7303 7304 /// Get a direct memory input to behave well as an indirect operand. 7305 /// This may introduce stores, hence the need for a \p Chain. 7306 /// \return The (possibly updated) chain. 7307 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7308 SDISelAsmOperandInfo &OpInfo, 7309 SelectionDAG &DAG) { 7310 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7311 7312 // If we don't have an indirect input, put it in the constpool if we can, 7313 // otherwise spill it to a stack slot. 7314 // TODO: This isn't quite right. We need to handle these according to 7315 // the addressing mode that the constraint wants. Also, this may take 7316 // an additional register for the computation and we don't want that 7317 // either. 7318 7319 // If the operand is a float, integer, or vector constant, spill to a 7320 // constant pool entry to get its address. 7321 const Value *OpVal = OpInfo.CallOperandVal; 7322 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7323 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7324 OpInfo.CallOperand = DAG.getConstantPool( 7325 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7326 return Chain; 7327 } 7328 7329 // Otherwise, create a stack slot and emit a store to it before the asm. 7330 Type *Ty = OpVal->getType(); 7331 auto &DL = DAG.getDataLayout(); 7332 uint64_t TySize = DL.getTypeAllocSize(Ty); 7333 unsigned Align = DL.getPrefTypeAlignment(Ty); 7334 MachineFunction &MF = DAG.getMachineFunction(); 7335 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7336 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7337 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7338 MachinePointerInfo::getFixedStack(MF, SSFI)); 7339 OpInfo.CallOperand = StackSlot; 7340 7341 return Chain; 7342 } 7343 7344 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7345 /// specified operand. We prefer to assign virtual registers, to allow the 7346 /// register allocator to handle the assignment process. However, if the asm 7347 /// uses features that we can't model on machineinstrs, we have SDISel do the 7348 /// allocation. This produces generally horrible, but correct, code. 7349 /// 7350 /// OpInfo describes the operand 7351 /// RefOpInfo describes the matching operand if any, the operand otherwise 7352 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI, 7353 const SDLoc &DL, SDISelAsmOperandInfo &OpInfo, 7354 SDISelAsmOperandInfo &RefOpInfo) { 7355 LLVMContext &Context = *DAG.getContext(); 7356 7357 MachineFunction &MF = DAG.getMachineFunction(); 7358 SmallVector<unsigned, 4> Regs; 7359 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7360 7361 // If this is a constraint for a single physreg, or a constraint for a 7362 // register class, find it. 7363 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 7364 TLI.getRegForInlineAsmConstraint(&TRI, RefOpInfo.ConstraintCode, 7365 RefOpInfo.ConstraintVT); 7366 7367 unsigned NumRegs = 1; 7368 if (OpInfo.ConstraintVT != MVT::Other) { 7369 // If this is an FP operand in an integer register (or visa versa), or more 7370 // generally if the operand value disagrees with the register class we plan 7371 // to stick it in, fix the operand type. 7372 // 7373 // If this is an input value, the bitcast to the new type is done now. 7374 // Bitcast for output value is done at the end of visitInlineAsm(). 7375 if ((OpInfo.Type == InlineAsm::isOutput || 7376 OpInfo.Type == InlineAsm::isInput) && 7377 PhysReg.second && 7378 !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) { 7379 // Try to convert to the first EVT that the reg class contains. If the 7380 // types are identical size, use a bitcast to convert (e.g. two differing 7381 // vector types). Note: output bitcast is done at the end of 7382 // visitInlineAsm(). 7383 MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second); 7384 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7385 // Exclude indirect inputs while they are unsupported because the code 7386 // to perform the load is missing and thus OpInfo.CallOperand still 7387 // refers to the input address rather than the pointed-to value. 7388 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7389 OpInfo.CallOperand = 7390 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7391 OpInfo.ConstraintVT = RegVT; 7392 // If the operand is an FP value and we want it in integer registers, 7393 // use the corresponding integer type. This turns an f64 value into 7394 // i64, which can be passed with two i32 values on a 32-bit machine. 7395 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7396 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7397 if (OpInfo.Type == InlineAsm::isInput) 7398 OpInfo.CallOperand = 7399 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7400 OpInfo.ConstraintVT = RegVT; 7401 } 7402 } 7403 7404 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7405 } 7406 7407 // No need to allocate a matching input constraint since the constraint it's 7408 // matching to has already been allocated. 7409 if (OpInfo.isMatchingInputConstraint()) 7410 return; 7411 7412 MVT RegVT; 7413 EVT ValueVT = OpInfo.ConstraintVT; 7414 7415 // If this is a constraint for a specific physical register, like {r17}, 7416 // assign it now. 7417 if (unsigned AssignedReg = PhysReg.first) { 7418 const TargetRegisterClass *RC = PhysReg.second; 7419 if (OpInfo.ConstraintVT == MVT::Other) 7420 ValueVT = *TRI.legalclasstypes_begin(*RC); 7421 7422 // Get the actual register value type. This is important, because the user 7423 // may have asked for (e.g.) the AX register in i32 type. We need to 7424 // remember that AX is actually i16 to get the right extension. 7425 RegVT = *TRI.legalclasstypes_begin(*RC); 7426 7427 // This is an explicit reference to a physical register. 7428 Regs.push_back(AssignedReg); 7429 7430 // If this is an expanded reference, add the rest of the regs to Regs. 7431 if (NumRegs != 1) { 7432 TargetRegisterClass::iterator I = RC->begin(); 7433 for (; *I != AssignedReg; ++I) 7434 assert(I != RC->end() && "Didn't find reg!"); 7435 7436 // Already added the first reg. 7437 --NumRegs; ++I; 7438 for (; NumRegs; --NumRegs, ++I) { 7439 assert(I != RC->end() && "Ran out of registers to allocate!"); 7440 Regs.push_back(*I); 7441 } 7442 } 7443 7444 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7445 return; 7446 } 7447 7448 // Otherwise, if this was a reference to an LLVM register class, create vregs 7449 // for this reference. 7450 if (const TargetRegisterClass *RC = PhysReg.second) { 7451 RegVT = *TRI.legalclasstypes_begin(*RC); 7452 if (OpInfo.ConstraintVT == MVT::Other) 7453 ValueVT = RegVT; 7454 7455 // Create the appropriate number of virtual registers. 7456 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7457 for (; NumRegs; --NumRegs) 7458 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7459 7460 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7461 return; 7462 } 7463 7464 // Otherwise, we couldn't allocate enough registers for this. 7465 } 7466 7467 static unsigned 7468 findMatchingInlineAsmOperand(unsigned OperandNo, 7469 const std::vector<SDValue> &AsmNodeOperands) { 7470 // Scan until we find the definition we already emitted of this operand. 7471 unsigned CurOp = InlineAsm::Op_FirstOperand; 7472 for (; OperandNo; --OperandNo) { 7473 // Advance to the next operand. 7474 unsigned OpFlag = 7475 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7476 assert((InlineAsm::isRegDefKind(OpFlag) || 7477 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7478 InlineAsm::isMemKind(OpFlag)) && 7479 "Skipped past definitions?"); 7480 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7481 } 7482 return CurOp; 7483 } 7484 7485 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT 7486 /// \return true if it has succeeded, false otherwise 7487 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs, 7488 MVT RegVT, SelectionDAG &DAG) { 7489 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7490 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 7491 for (unsigned i = 0, e = NumRegs; i != e; ++i) { 7492 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 7493 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7494 else 7495 return false; 7496 } 7497 return true; 7498 } 7499 7500 namespace { 7501 7502 class ExtraFlags { 7503 unsigned Flags = 0; 7504 7505 public: 7506 explicit ExtraFlags(ImmutableCallSite CS) { 7507 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7508 if (IA->hasSideEffects()) 7509 Flags |= InlineAsm::Extra_HasSideEffects; 7510 if (IA->isAlignStack()) 7511 Flags |= InlineAsm::Extra_IsAlignStack; 7512 if (CS.isConvergent()) 7513 Flags |= InlineAsm::Extra_IsConvergent; 7514 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7515 } 7516 7517 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7518 // Ideally, we would only check against memory constraints. However, the 7519 // meaning of an Other constraint can be target-specific and we can't easily 7520 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7521 // for Other constraints as well. 7522 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7523 OpInfo.ConstraintType == TargetLowering::C_Other) { 7524 if (OpInfo.Type == InlineAsm::isInput) 7525 Flags |= InlineAsm::Extra_MayLoad; 7526 else if (OpInfo.Type == InlineAsm::isOutput) 7527 Flags |= InlineAsm::Extra_MayStore; 7528 else if (OpInfo.Type == InlineAsm::isClobber) 7529 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7530 } 7531 } 7532 7533 unsigned get() const { return Flags; } 7534 }; 7535 7536 } // end anonymous namespace 7537 7538 /// visitInlineAsm - Handle a call to an InlineAsm object. 7539 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7540 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7541 7542 /// ConstraintOperands - Information about all of the constraints. 7543 SDISelAsmOperandInfoVector ConstraintOperands; 7544 7545 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7546 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7547 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7548 7549 bool hasMemory = false; 7550 7551 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7552 ExtraFlags ExtraInfo(CS); 7553 7554 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7555 unsigned ResNo = 0; // ResNo - The result number of the next output. 7556 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 7557 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 7558 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7559 7560 MVT OpVT = MVT::Other; 7561 7562 // Compute the value type for each operand. 7563 if (OpInfo.Type == InlineAsm::isInput || 7564 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7565 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7566 7567 // Process the call argument. BasicBlocks are labels, currently appearing 7568 // only in asm's. 7569 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7570 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7571 } else { 7572 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7573 } 7574 7575 OpVT = 7576 OpInfo 7577 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7578 .getSimpleVT(); 7579 } 7580 7581 if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7582 // The return value of the call is this value. As such, there is no 7583 // corresponding argument. 7584 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7585 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7586 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 7587 STy->getElementType(ResNo)); 7588 } else { 7589 assert(ResNo == 0 && "Asm only has one result!"); 7590 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7591 } 7592 ++ResNo; 7593 } 7594 7595 OpInfo.ConstraintVT = OpVT; 7596 7597 if (!hasMemory) 7598 hasMemory = OpInfo.hasMemory(TLI); 7599 7600 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7601 // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]? 7602 auto TargetConstraint = TargetConstraints[i]; 7603 7604 // Compute the constraint code and ConstraintType to use. 7605 TLI.ComputeConstraintToUse(TargetConstraint, SDValue()); 7606 7607 ExtraInfo.update(TargetConstraint); 7608 } 7609 7610 SDValue Chain, Flag; 7611 7612 // We won't need to flush pending loads if this asm doesn't touch 7613 // memory and is nonvolatile. 7614 if (hasMemory || IA->hasSideEffects()) 7615 Chain = getRoot(); 7616 else 7617 Chain = DAG.getRoot(); 7618 7619 // Second pass over the constraints: compute which constraint option to use 7620 // and assign registers to constraints that want a specific physreg. 7621 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7622 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7623 7624 // If this is an output operand with a matching input operand, look up the 7625 // matching input. If their types mismatch, e.g. one is an integer, the 7626 // other is floating point, or their sizes are different, flag it as an 7627 // error. 7628 if (OpInfo.hasMatchingInput()) { 7629 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7630 patchMatchingInput(OpInfo, Input, DAG); 7631 } 7632 7633 // Compute the constraint code and ConstraintType to use. 7634 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7635 7636 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7637 OpInfo.Type == InlineAsm::isClobber) 7638 continue; 7639 7640 // If this is a memory input, and if the operand is not indirect, do what we 7641 // need to provide an address for the memory input. 7642 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7643 !OpInfo.isIndirect) { 7644 assert((OpInfo.isMultipleAlternative || 7645 (OpInfo.Type == InlineAsm::isInput)) && 7646 "Can only indirectify direct input operands!"); 7647 7648 // Memory operands really want the address of the value. 7649 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7650 7651 // There is no longer a Value* corresponding to this operand. 7652 OpInfo.CallOperandVal = nullptr; 7653 7654 // It is now an indirect operand. 7655 OpInfo.isIndirect = true; 7656 } 7657 7658 // If this constraint is for a specific register, allocate it before 7659 // anything else. 7660 SDISelAsmOperandInfo &RefOpInfo = 7661 OpInfo.isMatchingInputConstraint() 7662 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7663 : ConstraintOperands[i]; 7664 if (RefOpInfo.ConstraintType == TargetLowering::C_Register) 7665 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo); 7666 } 7667 7668 // Third pass - Loop over all of the operands, assigning virtual or physregs 7669 // to register class operands. 7670 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7671 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7672 SDISelAsmOperandInfo &RefOpInfo = 7673 OpInfo.isMatchingInputConstraint() 7674 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7675 : ConstraintOperands[i]; 7676 7677 // C_Register operands have already been allocated, Other/Memory don't need 7678 // to be. 7679 if (RefOpInfo.ConstraintType == TargetLowering::C_RegisterClass) 7680 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo); 7681 } 7682 7683 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7684 std::vector<SDValue> AsmNodeOperands; 7685 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7686 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7687 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7688 7689 // If we have a !srcloc metadata node associated with it, we want to attach 7690 // this to the ultimately generated inline asm machineinstr. To do this, we 7691 // pass in the third operand as this (potentially null) inline asm MDNode. 7692 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7693 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7694 7695 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7696 // bits as operand 3. 7697 AsmNodeOperands.push_back(DAG.getTargetConstant( 7698 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7699 7700 // Loop over all of the inputs, copying the operand values into the 7701 // appropriate registers and processing the output regs. 7702 RegsForValue RetValRegs; 7703 7704 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 7705 std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit; 7706 7707 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7708 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7709 7710 switch (OpInfo.Type) { 7711 case InlineAsm::isOutput: 7712 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7713 OpInfo.ConstraintType != TargetLowering::C_Register) { 7714 // Memory output, or 'other' output (e.g. 'X' constraint). 7715 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7716 7717 unsigned ConstraintID = 7718 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7719 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7720 "Failed to convert memory constraint code to constraint id."); 7721 7722 // Add information to the INLINEASM node to know about this output. 7723 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7724 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7725 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7726 MVT::i32)); 7727 AsmNodeOperands.push_back(OpInfo.CallOperand); 7728 break; 7729 } 7730 7731 // Otherwise, this is a register or register class output. 7732 7733 // Copy the output from the appropriate register. Find a register that 7734 // we can use. 7735 if (OpInfo.AssignedRegs.Regs.empty()) { 7736 emitInlineAsmError( 7737 CS, "couldn't allocate output register for constraint '" + 7738 Twine(OpInfo.ConstraintCode) + "'"); 7739 return; 7740 } 7741 7742 // If this is an indirect operand, store through the pointer after the 7743 // asm. 7744 if (OpInfo.isIndirect) { 7745 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 7746 OpInfo.CallOperandVal)); 7747 } else { 7748 // This is the result value of the call. 7749 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7750 // Concatenate this output onto the outputs list. 7751 RetValRegs.append(OpInfo.AssignedRegs); 7752 } 7753 7754 // Add information to the INLINEASM node to know that this register is 7755 // set. 7756 OpInfo.AssignedRegs 7757 .AddInlineAsmOperands(OpInfo.isEarlyClobber 7758 ? InlineAsm::Kind_RegDefEarlyClobber 7759 : InlineAsm::Kind_RegDef, 7760 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7761 break; 7762 7763 case InlineAsm::isInput: { 7764 SDValue InOperandVal = OpInfo.CallOperand; 7765 7766 if (OpInfo.isMatchingInputConstraint()) { 7767 // If this is required to match an output register we have already set, 7768 // just use its register. 7769 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7770 AsmNodeOperands); 7771 unsigned OpFlag = 7772 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7773 if (InlineAsm::isRegDefKind(OpFlag) || 7774 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7775 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7776 if (OpInfo.isIndirect) { 7777 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7778 emitInlineAsmError(CS, "inline asm not supported yet:" 7779 " don't know how to handle tied " 7780 "indirect register inputs"); 7781 return; 7782 } 7783 7784 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7785 SmallVector<unsigned, 4> Regs; 7786 7787 if (!createVirtualRegs(Regs, 7788 InlineAsm::getNumOperandRegisters(OpFlag), 7789 RegVT, DAG)) { 7790 emitInlineAsmError(CS, "inline asm error: This value type register " 7791 "class is not natively supported!"); 7792 return; 7793 } 7794 7795 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7796 7797 SDLoc dl = getCurSDLoc(); 7798 // Use the produced MatchedRegs object to 7799 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7800 CS.getInstruction()); 7801 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7802 true, OpInfo.getMatchedOperand(), dl, 7803 DAG, AsmNodeOperands); 7804 break; 7805 } 7806 7807 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7808 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7809 "Unexpected number of operands"); 7810 // Add information to the INLINEASM node to know about this input. 7811 // See InlineAsm.h isUseOperandTiedToDef. 7812 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7813 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7814 OpInfo.getMatchedOperand()); 7815 AsmNodeOperands.push_back(DAG.getTargetConstant( 7816 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7817 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7818 break; 7819 } 7820 7821 // Treat indirect 'X' constraint as memory. 7822 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7823 OpInfo.isIndirect) 7824 OpInfo.ConstraintType = TargetLowering::C_Memory; 7825 7826 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7827 std::vector<SDValue> Ops; 7828 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7829 Ops, DAG); 7830 if (Ops.empty()) { 7831 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7832 Twine(OpInfo.ConstraintCode) + "'"); 7833 return; 7834 } 7835 7836 // Add information to the INLINEASM node to know about this input. 7837 unsigned ResOpType = 7838 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7839 AsmNodeOperands.push_back(DAG.getTargetConstant( 7840 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7841 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7842 break; 7843 } 7844 7845 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7846 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7847 assert(InOperandVal.getValueType() == 7848 TLI.getPointerTy(DAG.getDataLayout()) && 7849 "Memory operands expect pointer values"); 7850 7851 unsigned ConstraintID = 7852 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7853 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7854 "Failed to convert memory constraint code to constraint id."); 7855 7856 // Add information to the INLINEASM node to know about this input. 7857 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7858 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7859 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7860 getCurSDLoc(), 7861 MVT::i32)); 7862 AsmNodeOperands.push_back(InOperandVal); 7863 break; 7864 } 7865 7866 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7867 OpInfo.ConstraintType == TargetLowering::C_Register) && 7868 "Unknown constraint type!"); 7869 7870 // TODO: Support this. 7871 if (OpInfo.isIndirect) { 7872 emitInlineAsmError( 7873 CS, "Don't know how to handle indirect register inputs yet " 7874 "for constraint '" + 7875 Twine(OpInfo.ConstraintCode) + "'"); 7876 return; 7877 } 7878 7879 // Copy the input into the appropriate registers. 7880 if (OpInfo.AssignedRegs.Regs.empty()) { 7881 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7882 Twine(OpInfo.ConstraintCode) + "'"); 7883 return; 7884 } 7885 7886 SDLoc dl = getCurSDLoc(); 7887 7888 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7889 Chain, &Flag, CS.getInstruction()); 7890 7891 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7892 dl, DAG, AsmNodeOperands); 7893 break; 7894 } 7895 case InlineAsm::isClobber: 7896 // Add the clobbered value to the operand list, so that the register 7897 // allocator is aware that the physreg got clobbered. 7898 if (!OpInfo.AssignedRegs.Regs.empty()) 7899 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7900 false, 0, getCurSDLoc(), DAG, 7901 AsmNodeOperands); 7902 break; 7903 } 7904 } 7905 7906 // Finish up input operands. Set the input chain and add the flag last. 7907 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7908 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7909 7910 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7911 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7912 Flag = Chain.getValue(1); 7913 7914 // If this asm returns a register value, copy the result from that register 7915 // and set it as the value of the call. 7916 if (!RetValRegs.Regs.empty()) { 7917 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7918 Chain, &Flag, CS.getInstruction()); 7919 7920 llvm::Type *CSResultType = CS.getType(); 7921 unsigned numRet; 7922 ArrayRef<Type *> ResultTypes; 7923 SmallVector<SDValue, 1> ResultValues(1); 7924 if (CSResultType->isSingleValueType()) { 7925 numRet = 1; 7926 ResultValues[0] = Val; 7927 ResultTypes = makeArrayRef(CSResultType); 7928 } else { 7929 numRet = CSResultType->getNumContainedTypes(); 7930 assert(Val->getNumOperands() == numRet && 7931 "Mismatch in number of output operands in asm result"); 7932 ResultTypes = CSResultType->subtypes(); 7933 ArrayRef<SDUse> ValueUses = Val->ops(); 7934 ResultValues.resize(numRet); 7935 std::transform(ValueUses.begin(), ValueUses.end(), ResultValues.begin(), 7936 [](const SDUse &u) -> SDValue { return u.get(); }); 7937 } 7938 SmallVector<EVT, 1> ResultVTs(numRet); 7939 for (unsigned i = 0; i < numRet; i++) { 7940 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), ResultTypes[i]); 7941 SDValue Val = ResultValues[i]; 7942 assert(ResultTypes[i]->isSized() && "Unexpected unsized type"); 7943 // If the type of the inline asm call site return value is different but 7944 // has same size as the type of the asm output bitcast it. One example 7945 // of this is for vectors with different width / number of elements. 7946 // This can happen for register classes that can contain multiple 7947 // different value types. The preg or vreg allocated may not have the 7948 // same VT as was expected. 7949 // 7950 // This can also happen for a return value that disagrees with the 7951 // register class it is put in, eg. a double in a general-purpose 7952 // register on a 32-bit machine. 7953 if (ResultVT != Val.getValueType() && 7954 ResultVT.getSizeInBits() == Val.getValueSizeInBits()) 7955 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, Val); 7956 else if (ResultVT != Val.getValueType() && ResultVT.isInteger() && 7957 Val.getValueType().isInteger()) { 7958 // If a result value was tied to an input value, the computed result 7959 // may have a wider width than the expected result. Extract the 7960 // relevant portion. 7961 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, Val); 7962 } 7963 7964 assert(ResultVT == Val.getValueType() && "Asm result value mismatch!"); 7965 ResultVTs[i] = ResultVT; 7966 ResultValues[i] = Val; 7967 } 7968 7969 Val = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 7970 DAG.getVTList(ResultVTs), ResultValues); 7971 setValue(CS.getInstruction(), Val); 7972 // Don't need to use this as a chain in this case. 7973 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 7974 return; 7975 } 7976 7977 std::vector<std::pair<SDValue, const Value *>> StoresToEmit; 7978 7979 // Process indirect outputs, first output all of the flagged copies out of 7980 // physregs. 7981 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 7982 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 7983 const Value *Ptr = IndirectStoresToEmit[i].second; 7984 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7985 Chain, &Flag, IA); 7986 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 7987 } 7988 7989 // Emit the non-flagged stores from the physregs. 7990 SmallVector<SDValue, 8> OutChains; 7991 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 7992 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first, 7993 getValue(StoresToEmit[i].second), 7994 MachinePointerInfo(StoresToEmit[i].second)); 7995 OutChains.push_back(Val); 7996 } 7997 7998 if (!OutChains.empty()) 7999 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8000 8001 DAG.setRoot(Chain); 8002 } 8003 8004 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8005 const Twine &Message) { 8006 LLVMContext &Ctx = *DAG.getContext(); 8007 Ctx.emitError(CS.getInstruction(), Message); 8008 8009 // Make sure we leave the DAG in a valid state 8010 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8011 SmallVector<EVT, 1> ValueVTs; 8012 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8013 8014 if (ValueVTs.empty()) 8015 return; 8016 8017 SmallVector<SDValue, 1> Ops; 8018 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8019 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8020 8021 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8022 } 8023 8024 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8025 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8026 MVT::Other, getRoot(), 8027 getValue(I.getArgOperand(0)), 8028 DAG.getSrcValue(I.getArgOperand(0)))); 8029 } 8030 8031 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8032 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8033 const DataLayout &DL = DAG.getDataLayout(); 8034 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 8035 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 8036 DAG.getSrcValue(I.getOperand(0)), 8037 DL.getABITypeAlignment(I.getType())); 8038 setValue(&I, V); 8039 DAG.setRoot(V.getValue(1)); 8040 } 8041 8042 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8043 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8044 MVT::Other, getRoot(), 8045 getValue(I.getArgOperand(0)), 8046 DAG.getSrcValue(I.getArgOperand(0)))); 8047 } 8048 8049 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8050 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8051 MVT::Other, getRoot(), 8052 getValue(I.getArgOperand(0)), 8053 getValue(I.getArgOperand(1)), 8054 DAG.getSrcValue(I.getArgOperand(0)), 8055 DAG.getSrcValue(I.getArgOperand(1)))); 8056 } 8057 8058 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8059 const Instruction &I, 8060 SDValue Op) { 8061 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8062 if (!Range) 8063 return Op; 8064 8065 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8066 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 8067 return Op; 8068 8069 APInt Lo = CR.getUnsignedMin(); 8070 if (!Lo.isMinValue()) 8071 return Op; 8072 8073 APInt Hi = CR.getUnsignedMax(); 8074 unsigned Bits = std::max(Hi.getActiveBits(), 8075 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8076 8077 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8078 8079 SDLoc SL = getCurSDLoc(); 8080 8081 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8082 DAG.getValueType(SmallVT)); 8083 unsigned NumVals = Op.getNode()->getNumValues(); 8084 if (NumVals == 1) 8085 return ZExt; 8086 8087 SmallVector<SDValue, 4> Ops; 8088 8089 Ops.push_back(ZExt); 8090 for (unsigned I = 1; I != NumVals; ++I) 8091 Ops.push_back(Op.getValue(I)); 8092 8093 return DAG.getMergeValues(Ops, SL); 8094 } 8095 8096 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8097 /// the call being lowered. 8098 /// 8099 /// This is a helper for lowering intrinsics that follow a target calling 8100 /// convention or require stack pointer adjustment. Only a subset of the 8101 /// intrinsic's operands need to participate in the calling convention. 8102 void SelectionDAGBuilder::populateCallLoweringInfo( 8103 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 8104 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8105 bool IsPatchPoint) { 8106 TargetLowering::ArgListTy Args; 8107 Args.reserve(NumArgs); 8108 8109 // Populate the argument list. 8110 // Attributes for args start at offset 1, after the return attribute. 8111 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8112 ArgI != ArgE; ++ArgI) { 8113 const Value *V = CS->getOperand(ArgI); 8114 8115 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8116 8117 TargetLowering::ArgListEntry Entry; 8118 Entry.Node = getValue(V); 8119 Entry.Ty = V->getType(); 8120 Entry.setAttributes(&CS, ArgI); 8121 Args.push_back(Entry); 8122 } 8123 8124 CLI.setDebugLoc(getCurSDLoc()) 8125 .setChain(getRoot()) 8126 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 8127 .setDiscardResult(CS->use_empty()) 8128 .setIsPatchPoint(IsPatchPoint); 8129 } 8130 8131 /// Add a stack map intrinsic call's live variable operands to a stackmap 8132 /// or patchpoint target node's operand list. 8133 /// 8134 /// Constants are converted to TargetConstants purely as an optimization to 8135 /// avoid constant materialization and register allocation. 8136 /// 8137 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8138 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8139 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8140 /// address materialization and register allocation, but may also be required 8141 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8142 /// alloca in the entry block, then the runtime may assume that the alloca's 8143 /// StackMap location can be read immediately after compilation and that the 8144 /// location is valid at any point during execution (this is similar to the 8145 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8146 /// only available in a register, then the runtime would need to trap when 8147 /// execution reaches the StackMap in order to read the alloca's location. 8148 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8149 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8150 SelectionDAGBuilder &Builder) { 8151 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8152 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8153 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8154 Ops.push_back( 8155 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8156 Ops.push_back( 8157 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8158 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8159 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8160 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8161 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8162 } else 8163 Ops.push_back(OpVal); 8164 } 8165 } 8166 8167 /// Lower llvm.experimental.stackmap directly to its target opcode. 8168 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8169 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8170 // [live variables...]) 8171 8172 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8173 8174 SDValue Chain, InFlag, Callee, NullPtr; 8175 SmallVector<SDValue, 32> Ops; 8176 8177 SDLoc DL = getCurSDLoc(); 8178 Callee = getValue(CI.getCalledValue()); 8179 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8180 8181 // The stackmap intrinsic only records the live variables (the arguemnts 8182 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8183 // intrinsic, this won't be lowered to a function call. This means we don't 8184 // have to worry about calling conventions and target specific lowering code. 8185 // Instead we perform the call lowering right here. 8186 // 8187 // chain, flag = CALLSEQ_START(chain, 0, 0) 8188 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8189 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8190 // 8191 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8192 InFlag = Chain.getValue(1); 8193 8194 // Add the <id> and <numBytes> constants. 8195 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8196 Ops.push_back(DAG.getTargetConstant( 8197 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8198 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8199 Ops.push_back(DAG.getTargetConstant( 8200 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8201 MVT::i32)); 8202 8203 // Push live variables for the stack map. 8204 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8205 8206 // We are not pushing any register mask info here on the operands list, 8207 // because the stackmap doesn't clobber anything. 8208 8209 // Push the chain and the glue flag. 8210 Ops.push_back(Chain); 8211 Ops.push_back(InFlag); 8212 8213 // Create the STACKMAP node. 8214 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8215 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8216 Chain = SDValue(SM, 0); 8217 InFlag = Chain.getValue(1); 8218 8219 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8220 8221 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8222 8223 // Set the root to the target-lowered call chain. 8224 DAG.setRoot(Chain); 8225 8226 // Inform the Frame Information that we have a stackmap in this function. 8227 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8228 } 8229 8230 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8231 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8232 const BasicBlock *EHPadBB) { 8233 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8234 // i32 <numBytes>, 8235 // i8* <target>, 8236 // i32 <numArgs>, 8237 // [Args...], 8238 // [live variables...]) 8239 8240 CallingConv::ID CC = CS.getCallingConv(); 8241 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8242 bool HasDef = !CS->getType()->isVoidTy(); 8243 SDLoc dl = getCurSDLoc(); 8244 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8245 8246 // Handle immediate and symbolic callees. 8247 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8248 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8249 /*isTarget=*/true); 8250 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8251 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8252 SDLoc(SymbolicCallee), 8253 SymbolicCallee->getValueType(0)); 8254 8255 // Get the real number of arguments participating in the call <numArgs> 8256 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8257 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8258 8259 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8260 // Intrinsics include all meta-operands up to but not including CC. 8261 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8262 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8263 "Not enough arguments provided to the patchpoint intrinsic"); 8264 8265 // For AnyRegCC the arguments are lowered later on manually. 8266 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8267 Type *ReturnTy = 8268 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8269 8270 TargetLowering::CallLoweringInfo CLI(DAG); 8271 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8272 true); 8273 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8274 8275 SDNode *CallEnd = Result.second.getNode(); 8276 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8277 CallEnd = CallEnd->getOperand(0).getNode(); 8278 8279 /// Get a call instruction from the call sequence chain. 8280 /// Tail calls are not allowed. 8281 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8282 "Expected a callseq node."); 8283 SDNode *Call = CallEnd->getOperand(0).getNode(); 8284 bool HasGlue = Call->getGluedNode(); 8285 8286 // Replace the target specific call node with the patchable intrinsic. 8287 SmallVector<SDValue, 8> Ops; 8288 8289 // Add the <id> and <numBytes> constants. 8290 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8291 Ops.push_back(DAG.getTargetConstant( 8292 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8293 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8294 Ops.push_back(DAG.getTargetConstant( 8295 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8296 MVT::i32)); 8297 8298 // Add the callee. 8299 Ops.push_back(Callee); 8300 8301 // Adjust <numArgs> to account for any arguments that have been passed on the 8302 // stack instead. 8303 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8304 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8305 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8306 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8307 8308 // Add the calling convention 8309 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8310 8311 // Add the arguments we omitted previously. The register allocator should 8312 // place these in any free register. 8313 if (IsAnyRegCC) 8314 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8315 Ops.push_back(getValue(CS.getArgument(i))); 8316 8317 // Push the arguments from the call instruction up to the register mask. 8318 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8319 Ops.append(Call->op_begin() + 2, e); 8320 8321 // Push live variables for the stack map. 8322 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8323 8324 // Push the register mask info. 8325 if (HasGlue) 8326 Ops.push_back(*(Call->op_end()-2)); 8327 else 8328 Ops.push_back(*(Call->op_end()-1)); 8329 8330 // Push the chain (this is originally the first operand of the call, but 8331 // becomes now the last or second to last operand). 8332 Ops.push_back(*(Call->op_begin())); 8333 8334 // Push the glue flag (last operand). 8335 if (HasGlue) 8336 Ops.push_back(*(Call->op_end()-1)); 8337 8338 SDVTList NodeTys; 8339 if (IsAnyRegCC && HasDef) { 8340 // Create the return types based on the intrinsic definition 8341 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8342 SmallVector<EVT, 3> ValueVTs; 8343 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8344 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8345 8346 // There is always a chain and a glue type at the end 8347 ValueVTs.push_back(MVT::Other); 8348 ValueVTs.push_back(MVT::Glue); 8349 NodeTys = DAG.getVTList(ValueVTs); 8350 } else 8351 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8352 8353 // Replace the target specific call node with a PATCHPOINT node. 8354 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8355 dl, NodeTys, Ops); 8356 8357 // Update the NodeMap. 8358 if (HasDef) { 8359 if (IsAnyRegCC) 8360 setValue(CS.getInstruction(), SDValue(MN, 0)); 8361 else 8362 setValue(CS.getInstruction(), Result.first); 8363 } 8364 8365 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8366 // call sequence. Furthermore the location of the chain and glue can change 8367 // when the AnyReg calling convention is used and the intrinsic returns a 8368 // value. 8369 if (IsAnyRegCC && HasDef) { 8370 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8371 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8372 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8373 } else 8374 DAG.ReplaceAllUsesWith(Call, MN); 8375 DAG.DeleteNode(Call); 8376 8377 // Inform the Frame Information that we have a patchpoint in this function. 8378 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8379 } 8380 8381 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8382 unsigned Intrinsic) { 8383 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8384 SDValue Op1 = getValue(I.getArgOperand(0)); 8385 SDValue Op2; 8386 if (I.getNumArgOperands() > 1) 8387 Op2 = getValue(I.getArgOperand(1)); 8388 SDLoc dl = getCurSDLoc(); 8389 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8390 SDValue Res; 8391 FastMathFlags FMF; 8392 if (isa<FPMathOperator>(I)) 8393 FMF = I.getFastMathFlags(); 8394 8395 switch (Intrinsic) { 8396 case Intrinsic::experimental_vector_reduce_fadd: 8397 if (FMF.isFast()) 8398 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8399 else 8400 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8401 break; 8402 case Intrinsic::experimental_vector_reduce_fmul: 8403 if (FMF.isFast()) 8404 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8405 else 8406 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8407 break; 8408 case Intrinsic::experimental_vector_reduce_add: 8409 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8410 break; 8411 case Intrinsic::experimental_vector_reduce_mul: 8412 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8413 break; 8414 case Intrinsic::experimental_vector_reduce_and: 8415 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8416 break; 8417 case Intrinsic::experimental_vector_reduce_or: 8418 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8419 break; 8420 case Intrinsic::experimental_vector_reduce_xor: 8421 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8422 break; 8423 case Intrinsic::experimental_vector_reduce_smax: 8424 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8425 break; 8426 case Intrinsic::experimental_vector_reduce_smin: 8427 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8428 break; 8429 case Intrinsic::experimental_vector_reduce_umax: 8430 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8431 break; 8432 case Intrinsic::experimental_vector_reduce_umin: 8433 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8434 break; 8435 case Intrinsic::experimental_vector_reduce_fmax: 8436 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8437 break; 8438 case Intrinsic::experimental_vector_reduce_fmin: 8439 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8440 break; 8441 default: 8442 llvm_unreachable("Unhandled vector reduce intrinsic"); 8443 } 8444 setValue(&I, Res); 8445 } 8446 8447 /// Returns an AttributeList representing the attributes applied to the return 8448 /// value of the given call. 8449 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8450 SmallVector<Attribute::AttrKind, 2> Attrs; 8451 if (CLI.RetSExt) 8452 Attrs.push_back(Attribute::SExt); 8453 if (CLI.RetZExt) 8454 Attrs.push_back(Attribute::ZExt); 8455 if (CLI.IsInReg) 8456 Attrs.push_back(Attribute::InReg); 8457 8458 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8459 Attrs); 8460 } 8461 8462 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8463 /// implementation, which just calls LowerCall. 8464 /// FIXME: When all targets are 8465 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8466 std::pair<SDValue, SDValue> 8467 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8468 // Handle the incoming return values from the call. 8469 CLI.Ins.clear(); 8470 Type *OrigRetTy = CLI.RetTy; 8471 SmallVector<EVT, 4> RetTys; 8472 SmallVector<uint64_t, 4> Offsets; 8473 auto &DL = CLI.DAG.getDataLayout(); 8474 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8475 8476 if (CLI.IsPostTypeLegalization) { 8477 // If we are lowering a libcall after legalization, split the return type. 8478 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8479 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8480 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8481 EVT RetVT = OldRetTys[i]; 8482 uint64_t Offset = OldOffsets[i]; 8483 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8484 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8485 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8486 RetTys.append(NumRegs, RegisterVT); 8487 for (unsigned j = 0; j != NumRegs; ++j) 8488 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8489 } 8490 } 8491 8492 SmallVector<ISD::OutputArg, 4> Outs; 8493 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8494 8495 bool CanLowerReturn = 8496 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8497 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8498 8499 SDValue DemoteStackSlot; 8500 int DemoteStackIdx = -100; 8501 if (!CanLowerReturn) { 8502 // FIXME: equivalent assert? 8503 // assert(!CS.hasInAllocaArgument() && 8504 // "sret demotion is incompatible with inalloca"); 8505 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8506 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8507 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8508 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8509 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8510 DL.getAllocaAddrSpace()); 8511 8512 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8513 ArgListEntry Entry; 8514 Entry.Node = DemoteStackSlot; 8515 Entry.Ty = StackSlotPtrType; 8516 Entry.IsSExt = false; 8517 Entry.IsZExt = false; 8518 Entry.IsInReg = false; 8519 Entry.IsSRet = true; 8520 Entry.IsNest = false; 8521 Entry.IsByVal = false; 8522 Entry.IsReturned = false; 8523 Entry.IsSwiftSelf = false; 8524 Entry.IsSwiftError = false; 8525 Entry.Alignment = Align; 8526 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8527 CLI.NumFixedArgs += 1; 8528 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8529 8530 // sret demotion isn't compatible with tail-calls, since the sret argument 8531 // points into the callers stack frame. 8532 CLI.IsTailCall = false; 8533 } else { 8534 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8535 EVT VT = RetTys[I]; 8536 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8537 CLI.CallConv, VT); 8538 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8539 CLI.CallConv, VT); 8540 for (unsigned i = 0; i != NumRegs; ++i) { 8541 ISD::InputArg MyFlags; 8542 MyFlags.VT = RegisterVT; 8543 MyFlags.ArgVT = VT; 8544 MyFlags.Used = CLI.IsReturnValueUsed; 8545 if (CLI.RetSExt) 8546 MyFlags.Flags.setSExt(); 8547 if (CLI.RetZExt) 8548 MyFlags.Flags.setZExt(); 8549 if (CLI.IsInReg) 8550 MyFlags.Flags.setInReg(); 8551 CLI.Ins.push_back(MyFlags); 8552 } 8553 } 8554 } 8555 8556 // We push in swifterror return as the last element of CLI.Ins. 8557 ArgListTy &Args = CLI.getArgs(); 8558 if (supportSwiftError()) { 8559 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8560 if (Args[i].IsSwiftError) { 8561 ISD::InputArg MyFlags; 8562 MyFlags.VT = getPointerTy(DL); 8563 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8564 MyFlags.Flags.setSwiftError(); 8565 CLI.Ins.push_back(MyFlags); 8566 } 8567 } 8568 } 8569 8570 // Handle all of the outgoing arguments. 8571 CLI.Outs.clear(); 8572 CLI.OutVals.clear(); 8573 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8574 SmallVector<EVT, 4> ValueVTs; 8575 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8576 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8577 Type *FinalType = Args[i].Ty; 8578 if (Args[i].IsByVal) 8579 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8580 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8581 FinalType, CLI.CallConv, CLI.IsVarArg); 8582 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8583 ++Value) { 8584 EVT VT = ValueVTs[Value]; 8585 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8586 SDValue Op = SDValue(Args[i].Node.getNode(), 8587 Args[i].Node.getResNo() + Value); 8588 ISD::ArgFlagsTy Flags; 8589 8590 // Certain targets (such as MIPS), may have a different ABI alignment 8591 // for a type depending on the context. Give the target a chance to 8592 // specify the alignment it wants. 8593 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8594 8595 if (Args[i].IsZExt) 8596 Flags.setZExt(); 8597 if (Args[i].IsSExt) 8598 Flags.setSExt(); 8599 if (Args[i].IsInReg) { 8600 // If we are using vectorcall calling convention, a structure that is 8601 // passed InReg - is surely an HVA 8602 if (CLI.CallConv == CallingConv::X86_VectorCall && 8603 isa<StructType>(FinalType)) { 8604 // The first value of a structure is marked 8605 if (0 == Value) 8606 Flags.setHvaStart(); 8607 Flags.setHva(); 8608 } 8609 // Set InReg Flag 8610 Flags.setInReg(); 8611 } 8612 if (Args[i].IsSRet) 8613 Flags.setSRet(); 8614 if (Args[i].IsSwiftSelf) 8615 Flags.setSwiftSelf(); 8616 if (Args[i].IsSwiftError) 8617 Flags.setSwiftError(); 8618 if (Args[i].IsByVal) 8619 Flags.setByVal(); 8620 if (Args[i].IsInAlloca) { 8621 Flags.setInAlloca(); 8622 // Set the byval flag for CCAssignFn callbacks that don't know about 8623 // inalloca. This way we can know how many bytes we should've allocated 8624 // and how many bytes a callee cleanup function will pop. If we port 8625 // inalloca to more targets, we'll have to add custom inalloca handling 8626 // in the various CC lowering callbacks. 8627 Flags.setByVal(); 8628 } 8629 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8630 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8631 Type *ElementTy = Ty->getElementType(); 8632 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8633 // For ByVal, alignment should come from FE. BE will guess if this 8634 // info is not there but there are cases it cannot get right. 8635 unsigned FrameAlign; 8636 if (Args[i].Alignment) 8637 FrameAlign = Args[i].Alignment; 8638 else 8639 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8640 Flags.setByValAlign(FrameAlign); 8641 } 8642 if (Args[i].IsNest) 8643 Flags.setNest(); 8644 if (NeedsRegBlock) 8645 Flags.setInConsecutiveRegs(); 8646 Flags.setOrigAlign(OriginalAlignment); 8647 8648 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8649 CLI.CallConv, VT); 8650 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8651 CLI.CallConv, VT); 8652 SmallVector<SDValue, 4> Parts(NumParts); 8653 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8654 8655 if (Args[i].IsSExt) 8656 ExtendKind = ISD::SIGN_EXTEND; 8657 else if (Args[i].IsZExt) 8658 ExtendKind = ISD::ZERO_EXTEND; 8659 8660 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8661 // for now. 8662 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8663 CanLowerReturn) { 8664 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8665 "unexpected use of 'returned'"); 8666 // Before passing 'returned' to the target lowering code, ensure that 8667 // either the register MVT and the actual EVT are the same size or that 8668 // the return value and argument are extended in the same way; in these 8669 // cases it's safe to pass the argument register value unchanged as the 8670 // return register value (although it's at the target's option whether 8671 // to do so) 8672 // TODO: allow code generation to take advantage of partially preserved 8673 // registers rather than clobbering the entire register when the 8674 // parameter extension method is not compatible with the return 8675 // extension method 8676 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8677 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8678 CLI.RetZExt == Args[i].IsZExt)) 8679 Flags.setReturned(); 8680 } 8681 8682 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8683 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8684 8685 for (unsigned j = 0; j != NumParts; ++j) { 8686 // if it isn't first piece, alignment must be 1 8687 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8688 i < CLI.NumFixedArgs, 8689 i, j*Parts[j].getValueType().getStoreSize()); 8690 if (NumParts > 1 && j == 0) 8691 MyFlags.Flags.setSplit(); 8692 else if (j != 0) { 8693 MyFlags.Flags.setOrigAlign(1); 8694 if (j == NumParts - 1) 8695 MyFlags.Flags.setSplitEnd(); 8696 } 8697 8698 CLI.Outs.push_back(MyFlags); 8699 CLI.OutVals.push_back(Parts[j]); 8700 } 8701 8702 if (NeedsRegBlock && Value == NumValues - 1) 8703 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8704 } 8705 } 8706 8707 SmallVector<SDValue, 4> InVals; 8708 CLI.Chain = LowerCall(CLI, InVals); 8709 8710 // Update CLI.InVals to use outside of this function. 8711 CLI.InVals = InVals; 8712 8713 // Verify that the target's LowerCall behaved as expected. 8714 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8715 "LowerCall didn't return a valid chain!"); 8716 assert((!CLI.IsTailCall || InVals.empty()) && 8717 "LowerCall emitted a return value for a tail call!"); 8718 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8719 "LowerCall didn't emit the correct number of values!"); 8720 8721 // For a tail call, the return value is merely live-out and there aren't 8722 // any nodes in the DAG representing it. Return a special value to 8723 // indicate that a tail call has been emitted and no more Instructions 8724 // should be processed in the current block. 8725 if (CLI.IsTailCall) { 8726 CLI.DAG.setRoot(CLI.Chain); 8727 return std::make_pair(SDValue(), SDValue()); 8728 } 8729 8730 #ifndef NDEBUG 8731 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8732 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8733 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8734 "LowerCall emitted a value with the wrong type!"); 8735 } 8736 #endif 8737 8738 SmallVector<SDValue, 4> ReturnValues; 8739 if (!CanLowerReturn) { 8740 // The instruction result is the result of loading from the 8741 // hidden sret parameter. 8742 SmallVector<EVT, 1> PVTs; 8743 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8744 8745 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8746 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8747 EVT PtrVT = PVTs[0]; 8748 8749 unsigned NumValues = RetTys.size(); 8750 ReturnValues.resize(NumValues); 8751 SmallVector<SDValue, 4> Chains(NumValues); 8752 8753 // An aggregate return value cannot wrap around the address space, so 8754 // offsets to its parts don't wrap either. 8755 SDNodeFlags Flags; 8756 Flags.setNoUnsignedWrap(true); 8757 8758 for (unsigned i = 0; i < NumValues; ++i) { 8759 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8760 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8761 PtrVT), Flags); 8762 SDValue L = CLI.DAG.getLoad( 8763 RetTys[i], CLI.DL, CLI.Chain, Add, 8764 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8765 DemoteStackIdx, Offsets[i]), 8766 /* Alignment = */ 1); 8767 ReturnValues[i] = L; 8768 Chains[i] = L.getValue(1); 8769 } 8770 8771 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8772 } else { 8773 // Collect the legal value parts into potentially illegal values 8774 // that correspond to the original function's return values. 8775 Optional<ISD::NodeType> AssertOp; 8776 if (CLI.RetSExt) 8777 AssertOp = ISD::AssertSext; 8778 else if (CLI.RetZExt) 8779 AssertOp = ISD::AssertZext; 8780 unsigned CurReg = 0; 8781 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8782 EVT VT = RetTys[I]; 8783 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8784 CLI.CallConv, VT); 8785 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8786 CLI.CallConv, VT); 8787 8788 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8789 NumRegs, RegisterVT, VT, nullptr, 8790 CLI.CallConv, AssertOp)); 8791 CurReg += NumRegs; 8792 } 8793 8794 // For a function returning void, there is no return value. We can't create 8795 // such a node, so we just return a null return value in that case. In 8796 // that case, nothing will actually look at the value. 8797 if (ReturnValues.empty()) 8798 return std::make_pair(SDValue(), CLI.Chain); 8799 } 8800 8801 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8802 CLI.DAG.getVTList(RetTys), ReturnValues); 8803 return std::make_pair(Res, CLI.Chain); 8804 } 8805 8806 void TargetLowering::LowerOperationWrapper(SDNode *N, 8807 SmallVectorImpl<SDValue> &Results, 8808 SelectionDAG &DAG) const { 8809 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8810 Results.push_back(Res); 8811 } 8812 8813 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8814 llvm_unreachable("LowerOperation not implemented for this target!"); 8815 } 8816 8817 void 8818 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8819 SDValue Op = getNonRegisterValue(V); 8820 assert((Op.getOpcode() != ISD::CopyFromReg || 8821 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8822 "Copy from a reg to the same reg!"); 8823 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8824 8825 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8826 // If this is an InlineAsm we have to match the registers required, not the 8827 // notional registers required by the type. 8828 8829 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 8830 None); // This is not an ABI copy. 8831 SDValue Chain = DAG.getEntryNode(); 8832 8833 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8834 FuncInfo.PreferredExtendType.end()) 8835 ? ISD::ANY_EXTEND 8836 : FuncInfo.PreferredExtendType[V]; 8837 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8838 PendingExports.push_back(Chain); 8839 } 8840 8841 #include "llvm/CodeGen/SelectionDAGISel.h" 8842 8843 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8844 /// entry block, return true. This includes arguments used by switches, since 8845 /// the switch may expand into multiple basic blocks. 8846 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8847 // With FastISel active, we may be splitting blocks, so force creation 8848 // of virtual registers for all non-dead arguments. 8849 if (FastISel) 8850 return A->use_empty(); 8851 8852 const BasicBlock &Entry = A->getParent()->front(); 8853 for (const User *U : A->users()) 8854 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8855 return false; // Use not in entry block. 8856 8857 return true; 8858 } 8859 8860 using ArgCopyElisionMapTy = 8861 DenseMap<const Argument *, 8862 std::pair<const AllocaInst *, const StoreInst *>>; 8863 8864 /// Scan the entry block of the function in FuncInfo for arguments that look 8865 /// like copies into a local alloca. Record any copied arguments in 8866 /// ArgCopyElisionCandidates. 8867 static void 8868 findArgumentCopyElisionCandidates(const DataLayout &DL, 8869 FunctionLoweringInfo *FuncInfo, 8870 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8871 // Record the state of every static alloca used in the entry block. Argument 8872 // allocas are all used in the entry block, so we need approximately as many 8873 // entries as we have arguments. 8874 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8875 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8876 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8877 StaticAllocas.reserve(NumArgs * 2); 8878 8879 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8880 if (!V) 8881 return nullptr; 8882 V = V->stripPointerCasts(); 8883 const auto *AI = dyn_cast<AllocaInst>(V); 8884 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8885 return nullptr; 8886 auto Iter = StaticAllocas.insert({AI, Unknown}); 8887 return &Iter.first->second; 8888 }; 8889 8890 // Look for stores of arguments to static allocas. Look through bitcasts and 8891 // GEPs to handle type coercions, as long as the alloca is fully initialized 8892 // by the store. Any non-store use of an alloca escapes it and any subsequent 8893 // unanalyzed store might write it. 8894 // FIXME: Handle structs initialized with multiple stores. 8895 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8896 // Look for stores, and handle non-store uses conservatively. 8897 const auto *SI = dyn_cast<StoreInst>(&I); 8898 if (!SI) { 8899 // We will look through cast uses, so ignore them completely. 8900 if (I.isCast()) 8901 continue; 8902 // Ignore debug info intrinsics, they don't escape or store to allocas. 8903 if (isa<DbgInfoIntrinsic>(I)) 8904 continue; 8905 // This is an unknown instruction. Assume it escapes or writes to all 8906 // static alloca operands. 8907 for (const Use &U : I.operands()) { 8908 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8909 *Info = StaticAllocaInfo::Clobbered; 8910 } 8911 continue; 8912 } 8913 8914 // If the stored value is a static alloca, mark it as escaped. 8915 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8916 *Info = StaticAllocaInfo::Clobbered; 8917 8918 // Check if the destination is a static alloca. 8919 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8920 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8921 if (!Info) 8922 continue; 8923 const AllocaInst *AI = cast<AllocaInst>(Dst); 8924 8925 // Skip allocas that have been initialized or clobbered. 8926 if (*Info != StaticAllocaInfo::Unknown) 8927 continue; 8928 8929 // Check if the stored value is an argument, and that this store fully 8930 // initializes the alloca. Don't elide copies from the same argument twice. 8931 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8932 const auto *Arg = dyn_cast<Argument>(Val); 8933 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8934 Arg->getType()->isEmptyTy() || 8935 DL.getTypeStoreSize(Arg->getType()) != 8936 DL.getTypeAllocSize(AI->getAllocatedType()) || 8937 ArgCopyElisionCandidates.count(Arg)) { 8938 *Info = StaticAllocaInfo::Clobbered; 8939 continue; 8940 } 8941 8942 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8943 << '\n'); 8944 8945 // Mark this alloca and store for argument copy elision. 8946 *Info = StaticAllocaInfo::Elidable; 8947 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8948 8949 // Stop scanning if we've seen all arguments. This will happen early in -O0 8950 // builds, which is useful, because -O0 builds have large entry blocks and 8951 // many allocas. 8952 if (ArgCopyElisionCandidates.size() == NumArgs) 8953 break; 8954 } 8955 } 8956 8957 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8958 /// ArgVal is a load from a suitable fixed stack object. 8959 static void tryToElideArgumentCopy( 8960 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8961 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8962 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8963 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8964 SDValue ArgVal, bool &ArgHasUses) { 8965 // Check if this is a load from a fixed stack object. 8966 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8967 if (!LNode) 8968 return; 8969 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8970 if (!FINode) 8971 return; 8972 8973 // Check that the fixed stack object is the right size and alignment. 8974 // Look at the alignment that the user wrote on the alloca instead of looking 8975 // at the stack object. 8976 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8977 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8978 const AllocaInst *AI = ArgCopyIter->second.first; 8979 int FixedIndex = FINode->getIndex(); 8980 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8981 int OldIndex = AllocaIndex; 8982 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8983 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8984 LLVM_DEBUG( 8985 dbgs() << " argument copy elision failed due to bad fixed stack " 8986 "object size\n"); 8987 return; 8988 } 8989 unsigned RequiredAlignment = AI->getAlignment(); 8990 if (!RequiredAlignment) { 8991 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8992 AI->getAllocatedType()); 8993 } 8994 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8995 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8996 "greater than stack argument alignment (" 8997 << RequiredAlignment << " vs " 8998 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8999 return; 9000 } 9001 9002 // Perform the elision. Delete the old stack object and replace its only use 9003 // in the variable info map. Mark the stack object as mutable. 9004 LLVM_DEBUG({ 9005 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9006 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9007 << '\n'; 9008 }); 9009 MFI.RemoveStackObject(OldIndex); 9010 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9011 AllocaIndex = FixedIndex; 9012 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9013 Chains.push_back(ArgVal.getValue(1)); 9014 9015 // Avoid emitting code for the store implementing the copy. 9016 const StoreInst *SI = ArgCopyIter->second.second; 9017 ElidedArgCopyInstrs.insert(SI); 9018 9019 // Check for uses of the argument again so that we can avoid exporting ArgVal 9020 // if it is't used by anything other than the store. 9021 for (const Value *U : Arg.users()) { 9022 if (U != SI) { 9023 ArgHasUses = true; 9024 break; 9025 } 9026 } 9027 } 9028 9029 void SelectionDAGISel::LowerArguments(const Function &F) { 9030 SelectionDAG &DAG = SDB->DAG; 9031 SDLoc dl = SDB->getCurSDLoc(); 9032 const DataLayout &DL = DAG.getDataLayout(); 9033 SmallVector<ISD::InputArg, 16> Ins; 9034 9035 if (!FuncInfo->CanLowerReturn) { 9036 // Put in an sret pointer parameter before all the other parameters. 9037 SmallVector<EVT, 1> ValueVTs; 9038 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9039 F.getReturnType()->getPointerTo( 9040 DAG.getDataLayout().getAllocaAddrSpace()), 9041 ValueVTs); 9042 9043 // NOTE: Assuming that a pointer will never break down to more than one VT 9044 // or one register. 9045 ISD::ArgFlagsTy Flags; 9046 Flags.setSRet(); 9047 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9048 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9049 ISD::InputArg::NoArgIndex, 0); 9050 Ins.push_back(RetArg); 9051 } 9052 9053 // Look for stores of arguments to static allocas. Mark such arguments with a 9054 // flag to ask the target to give us the memory location of that argument if 9055 // available. 9056 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9057 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9058 9059 // Set up the incoming argument description vector. 9060 for (const Argument &Arg : F.args()) { 9061 unsigned ArgNo = Arg.getArgNo(); 9062 SmallVector<EVT, 4> ValueVTs; 9063 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9064 bool isArgValueUsed = !Arg.use_empty(); 9065 unsigned PartBase = 0; 9066 Type *FinalType = Arg.getType(); 9067 if (Arg.hasAttribute(Attribute::ByVal)) 9068 FinalType = cast<PointerType>(FinalType)->getElementType(); 9069 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9070 FinalType, F.getCallingConv(), F.isVarArg()); 9071 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9072 Value != NumValues; ++Value) { 9073 EVT VT = ValueVTs[Value]; 9074 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9075 ISD::ArgFlagsTy Flags; 9076 9077 // Certain targets (such as MIPS), may have a different ABI alignment 9078 // for a type depending on the context. Give the target a chance to 9079 // specify the alignment it wants. 9080 unsigned OriginalAlignment = 9081 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9082 9083 if (Arg.hasAttribute(Attribute::ZExt)) 9084 Flags.setZExt(); 9085 if (Arg.hasAttribute(Attribute::SExt)) 9086 Flags.setSExt(); 9087 if (Arg.hasAttribute(Attribute::InReg)) { 9088 // If we are using vectorcall calling convention, a structure that is 9089 // passed InReg - is surely an HVA 9090 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9091 isa<StructType>(Arg.getType())) { 9092 // The first value of a structure is marked 9093 if (0 == Value) 9094 Flags.setHvaStart(); 9095 Flags.setHva(); 9096 } 9097 // Set InReg Flag 9098 Flags.setInReg(); 9099 } 9100 if (Arg.hasAttribute(Attribute::StructRet)) 9101 Flags.setSRet(); 9102 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9103 Flags.setSwiftSelf(); 9104 if (Arg.hasAttribute(Attribute::SwiftError)) 9105 Flags.setSwiftError(); 9106 if (Arg.hasAttribute(Attribute::ByVal)) 9107 Flags.setByVal(); 9108 if (Arg.hasAttribute(Attribute::InAlloca)) { 9109 Flags.setInAlloca(); 9110 // Set the byval flag for CCAssignFn callbacks that don't know about 9111 // inalloca. This way we can know how many bytes we should've allocated 9112 // and how many bytes a callee cleanup function will pop. If we port 9113 // inalloca to more targets, we'll have to add custom inalloca handling 9114 // in the various CC lowering callbacks. 9115 Flags.setByVal(); 9116 } 9117 if (F.getCallingConv() == CallingConv::X86_INTR) { 9118 // IA Interrupt passes frame (1st parameter) by value in the stack. 9119 if (ArgNo == 0) 9120 Flags.setByVal(); 9121 } 9122 if (Flags.isByVal() || Flags.isInAlloca()) { 9123 PointerType *Ty = cast<PointerType>(Arg.getType()); 9124 Type *ElementTy = Ty->getElementType(); 9125 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9126 // For ByVal, alignment should be passed from FE. BE will guess if 9127 // this info is not there but there are cases it cannot get right. 9128 unsigned FrameAlign; 9129 if (Arg.getParamAlignment()) 9130 FrameAlign = Arg.getParamAlignment(); 9131 else 9132 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9133 Flags.setByValAlign(FrameAlign); 9134 } 9135 if (Arg.hasAttribute(Attribute::Nest)) 9136 Flags.setNest(); 9137 if (NeedsRegBlock) 9138 Flags.setInConsecutiveRegs(); 9139 Flags.setOrigAlign(OriginalAlignment); 9140 if (ArgCopyElisionCandidates.count(&Arg)) 9141 Flags.setCopyElisionCandidate(); 9142 9143 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9144 *CurDAG->getContext(), F.getCallingConv(), VT); 9145 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9146 *CurDAG->getContext(), F.getCallingConv(), VT); 9147 for (unsigned i = 0; i != NumRegs; ++i) { 9148 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9149 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9150 if (NumRegs > 1 && i == 0) 9151 MyFlags.Flags.setSplit(); 9152 // if it isn't first piece, alignment must be 1 9153 else if (i > 0) { 9154 MyFlags.Flags.setOrigAlign(1); 9155 if (i == NumRegs - 1) 9156 MyFlags.Flags.setSplitEnd(); 9157 } 9158 Ins.push_back(MyFlags); 9159 } 9160 if (NeedsRegBlock && Value == NumValues - 1) 9161 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9162 PartBase += VT.getStoreSize(); 9163 } 9164 } 9165 9166 // Call the target to set up the argument values. 9167 SmallVector<SDValue, 8> InVals; 9168 SDValue NewRoot = TLI->LowerFormalArguments( 9169 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9170 9171 // Verify that the target's LowerFormalArguments behaved as expected. 9172 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9173 "LowerFormalArguments didn't return a valid chain!"); 9174 assert(InVals.size() == Ins.size() && 9175 "LowerFormalArguments didn't emit the correct number of values!"); 9176 LLVM_DEBUG({ 9177 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9178 assert(InVals[i].getNode() && 9179 "LowerFormalArguments emitted a null value!"); 9180 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9181 "LowerFormalArguments emitted a value with the wrong type!"); 9182 } 9183 }); 9184 9185 // Update the DAG with the new chain value resulting from argument lowering. 9186 DAG.setRoot(NewRoot); 9187 9188 // Set up the argument values. 9189 unsigned i = 0; 9190 if (!FuncInfo->CanLowerReturn) { 9191 // Create a virtual register for the sret pointer, and put in a copy 9192 // from the sret argument into it. 9193 SmallVector<EVT, 1> ValueVTs; 9194 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9195 F.getReturnType()->getPointerTo( 9196 DAG.getDataLayout().getAllocaAddrSpace()), 9197 ValueVTs); 9198 MVT VT = ValueVTs[0].getSimpleVT(); 9199 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9200 Optional<ISD::NodeType> AssertOp = None; 9201 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9202 nullptr, F.getCallingConv(), AssertOp); 9203 9204 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9205 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9206 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9207 FuncInfo->DemoteRegister = SRetReg; 9208 NewRoot = 9209 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9210 DAG.setRoot(NewRoot); 9211 9212 // i indexes lowered arguments. Bump it past the hidden sret argument. 9213 ++i; 9214 } 9215 9216 SmallVector<SDValue, 4> Chains; 9217 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9218 for (const Argument &Arg : F.args()) { 9219 SmallVector<SDValue, 4> ArgValues; 9220 SmallVector<EVT, 4> ValueVTs; 9221 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9222 unsigned NumValues = ValueVTs.size(); 9223 if (NumValues == 0) 9224 continue; 9225 9226 bool ArgHasUses = !Arg.use_empty(); 9227 9228 // Elide the copying store if the target loaded this argument from a 9229 // suitable fixed stack object. 9230 if (Ins[i].Flags.isCopyElisionCandidate()) { 9231 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9232 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9233 InVals[i], ArgHasUses); 9234 } 9235 9236 // If this argument is unused then remember its value. It is used to generate 9237 // debugging information. 9238 bool isSwiftErrorArg = 9239 TLI->supportSwiftError() && 9240 Arg.hasAttribute(Attribute::SwiftError); 9241 if (!ArgHasUses && !isSwiftErrorArg) { 9242 SDB->setUnusedArgValue(&Arg, InVals[i]); 9243 9244 // Also remember any frame index for use in FastISel. 9245 if (FrameIndexSDNode *FI = 9246 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9247 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9248 } 9249 9250 for (unsigned Val = 0; Val != NumValues; ++Val) { 9251 EVT VT = ValueVTs[Val]; 9252 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9253 F.getCallingConv(), VT); 9254 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9255 *CurDAG->getContext(), F.getCallingConv(), VT); 9256 9257 // Even an apparant 'unused' swifterror argument needs to be returned. So 9258 // we do generate a copy for it that can be used on return from the 9259 // function. 9260 if (ArgHasUses || isSwiftErrorArg) { 9261 Optional<ISD::NodeType> AssertOp; 9262 if (Arg.hasAttribute(Attribute::SExt)) 9263 AssertOp = ISD::AssertSext; 9264 else if (Arg.hasAttribute(Attribute::ZExt)) 9265 AssertOp = ISD::AssertZext; 9266 9267 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9268 PartVT, VT, nullptr, 9269 F.getCallingConv(), AssertOp)); 9270 } 9271 9272 i += NumParts; 9273 } 9274 9275 // We don't need to do anything else for unused arguments. 9276 if (ArgValues.empty()) 9277 continue; 9278 9279 // Note down frame index. 9280 if (FrameIndexSDNode *FI = 9281 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9282 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9283 9284 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9285 SDB->getCurSDLoc()); 9286 9287 SDB->setValue(&Arg, Res); 9288 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9289 // We want to associate the argument with the frame index, among 9290 // involved operands, that correspond to the lowest address. The 9291 // getCopyFromParts function, called earlier, is swapping the order of 9292 // the operands to BUILD_PAIR depending on endianness. The result of 9293 // that swapping is that the least significant bits of the argument will 9294 // be in the first operand of the BUILD_PAIR node, and the most 9295 // significant bits will be in the second operand. 9296 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9297 if (LoadSDNode *LNode = 9298 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9299 if (FrameIndexSDNode *FI = 9300 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9301 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9302 } 9303 9304 // Update the SwiftErrorVRegDefMap. 9305 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9306 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9307 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9308 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9309 FuncInfo->SwiftErrorArg, Reg); 9310 } 9311 9312 // If this argument is live outside of the entry block, insert a copy from 9313 // wherever we got it to the vreg that other BB's will reference it as. 9314 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9315 // If we can, though, try to skip creating an unnecessary vreg. 9316 // FIXME: This isn't very clean... it would be nice to make this more 9317 // general. It's also subtly incompatible with the hacks FastISel 9318 // uses with vregs. 9319 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9320 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9321 FuncInfo->ValueMap[&Arg] = Reg; 9322 continue; 9323 } 9324 } 9325 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9326 FuncInfo->InitializeRegForValue(&Arg); 9327 SDB->CopyToExportRegsIfNeeded(&Arg); 9328 } 9329 } 9330 9331 if (!Chains.empty()) { 9332 Chains.push_back(NewRoot); 9333 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9334 } 9335 9336 DAG.setRoot(NewRoot); 9337 9338 assert(i == InVals.size() && "Argument register count mismatch!"); 9339 9340 // If any argument copy elisions occurred and we have debug info, update the 9341 // stale frame indices used in the dbg.declare variable info table. 9342 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9343 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9344 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9345 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9346 if (I != ArgCopyElisionFrameIndexMap.end()) 9347 VI.Slot = I->second; 9348 } 9349 } 9350 9351 // Finally, if the target has anything special to do, allow it to do so. 9352 EmitFunctionEntryCode(); 9353 } 9354 9355 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9356 /// ensure constants are generated when needed. Remember the virtual registers 9357 /// that need to be added to the Machine PHI nodes as input. We cannot just 9358 /// directly add them, because expansion might result in multiple MBB's for one 9359 /// BB. As such, the start of the BB might correspond to a different MBB than 9360 /// the end. 9361 void 9362 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9363 const Instruction *TI = LLVMBB->getTerminator(); 9364 9365 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9366 9367 // Check PHI nodes in successors that expect a value to be available from this 9368 // block. 9369 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9370 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9371 if (!isa<PHINode>(SuccBB->begin())) continue; 9372 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9373 9374 // If this terminator has multiple identical successors (common for 9375 // switches), only handle each succ once. 9376 if (!SuccsHandled.insert(SuccMBB).second) 9377 continue; 9378 9379 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9380 9381 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9382 // nodes and Machine PHI nodes, but the incoming operands have not been 9383 // emitted yet. 9384 for (const PHINode &PN : SuccBB->phis()) { 9385 // Ignore dead phi's. 9386 if (PN.use_empty()) 9387 continue; 9388 9389 // Skip empty types 9390 if (PN.getType()->isEmptyTy()) 9391 continue; 9392 9393 unsigned Reg; 9394 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9395 9396 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9397 unsigned &RegOut = ConstantsOut[C]; 9398 if (RegOut == 0) { 9399 RegOut = FuncInfo.CreateRegs(C->getType()); 9400 CopyValueToVirtualRegister(C, RegOut); 9401 } 9402 Reg = RegOut; 9403 } else { 9404 DenseMap<const Value *, unsigned>::iterator I = 9405 FuncInfo.ValueMap.find(PHIOp); 9406 if (I != FuncInfo.ValueMap.end()) 9407 Reg = I->second; 9408 else { 9409 assert(isa<AllocaInst>(PHIOp) && 9410 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9411 "Didn't codegen value into a register!??"); 9412 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9413 CopyValueToVirtualRegister(PHIOp, Reg); 9414 } 9415 } 9416 9417 // Remember that this register needs to added to the machine PHI node as 9418 // the input for this MBB. 9419 SmallVector<EVT, 4> ValueVTs; 9420 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9421 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9422 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9423 EVT VT = ValueVTs[vti]; 9424 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9425 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9426 FuncInfo.PHINodesToUpdate.push_back( 9427 std::make_pair(&*MBBI++, Reg + i)); 9428 Reg += NumRegisters; 9429 } 9430 } 9431 } 9432 9433 ConstantsOut.clear(); 9434 } 9435 9436 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9437 /// is 0. 9438 MachineBasicBlock * 9439 SelectionDAGBuilder::StackProtectorDescriptor:: 9440 AddSuccessorMBB(const BasicBlock *BB, 9441 MachineBasicBlock *ParentMBB, 9442 bool IsLikely, 9443 MachineBasicBlock *SuccMBB) { 9444 // If SuccBB has not been created yet, create it. 9445 if (!SuccMBB) { 9446 MachineFunction *MF = ParentMBB->getParent(); 9447 MachineFunction::iterator BBI(ParentMBB); 9448 SuccMBB = MF->CreateMachineBasicBlock(BB); 9449 MF->insert(++BBI, SuccMBB); 9450 } 9451 // Add it as a successor of ParentMBB. 9452 ParentMBB->addSuccessor( 9453 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9454 return SuccMBB; 9455 } 9456 9457 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9458 MachineFunction::iterator I(MBB); 9459 if (++I == FuncInfo.MF->end()) 9460 return nullptr; 9461 return &*I; 9462 } 9463 9464 /// During lowering new call nodes can be created (such as memset, etc.). 9465 /// Those will become new roots of the current DAG, but complications arise 9466 /// when they are tail calls. In such cases, the call lowering will update 9467 /// the root, but the builder still needs to know that a tail call has been 9468 /// lowered in order to avoid generating an additional return. 9469 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9470 // If the node is null, we do have a tail call. 9471 if (MaybeTC.getNode() != nullptr) 9472 DAG.setRoot(MaybeTC); 9473 else 9474 HasTailCall = true; 9475 } 9476 9477 uint64_t 9478 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9479 unsigned First, unsigned Last) const { 9480 assert(Last >= First); 9481 const APInt &LowCase = Clusters[First].Low->getValue(); 9482 const APInt &HighCase = Clusters[Last].High->getValue(); 9483 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9484 9485 // FIXME: A range of consecutive cases has 100% density, but only requires one 9486 // comparison to lower. We should discriminate against such consecutive ranges 9487 // in jump tables. 9488 9489 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9490 } 9491 9492 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9493 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9494 unsigned Last) const { 9495 assert(Last >= First); 9496 assert(TotalCases[Last] >= TotalCases[First]); 9497 uint64_t NumCases = 9498 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9499 return NumCases; 9500 } 9501 9502 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9503 unsigned First, unsigned Last, 9504 const SwitchInst *SI, 9505 MachineBasicBlock *DefaultMBB, 9506 CaseCluster &JTCluster) { 9507 assert(First <= Last); 9508 9509 auto Prob = BranchProbability::getZero(); 9510 unsigned NumCmps = 0; 9511 std::vector<MachineBasicBlock*> Table; 9512 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9513 9514 // Initialize probabilities in JTProbs. 9515 for (unsigned I = First; I <= Last; ++I) 9516 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9517 9518 for (unsigned I = First; I <= Last; ++I) { 9519 assert(Clusters[I].Kind == CC_Range); 9520 Prob += Clusters[I].Prob; 9521 const APInt &Low = Clusters[I].Low->getValue(); 9522 const APInt &High = Clusters[I].High->getValue(); 9523 NumCmps += (Low == High) ? 1 : 2; 9524 if (I != First) { 9525 // Fill the gap between this and the previous cluster. 9526 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9527 assert(PreviousHigh.slt(Low)); 9528 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9529 for (uint64_t J = 0; J < Gap; J++) 9530 Table.push_back(DefaultMBB); 9531 } 9532 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9533 for (uint64_t J = 0; J < ClusterSize; ++J) 9534 Table.push_back(Clusters[I].MBB); 9535 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9536 } 9537 9538 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9539 unsigned NumDests = JTProbs.size(); 9540 if (TLI.isSuitableForBitTests( 9541 NumDests, NumCmps, Clusters[First].Low->getValue(), 9542 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9543 // Clusters[First..Last] should be lowered as bit tests instead. 9544 return false; 9545 } 9546 9547 // Create the MBB that will load from and jump through the table. 9548 // Note: We create it here, but it's not inserted into the function yet. 9549 MachineFunction *CurMF = FuncInfo.MF; 9550 MachineBasicBlock *JumpTableMBB = 9551 CurMF->CreateMachineBasicBlock(SI->getParent()); 9552 9553 // Add successors. Note: use table order for determinism. 9554 SmallPtrSet<MachineBasicBlock *, 8> Done; 9555 for (MachineBasicBlock *Succ : Table) { 9556 if (Done.count(Succ)) 9557 continue; 9558 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9559 Done.insert(Succ); 9560 } 9561 JumpTableMBB->normalizeSuccProbs(); 9562 9563 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9564 ->createJumpTableIndex(Table); 9565 9566 // Set up the jump table info. 9567 bool UnreachableDefault = 9568 isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 9569 bool OmitRangeCheck = UnreachableDefault; 9570 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9571 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9572 Clusters[Last].High->getValue(), SI->getCondition(), 9573 nullptr, false, OmitRangeCheck); 9574 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9575 9576 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9577 JTCases.size() - 1, Prob); 9578 return true; 9579 } 9580 9581 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9582 const SwitchInst *SI, 9583 MachineBasicBlock *DefaultMBB) { 9584 #ifndef NDEBUG 9585 // Clusters must be non-empty, sorted, and only contain Range clusters. 9586 assert(!Clusters.empty()); 9587 for (CaseCluster &C : Clusters) 9588 assert(C.Kind == CC_Range); 9589 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9590 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9591 #endif 9592 9593 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9594 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9595 return; 9596 9597 const int64_t N = Clusters.size(); 9598 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9599 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9600 9601 if (N < 2 || N < MinJumpTableEntries) 9602 return; 9603 9604 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9605 SmallVector<unsigned, 8> TotalCases(N); 9606 for (unsigned i = 0; i < N; ++i) { 9607 const APInt &Hi = Clusters[i].High->getValue(); 9608 const APInt &Lo = Clusters[i].Low->getValue(); 9609 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9610 if (i != 0) 9611 TotalCases[i] += TotalCases[i - 1]; 9612 } 9613 9614 // Cheap case: the whole range may be suitable for jump table. 9615 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9616 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9617 assert(NumCases < UINT64_MAX / 100); 9618 assert(Range >= NumCases); 9619 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9620 CaseCluster JTCluster; 9621 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9622 Clusters[0] = JTCluster; 9623 Clusters.resize(1); 9624 return; 9625 } 9626 } 9627 9628 // The algorithm below is not suitable for -O0. 9629 if (TM.getOptLevel() == CodeGenOpt::None) 9630 return; 9631 9632 // Split Clusters into minimum number of dense partitions. The algorithm uses 9633 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9634 // for the Case Statement'" (1994), but builds the MinPartitions array in 9635 // reverse order to make it easier to reconstruct the partitions in ascending 9636 // order. In the choice between two optimal partitionings, it picks the one 9637 // which yields more jump tables. 9638 9639 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9640 SmallVector<unsigned, 8> MinPartitions(N); 9641 // LastElement[i] is the last element of the partition starting at i. 9642 SmallVector<unsigned, 8> LastElement(N); 9643 // PartitionsScore[i] is used to break ties when choosing between two 9644 // partitionings resulting in the same number of partitions. 9645 SmallVector<unsigned, 8> PartitionsScore(N); 9646 // For PartitionsScore, a small number of comparisons is considered as good as 9647 // a jump table and a single comparison is considered better than a jump 9648 // table. 9649 enum PartitionScores : unsigned { 9650 NoTable = 0, 9651 Table = 1, 9652 FewCases = 1, 9653 SingleCase = 2 9654 }; 9655 9656 // Base case: There is only one way to partition Clusters[N-1]. 9657 MinPartitions[N - 1] = 1; 9658 LastElement[N - 1] = N - 1; 9659 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9660 9661 // Note: loop indexes are signed to avoid underflow. 9662 for (int64_t i = N - 2; i >= 0; i--) { 9663 // Find optimal partitioning of Clusters[i..N-1]. 9664 // Baseline: Put Clusters[i] into a partition on its own. 9665 MinPartitions[i] = MinPartitions[i + 1] + 1; 9666 LastElement[i] = i; 9667 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9668 9669 // Search for a solution that results in fewer partitions. 9670 for (int64_t j = N - 1; j > i; j--) { 9671 // Try building a partition from Clusters[i..j]. 9672 uint64_t Range = getJumpTableRange(Clusters, i, j); 9673 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9674 assert(NumCases < UINT64_MAX / 100); 9675 assert(Range >= NumCases); 9676 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9677 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9678 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9679 int64_t NumEntries = j - i + 1; 9680 9681 if (NumEntries == 1) 9682 Score += PartitionScores::SingleCase; 9683 else if (NumEntries <= SmallNumberOfEntries) 9684 Score += PartitionScores::FewCases; 9685 else if (NumEntries >= MinJumpTableEntries) 9686 Score += PartitionScores::Table; 9687 9688 // If this leads to fewer partitions, or to the same number of 9689 // partitions with better score, it is a better partitioning. 9690 if (NumPartitions < MinPartitions[i] || 9691 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9692 MinPartitions[i] = NumPartitions; 9693 LastElement[i] = j; 9694 PartitionsScore[i] = Score; 9695 } 9696 } 9697 } 9698 } 9699 9700 // Iterate over the partitions, replacing some with jump tables in-place. 9701 unsigned DstIndex = 0; 9702 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9703 Last = LastElement[First]; 9704 assert(Last >= First); 9705 assert(DstIndex <= First); 9706 unsigned NumClusters = Last - First + 1; 9707 9708 CaseCluster JTCluster; 9709 if (NumClusters >= MinJumpTableEntries && 9710 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9711 Clusters[DstIndex++] = JTCluster; 9712 } else { 9713 for (unsigned I = First; I <= Last; ++I) 9714 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9715 } 9716 } 9717 Clusters.resize(DstIndex); 9718 } 9719 9720 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9721 unsigned First, unsigned Last, 9722 const SwitchInst *SI, 9723 CaseCluster &BTCluster) { 9724 assert(First <= Last); 9725 if (First == Last) 9726 return false; 9727 9728 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9729 unsigned NumCmps = 0; 9730 for (int64_t I = First; I <= Last; ++I) { 9731 assert(Clusters[I].Kind == CC_Range); 9732 Dests.set(Clusters[I].MBB->getNumber()); 9733 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9734 } 9735 unsigned NumDests = Dests.count(); 9736 9737 APInt Low = Clusters[First].Low->getValue(); 9738 APInt High = Clusters[Last].High->getValue(); 9739 assert(Low.slt(High)); 9740 9741 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9742 const DataLayout &DL = DAG.getDataLayout(); 9743 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9744 return false; 9745 9746 APInt LowBound; 9747 APInt CmpRange; 9748 9749 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9750 assert(TLI.rangeFitsInWord(Low, High, DL) && 9751 "Case range must fit in bit mask!"); 9752 9753 // Check if the clusters cover a contiguous range such that no value in the 9754 // range will jump to the default statement. 9755 bool ContiguousRange = true; 9756 for (int64_t I = First + 1; I <= Last; ++I) { 9757 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9758 ContiguousRange = false; 9759 break; 9760 } 9761 } 9762 9763 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9764 // Optimize the case where all the case values fit in a word without having 9765 // to subtract minValue. In this case, we can optimize away the subtraction. 9766 LowBound = APInt::getNullValue(Low.getBitWidth()); 9767 CmpRange = High; 9768 ContiguousRange = false; 9769 } else { 9770 LowBound = Low; 9771 CmpRange = High - Low; 9772 } 9773 9774 CaseBitsVector CBV; 9775 auto TotalProb = BranchProbability::getZero(); 9776 for (unsigned i = First; i <= Last; ++i) { 9777 // Find the CaseBits for this destination. 9778 unsigned j; 9779 for (j = 0; j < CBV.size(); ++j) 9780 if (CBV[j].BB == Clusters[i].MBB) 9781 break; 9782 if (j == CBV.size()) 9783 CBV.push_back( 9784 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9785 CaseBits *CB = &CBV[j]; 9786 9787 // Update Mask, Bits and ExtraProb. 9788 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9789 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9790 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9791 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9792 CB->Bits += Hi - Lo + 1; 9793 CB->ExtraProb += Clusters[i].Prob; 9794 TotalProb += Clusters[i].Prob; 9795 } 9796 9797 BitTestInfo BTI; 9798 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 9799 // Sort by probability first, number of bits second, bit mask third. 9800 if (a.ExtraProb != b.ExtraProb) 9801 return a.ExtraProb > b.ExtraProb; 9802 if (a.Bits != b.Bits) 9803 return a.Bits > b.Bits; 9804 return a.Mask < b.Mask; 9805 }); 9806 9807 for (auto &CB : CBV) { 9808 MachineBasicBlock *BitTestBB = 9809 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9810 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9811 } 9812 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9813 SI->getCondition(), -1U, MVT::Other, false, 9814 ContiguousRange, nullptr, nullptr, std::move(BTI), 9815 TotalProb); 9816 9817 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9818 BitTestCases.size() - 1, TotalProb); 9819 return true; 9820 } 9821 9822 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9823 const SwitchInst *SI) { 9824 // Partition Clusters into as few subsets as possible, where each subset has a 9825 // range that fits in a machine word and has <= 3 unique destinations. 9826 9827 #ifndef NDEBUG 9828 // Clusters must be sorted and contain Range or JumpTable clusters. 9829 assert(!Clusters.empty()); 9830 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9831 for (const CaseCluster &C : Clusters) 9832 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9833 for (unsigned i = 1; i < Clusters.size(); ++i) 9834 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9835 #endif 9836 9837 // The algorithm below is not suitable for -O0. 9838 if (TM.getOptLevel() == CodeGenOpt::None) 9839 return; 9840 9841 // If target does not have legal shift left, do not emit bit tests at all. 9842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9843 const DataLayout &DL = DAG.getDataLayout(); 9844 9845 EVT PTy = TLI.getPointerTy(DL); 9846 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9847 return; 9848 9849 int BitWidth = PTy.getSizeInBits(); 9850 const int64_t N = Clusters.size(); 9851 9852 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9853 SmallVector<unsigned, 8> MinPartitions(N); 9854 // LastElement[i] is the last element of the partition starting at i. 9855 SmallVector<unsigned, 8> LastElement(N); 9856 9857 // FIXME: This might not be the best algorithm for finding bit test clusters. 9858 9859 // Base case: There is only one way to partition Clusters[N-1]. 9860 MinPartitions[N - 1] = 1; 9861 LastElement[N - 1] = N - 1; 9862 9863 // Note: loop indexes are signed to avoid underflow. 9864 for (int64_t i = N - 2; i >= 0; --i) { 9865 // Find optimal partitioning of Clusters[i..N-1]. 9866 // Baseline: Put Clusters[i] into a partition on its own. 9867 MinPartitions[i] = MinPartitions[i + 1] + 1; 9868 LastElement[i] = i; 9869 9870 // Search for a solution that results in fewer partitions. 9871 // Note: the search is limited by BitWidth, reducing time complexity. 9872 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9873 // Try building a partition from Clusters[i..j]. 9874 9875 // Check the range. 9876 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9877 Clusters[j].High->getValue(), DL)) 9878 continue; 9879 9880 // Check nbr of destinations and cluster types. 9881 // FIXME: This works, but doesn't seem very efficient. 9882 bool RangesOnly = true; 9883 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9884 for (int64_t k = i; k <= j; k++) { 9885 if (Clusters[k].Kind != CC_Range) { 9886 RangesOnly = false; 9887 break; 9888 } 9889 Dests.set(Clusters[k].MBB->getNumber()); 9890 } 9891 if (!RangesOnly || Dests.count() > 3) 9892 break; 9893 9894 // Check if it's a better partition. 9895 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9896 if (NumPartitions < MinPartitions[i]) { 9897 // Found a better partition. 9898 MinPartitions[i] = NumPartitions; 9899 LastElement[i] = j; 9900 } 9901 } 9902 } 9903 9904 // Iterate over the partitions, replacing with bit-test clusters in-place. 9905 unsigned DstIndex = 0; 9906 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9907 Last = LastElement[First]; 9908 assert(First <= Last); 9909 assert(DstIndex <= First); 9910 9911 CaseCluster BitTestCluster; 9912 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9913 Clusters[DstIndex++] = BitTestCluster; 9914 } else { 9915 size_t NumClusters = Last - First + 1; 9916 std::memmove(&Clusters[DstIndex], &Clusters[First], 9917 sizeof(Clusters[0]) * NumClusters); 9918 DstIndex += NumClusters; 9919 } 9920 } 9921 Clusters.resize(DstIndex); 9922 } 9923 9924 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9925 MachineBasicBlock *SwitchMBB, 9926 MachineBasicBlock *DefaultMBB) { 9927 MachineFunction *CurMF = FuncInfo.MF; 9928 MachineBasicBlock *NextMBB = nullptr; 9929 MachineFunction::iterator BBI(W.MBB); 9930 if (++BBI != FuncInfo.MF->end()) 9931 NextMBB = &*BBI; 9932 9933 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9934 9935 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9936 9937 if (Size == 2 && W.MBB == SwitchMBB) { 9938 // If any two of the cases has the same destination, and if one value 9939 // is the same as the other, but has one bit unset that the other has set, 9940 // use bit manipulation to do two compares at once. For example: 9941 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9942 // TODO: This could be extended to merge any 2 cases in switches with 3 9943 // cases. 9944 // TODO: Handle cases where W.CaseBB != SwitchBB. 9945 CaseCluster &Small = *W.FirstCluster; 9946 CaseCluster &Big = *W.LastCluster; 9947 9948 if (Small.Low == Small.High && Big.Low == Big.High && 9949 Small.MBB == Big.MBB) { 9950 const APInt &SmallValue = Small.Low->getValue(); 9951 const APInt &BigValue = Big.Low->getValue(); 9952 9953 // Check that there is only one bit different. 9954 APInt CommonBit = BigValue ^ SmallValue; 9955 if (CommonBit.isPowerOf2()) { 9956 SDValue CondLHS = getValue(Cond); 9957 EVT VT = CondLHS.getValueType(); 9958 SDLoc DL = getCurSDLoc(); 9959 9960 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9961 DAG.getConstant(CommonBit, DL, VT)); 9962 SDValue Cond = DAG.getSetCC( 9963 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9964 ISD::SETEQ); 9965 9966 // Update successor info. 9967 // Both Small and Big will jump to Small.BB, so we sum up the 9968 // probabilities. 9969 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9970 if (BPI) 9971 addSuccessorWithProb( 9972 SwitchMBB, DefaultMBB, 9973 // The default destination is the first successor in IR. 9974 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9975 else 9976 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9977 9978 // Insert the true branch. 9979 SDValue BrCond = 9980 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9981 DAG.getBasicBlock(Small.MBB)); 9982 // Insert the false branch. 9983 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9984 DAG.getBasicBlock(DefaultMBB)); 9985 9986 DAG.setRoot(BrCond); 9987 return; 9988 } 9989 } 9990 } 9991 9992 if (TM.getOptLevel() != CodeGenOpt::None) { 9993 // Here, we order cases by probability so the most likely case will be 9994 // checked first. However, two clusters can have the same probability in 9995 // which case their relative ordering is non-deterministic. So we use Low 9996 // as a tie-breaker as clusters are guaranteed to never overlap. 9997 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9998 [](const CaseCluster &a, const CaseCluster &b) { 9999 return a.Prob != b.Prob ? 10000 a.Prob > b.Prob : 10001 a.Low->getValue().slt(b.Low->getValue()); 10002 }); 10003 10004 // Rearrange the case blocks so that the last one falls through if possible 10005 // without changing the order of probabilities. 10006 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10007 --I; 10008 if (I->Prob > W.LastCluster->Prob) 10009 break; 10010 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10011 std::swap(*I, *W.LastCluster); 10012 break; 10013 } 10014 } 10015 } 10016 10017 // Compute total probability. 10018 BranchProbability DefaultProb = W.DefaultProb; 10019 BranchProbability UnhandledProbs = DefaultProb; 10020 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10021 UnhandledProbs += I->Prob; 10022 10023 MachineBasicBlock *CurMBB = W.MBB; 10024 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10025 MachineBasicBlock *Fallthrough; 10026 if (I == W.LastCluster) { 10027 // For the last cluster, fall through to the default destination. 10028 Fallthrough = DefaultMBB; 10029 } else { 10030 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10031 CurMF->insert(BBI, Fallthrough); 10032 // Put Cond in a virtual register to make it available from the new blocks. 10033 ExportFromCurrentBlock(Cond); 10034 } 10035 UnhandledProbs -= I->Prob; 10036 10037 switch (I->Kind) { 10038 case CC_JumpTable: { 10039 // FIXME: Optimize away range check based on pivot comparisons. 10040 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 10041 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 10042 10043 // The jump block hasn't been inserted yet; insert it here. 10044 MachineBasicBlock *JumpMBB = JT->MBB; 10045 CurMF->insert(BBI, JumpMBB); 10046 10047 auto JumpProb = I->Prob; 10048 auto FallthroughProb = UnhandledProbs; 10049 10050 // If the default statement is a target of the jump table, we evenly 10051 // distribute the default probability to successors of CurMBB. Also 10052 // update the probability on the edge from JumpMBB to Fallthrough. 10053 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10054 SE = JumpMBB->succ_end(); 10055 SI != SE; ++SI) { 10056 if (*SI == DefaultMBB) { 10057 JumpProb += DefaultProb / 2; 10058 FallthroughProb -= DefaultProb / 2; 10059 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10060 JumpMBB->normalizeSuccProbs(); 10061 break; 10062 } 10063 } 10064 10065 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10066 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10067 CurMBB->normalizeSuccProbs(); 10068 10069 // The jump table header will be inserted in our current block, do the 10070 // range check, and fall through to our fallthrough block. 10071 JTH->HeaderBB = CurMBB; 10072 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10073 10074 // If we're in the right place, emit the jump table header right now. 10075 if (CurMBB == SwitchMBB) { 10076 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10077 JTH->Emitted = true; 10078 } 10079 break; 10080 } 10081 case CC_BitTests: { 10082 // FIXME: Optimize away range check based on pivot comparisons. 10083 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10084 10085 // The bit test blocks haven't been inserted yet; insert them here. 10086 for (BitTestCase &BTC : BTB->Cases) 10087 CurMF->insert(BBI, BTC.ThisBB); 10088 10089 // Fill in fields of the BitTestBlock. 10090 BTB->Parent = CurMBB; 10091 BTB->Default = Fallthrough; 10092 10093 BTB->DefaultProb = UnhandledProbs; 10094 // If the cases in bit test don't form a contiguous range, we evenly 10095 // distribute the probability on the edge to Fallthrough to two 10096 // successors of CurMBB. 10097 if (!BTB->ContiguousRange) { 10098 BTB->Prob += DefaultProb / 2; 10099 BTB->DefaultProb -= DefaultProb / 2; 10100 } 10101 10102 // If we're in the right place, emit the bit test header right now. 10103 if (CurMBB == SwitchMBB) { 10104 visitBitTestHeader(*BTB, SwitchMBB); 10105 BTB->Emitted = true; 10106 } 10107 break; 10108 } 10109 case CC_Range: { 10110 const Value *RHS, *LHS, *MHS; 10111 ISD::CondCode CC; 10112 if (I->Low == I->High) { 10113 // Check Cond == I->Low. 10114 CC = ISD::SETEQ; 10115 LHS = Cond; 10116 RHS=I->Low; 10117 MHS = nullptr; 10118 } else { 10119 // Check I->Low <= Cond <= I->High. 10120 CC = ISD::SETLE; 10121 LHS = I->Low; 10122 MHS = Cond; 10123 RHS = I->High; 10124 } 10125 10126 // The false probability is the sum of all unhandled cases. 10127 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10128 getCurSDLoc(), I->Prob, UnhandledProbs); 10129 10130 if (CurMBB == SwitchMBB) 10131 visitSwitchCase(CB, SwitchMBB); 10132 else 10133 SwitchCases.push_back(CB); 10134 10135 break; 10136 } 10137 } 10138 CurMBB = Fallthrough; 10139 } 10140 } 10141 10142 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10143 CaseClusterIt First, 10144 CaseClusterIt Last) { 10145 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10146 if (X.Prob != CC.Prob) 10147 return X.Prob > CC.Prob; 10148 10149 // Ties are broken by comparing the case value. 10150 return X.Low->getValue().slt(CC.Low->getValue()); 10151 }); 10152 } 10153 10154 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10155 const SwitchWorkListItem &W, 10156 Value *Cond, 10157 MachineBasicBlock *SwitchMBB) { 10158 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10159 "Clusters not sorted?"); 10160 10161 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10162 10163 // Balance the tree based on branch probabilities to create a near-optimal (in 10164 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10165 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10166 CaseClusterIt LastLeft = W.FirstCluster; 10167 CaseClusterIt FirstRight = W.LastCluster; 10168 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10169 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10170 10171 // Move LastLeft and FirstRight towards each other from opposite directions to 10172 // find a partitioning of the clusters which balances the probability on both 10173 // sides. If LeftProb and RightProb are equal, alternate which side is 10174 // taken to ensure 0-probability nodes are distributed evenly. 10175 unsigned I = 0; 10176 while (LastLeft + 1 < FirstRight) { 10177 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10178 LeftProb += (++LastLeft)->Prob; 10179 else 10180 RightProb += (--FirstRight)->Prob; 10181 I++; 10182 } 10183 10184 while (true) { 10185 // Our binary search tree differs from a typical BST in that ours can have up 10186 // to three values in each leaf. The pivot selection above doesn't take that 10187 // into account, which means the tree might require more nodes and be less 10188 // efficient. We compensate for this here. 10189 10190 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10191 unsigned NumRight = W.LastCluster - FirstRight + 1; 10192 10193 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10194 // If one side has less than 3 clusters, and the other has more than 3, 10195 // consider taking a cluster from the other side. 10196 10197 if (NumLeft < NumRight) { 10198 // Consider moving the first cluster on the right to the left side. 10199 CaseCluster &CC = *FirstRight; 10200 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10201 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10202 if (LeftSideRank <= RightSideRank) { 10203 // Moving the cluster to the left does not demote it. 10204 ++LastLeft; 10205 ++FirstRight; 10206 continue; 10207 } 10208 } else { 10209 assert(NumRight < NumLeft); 10210 // Consider moving the last element on the left to the right side. 10211 CaseCluster &CC = *LastLeft; 10212 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10213 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10214 if (RightSideRank <= LeftSideRank) { 10215 // Moving the cluster to the right does not demot it. 10216 --LastLeft; 10217 --FirstRight; 10218 continue; 10219 } 10220 } 10221 } 10222 break; 10223 } 10224 10225 assert(LastLeft + 1 == FirstRight); 10226 assert(LastLeft >= W.FirstCluster); 10227 assert(FirstRight <= W.LastCluster); 10228 10229 // Use the first element on the right as pivot since we will make less-than 10230 // comparisons against it. 10231 CaseClusterIt PivotCluster = FirstRight; 10232 assert(PivotCluster > W.FirstCluster); 10233 assert(PivotCluster <= W.LastCluster); 10234 10235 CaseClusterIt FirstLeft = W.FirstCluster; 10236 CaseClusterIt LastRight = W.LastCluster; 10237 10238 const ConstantInt *Pivot = PivotCluster->Low; 10239 10240 // New blocks will be inserted immediately after the current one. 10241 MachineFunction::iterator BBI(W.MBB); 10242 ++BBI; 10243 10244 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10245 // we can branch to its destination directly if it's squeezed exactly in 10246 // between the known lower bound and Pivot - 1. 10247 MachineBasicBlock *LeftMBB; 10248 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10249 FirstLeft->Low == W.GE && 10250 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10251 LeftMBB = FirstLeft->MBB; 10252 } else { 10253 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10254 FuncInfo.MF->insert(BBI, LeftMBB); 10255 WorkList.push_back( 10256 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10257 // Put Cond in a virtual register to make it available from the new blocks. 10258 ExportFromCurrentBlock(Cond); 10259 } 10260 10261 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10262 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10263 // directly if RHS.High equals the current upper bound. 10264 MachineBasicBlock *RightMBB; 10265 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10266 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10267 RightMBB = FirstRight->MBB; 10268 } else { 10269 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10270 FuncInfo.MF->insert(BBI, RightMBB); 10271 WorkList.push_back( 10272 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10273 // Put Cond in a virtual register to make it available from the new blocks. 10274 ExportFromCurrentBlock(Cond); 10275 } 10276 10277 // Create the CaseBlock record that will be used to lower the branch. 10278 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10279 getCurSDLoc(), LeftProb, RightProb); 10280 10281 if (W.MBB == SwitchMBB) 10282 visitSwitchCase(CB, SwitchMBB); 10283 else 10284 SwitchCases.push_back(CB); 10285 } 10286 10287 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10288 // from the swith statement. 10289 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10290 BranchProbability PeeledCaseProb) { 10291 if (PeeledCaseProb == BranchProbability::getOne()) 10292 return BranchProbability::getZero(); 10293 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10294 10295 uint32_t Numerator = CaseProb.getNumerator(); 10296 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10297 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10298 } 10299 10300 // Try to peel the top probability case if it exceeds the threshold. 10301 // Return current MachineBasicBlock for the switch statement if the peeling 10302 // does not occur. 10303 // If the peeling is performed, return the newly created MachineBasicBlock 10304 // for the peeled switch statement. Also update Clusters to remove the peeled 10305 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10306 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10307 const SwitchInst &SI, CaseClusterVector &Clusters, 10308 BranchProbability &PeeledCaseProb) { 10309 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10310 10311 // Don't perform if there is only one cluster or optimizing for size. 10312 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10313 TM.getOptLevel() == CodeGenOpt::None || 10314 SwitchMBB->getParent()->getFunction().optForMinSize()) 10315 return SwitchMBB; 10316 10317 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10318 unsigned PeeledCaseIndex = 0; 10319 bool SwitchPeeled = false; 10320 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10321 CaseCluster &CC = Clusters[Index]; 10322 if (CC.Prob < TopCaseProb) 10323 continue; 10324 TopCaseProb = CC.Prob; 10325 PeeledCaseIndex = Index; 10326 SwitchPeeled = true; 10327 } 10328 if (!SwitchPeeled) 10329 return SwitchMBB; 10330 10331 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10332 << TopCaseProb << "\n"); 10333 10334 // Record the MBB for the peeled switch statement. 10335 MachineFunction::iterator BBI(SwitchMBB); 10336 ++BBI; 10337 MachineBasicBlock *PeeledSwitchMBB = 10338 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10339 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10340 10341 ExportFromCurrentBlock(SI.getCondition()); 10342 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10343 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10344 nullptr, nullptr, TopCaseProb.getCompl()}; 10345 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10346 10347 Clusters.erase(PeeledCaseIt); 10348 for (CaseCluster &CC : Clusters) { 10349 LLVM_DEBUG( 10350 dbgs() << "Scale the probablity for one cluster, before scaling: " 10351 << CC.Prob << "\n"); 10352 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10353 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10354 } 10355 PeeledCaseProb = TopCaseProb; 10356 return PeeledSwitchMBB; 10357 } 10358 10359 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10360 // Extract cases from the switch. 10361 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10362 CaseClusterVector Clusters; 10363 10364 Clusters.reserve(SI.getNumCases()); 10365 for (auto I : SI.cases()) { 10366 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10367 const ConstantInt *CaseVal = I.getCaseValue(); 10368 BranchProbability Prob = 10369 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10370 : BranchProbability(1, SI.getNumCases() + 1); 10371 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10372 } 10373 10374 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10375 10376 // Cluster adjacent cases with the same destination. We do this at all 10377 // optimization levels because it's cheap to do and will make codegen faster 10378 // if there are many clusters. 10379 sortAndRangeify(Clusters); 10380 10381 // The branch probablity of the peeled case. 10382 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10383 MachineBasicBlock *PeeledSwitchMBB = 10384 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10385 10386 // If there is only the default destination, jump there directly. 10387 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10388 if (Clusters.empty()) { 10389 assert(PeeledSwitchMBB == SwitchMBB); 10390 SwitchMBB->addSuccessor(DefaultMBB); 10391 if (DefaultMBB != NextBlock(SwitchMBB)) { 10392 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10393 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10394 } 10395 return; 10396 } 10397 10398 findJumpTables(Clusters, &SI, DefaultMBB); 10399 findBitTestClusters(Clusters, &SI); 10400 10401 LLVM_DEBUG({ 10402 dbgs() << "Case clusters: "; 10403 for (const CaseCluster &C : Clusters) { 10404 if (C.Kind == CC_JumpTable) 10405 dbgs() << "JT:"; 10406 if (C.Kind == CC_BitTests) 10407 dbgs() << "BT:"; 10408 10409 C.Low->getValue().print(dbgs(), true); 10410 if (C.Low != C.High) { 10411 dbgs() << '-'; 10412 C.High->getValue().print(dbgs(), true); 10413 } 10414 dbgs() << ' '; 10415 } 10416 dbgs() << '\n'; 10417 }); 10418 10419 assert(!Clusters.empty()); 10420 SwitchWorkList WorkList; 10421 CaseClusterIt First = Clusters.begin(); 10422 CaseClusterIt Last = Clusters.end() - 1; 10423 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10424 // Scale the branchprobability for DefaultMBB if the peel occurs and 10425 // DefaultMBB is not replaced. 10426 if (PeeledCaseProb != BranchProbability::getZero() && 10427 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10428 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10429 WorkList.push_back( 10430 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10431 10432 while (!WorkList.empty()) { 10433 SwitchWorkListItem W = WorkList.back(); 10434 WorkList.pop_back(); 10435 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10436 10437 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10438 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10439 // For optimized builds, lower large range as a balanced binary tree. 10440 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10441 continue; 10442 } 10443 10444 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10445 } 10446 } 10447