1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/BlockFrequencyInfo.h" 27 #include "llvm/Analysis/BranchProbabilityInfo.h" 28 #include "llvm/Analysis/ConstantFolding.h" 29 #include "llvm/Analysis/EHPersonalities.h" 30 #include "llvm/Analysis/Loads.h" 31 #include "llvm/Analysis/MemoryLocation.h" 32 #include "llvm/Analysis/ProfileSummaryInfo.h" 33 #include "llvm/Analysis/TargetLibraryInfo.h" 34 #include "llvm/Analysis/ValueTracking.h" 35 #include "llvm/Analysis/VectorUtils.h" 36 #include "llvm/CodeGen/Analysis.h" 37 #include "llvm/CodeGen/FunctionLoweringInfo.h" 38 #include "llvm/CodeGen/GCMetadata.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineMemOperand.h" 46 #include "llvm/CodeGen/MachineModuleInfo.h" 47 #include "llvm/CodeGen/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/RuntimeLibcalls.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 52 #include "llvm/CodeGen/StackMaps.h" 53 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 54 #include "llvm/CodeGen/TargetFrameLowering.h" 55 #include "llvm/CodeGen/TargetInstrInfo.h" 56 #include "llvm/CodeGen/TargetOpcodes.h" 57 #include "llvm/CodeGen/TargetRegisterInfo.h" 58 #include "llvm/CodeGen/TargetSubtargetInfo.h" 59 #include "llvm/CodeGen/WinEHFuncInfo.h" 60 #include "llvm/IR/Argument.h" 61 #include "llvm/IR/Attributes.h" 62 #include "llvm/IR/BasicBlock.h" 63 #include "llvm/IR/CFG.h" 64 #include "llvm/IR/CallingConv.h" 65 #include "llvm/IR/Constant.h" 66 #include "llvm/IR/ConstantRange.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DebugInfoMetadata.h" 70 #include "llvm/IR/DerivedTypes.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GetElementPtrTypeIterator.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/IntrinsicsAArch64.h" 79 #include "llvm/IR/IntrinsicsWebAssembly.h" 80 #include "llvm/IR/LLVMContext.h" 81 #include "llvm/IR/Metadata.h" 82 #include "llvm/IR/Module.h" 83 #include "llvm/IR/Operator.h" 84 #include "llvm/IR/PatternMatch.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/MC/MCSymbol.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/Casting.h" 92 #include "llvm/Support/CommandLine.h" 93 #include "llvm/Support/Compiler.h" 94 #include "llvm/Support/Debug.h" 95 #include "llvm/Support/MathExtras.h" 96 #include "llvm/Support/raw_ostream.h" 97 #include "llvm/Target/TargetIntrinsicInfo.h" 98 #include "llvm/Target/TargetMachine.h" 99 #include "llvm/Target/TargetOptions.h" 100 #include "llvm/Transforms/Utils/Local.h" 101 #include <cstddef> 102 #include <cstring> 103 #include <iterator> 104 #include <limits> 105 #include <numeric> 106 #include <tuple> 107 108 using namespace llvm; 109 using namespace PatternMatch; 110 using namespace SwitchCG; 111 112 #define DEBUG_TYPE "isel" 113 114 /// LimitFloatPrecision - Generate low-precision inline sequences for 115 /// some float libcalls (6, 8 or 12 bits). 116 static unsigned LimitFloatPrecision; 117 118 static cl::opt<bool> 119 InsertAssertAlign("insert-assert-align", cl::init(true), 120 cl::desc("Insert the experimental `assertalign` node."), 121 cl::ReallyHidden); 122 123 static cl::opt<unsigned, true> 124 LimitFPPrecision("limit-float-precision", 125 cl::desc("Generate low-precision inline sequences " 126 "for some float libcalls"), 127 cl::location(LimitFloatPrecision), cl::Hidden, 128 cl::init(0)); 129 130 static cl::opt<unsigned> SwitchPeelThreshold( 131 "switch-peel-threshold", cl::Hidden, cl::init(66), 132 cl::desc("Set the case probability threshold for peeling the case from a " 133 "switch statement. A value greater than 100 will void this " 134 "optimization")); 135 136 // Limit the width of DAG chains. This is important in general to prevent 137 // DAG-based analysis from blowing up. For example, alias analysis and 138 // load clustering may not complete in reasonable time. It is difficult to 139 // recognize and avoid this situation within each individual analysis, and 140 // future analyses are likely to have the same behavior. Limiting DAG width is 141 // the safe approach and will be especially important with global DAGs. 142 // 143 // MaxParallelChains default is arbitrarily high to avoid affecting 144 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 145 // sequence over this should have been converted to llvm.memcpy by the 146 // frontend. It is easy to induce this behavior with .ll code such as: 147 // %buffer = alloca [4096 x i8] 148 // %data = load [4096 x i8]* %argPtr 149 // store [4096 x i8] %data, [4096 x i8]* %buffer 150 static const unsigned MaxParallelChains = 64; 151 152 // Return the calling convention if the Value passed requires ABI mangling as it 153 // is a parameter to a function or a return value from a function which is not 154 // an intrinsic. 155 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 156 if (auto *R = dyn_cast<ReturnInst>(V)) 157 return R->getParent()->getParent()->getCallingConv(); 158 159 if (auto *CI = dyn_cast<CallInst>(V)) { 160 const bool IsInlineAsm = CI->isInlineAsm(); 161 const bool IsIndirectFunctionCall = 162 !IsInlineAsm && !CI->getCalledFunction(); 163 164 // It is possible that the call instruction is an inline asm statement or an 165 // indirect function call in which case the return value of 166 // getCalledFunction() would be nullptr. 167 const bool IsInstrinsicCall = 168 !IsInlineAsm && !IsIndirectFunctionCall && 169 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 170 171 if (!IsInlineAsm && !IsInstrinsicCall) 172 return CI->getCallingConv(); 173 } 174 175 return None; 176 } 177 178 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 179 const SDValue *Parts, unsigned NumParts, 180 MVT PartVT, EVT ValueVT, const Value *V, 181 Optional<CallingConv::ID> CC); 182 183 /// getCopyFromParts - Create a value that contains the specified legal parts 184 /// combined into the value they represent. If the parts combine to a type 185 /// larger than ValueVT then AssertOp can be used to specify whether the extra 186 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 187 /// (ISD::AssertSext). 188 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 189 const SDValue *Parts, unsigned NumParts, 190 MVT PartVT, EVT ValueVT, const Value *V, 191 Optional<CallingConv::ID> CC = None, 192 Optional<ISD::NodeType> AssertOp = None) { 193 // Let the target assemble the parts if it wants to 194 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 195 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 196 PartVT, ValueVT, CC)) 197 return Val; 198 199 if (ValueVT.isVector()) 200 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 201 CC); 202 203 assert(NumParts > 0 && "No parts to assemble!"); 204 SDValue Val = Parts[0]; 205 206 if (NumParts > 1) { 207 // Assemble the value from multiple parts. 208 if (ValueVT.isInteger()) { 209 unsigned PartBits = PartVT.getSizeInBits(); 210 unsigned ValueBits = ValueVT.getSizeInBits(); 211 212 // Assemble the power of 2 part. 213 unsigned RoundParts = 214 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 215 unsigned RoundBits = PartBits * RoundParts; 216 EVT RoundVT = RoundBits == ValueBits ? 217 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 218 SDValue Lo, Hi; 219 220 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 221 222 if (RoundParts > 2) { 223 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 224 PartVT, HalfVT, V); 225 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 226 RoundParts / 2, PartVT, HalfVT, V); 227 } else { 228 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 229 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 230 } 231 232 if (DAG.getDataLayout().isBigEndian()) 233 std::swap(Lo, Hi); 234 235 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 236 237 if (RoundParts < NumParts) { 238 // Assemble the trailing non-power-of-2 part. 239 unsigned OddParts = NumParts - RoundParts; 240 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 241 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 242 OddVT, V, CC); 243 244 // Combine the round and odd parts. 245 Lo = Val; 246 if (DAG.getDataLayout().isBigEndian()) 247 std::swap(Lo, Hi); 248 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 249 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 250 Hi = 251 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 252 DAG.getConstant(Lo.getValueSizeInBits(), DL, 253 TLI.getPointerTy(DAG.getDataLayout()))); 254 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 255 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 256 } 257 } else if (PartVT.isFloatingPoint()) { 258 // FP split into multiple FP parts (for ppcf128) 259 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 260 "Unexpected split"); 261 SDValue Lo, Hi; 262 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 263 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 264 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 265 std::swap(Lo, Hi); 266 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 267 } else { 268 // FP split into integer parts (soft fp) 269 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 270 !PartVT.isVector() && "Unexpected split"); 271 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 272 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 273 } 274 } 275 276 // There is now one part, held in Val. Correct it to match ValueVT. 277 // PartEVT is the type of the register class that holds the value. 278 // ValueVT is the type of the inline asm operation. 279 EVT PartEVT = Val.getValueType(); 280 281 if (PartEVT == ValueVT) 282 return Val; 283 284 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 285 ValueVT.bitsLT(PartEVT)) { 286 // For an FP value in an integer part, we need to truncate to the right 287 // width first. 288 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 289 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 290 } 291 292 // Handle types that have the same size. 293 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 294 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 295 296 // Handle types with different sizes. 297 if (PartEVT.isInteger() && ValueVT.isInteger()) { 298 if (ValueVT.bitsLT(PartEVT)) { 299 // For a truncate, see if we have any information to 300 // indicate whether the truncated bits will always be 301 // zero or sign-extension. 302 if (AssertOp.hasValue()) 303 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 304 DAG.getValueType(ValueVT)); 305 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 306 } 307 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 308 } 309 310 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 311 // FP_ROUND's are always exact here. 312 if (ValueVT.bitsLT(Val.getValueType())) 313 return DAG.getNode( 314 ISD::FP_ROUND, DL, ValueVT, Val, 315 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 316 317 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 318 } 319 320 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 321 // then truncating. 322 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 323 ValueVT.bitsLT(PartEVT)) { 324 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 325 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 326 } 327 328 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 329 } 330 331 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 332 const Twine &ErrMsg) { 333 const Instruction *I = dyn_cast_or_null<Instruction>(V); 334 if (!V) 335 return Ctx.emitError(ErrMsg); 336 337 const char *AsmError = ", possible invalid constraint for vector type"; 338 if (const CallInst *CI = dyn_cast<CallInst>(I)) 339 if (CI->isInlineAsm()) 340 return Ctx.emitError(I, ErrMsg + AsmError); 341 342 return Ctx.emitError(I, ErrMsg); 343 } 344 345 /// getCopyFromPartsVector - Create a value that contains the specified legal 346 /// parts combined into the value they represent. If the parts combine to a 347 /// type larger than ValueVT then AssertOp can be used to specify whether the 348 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 349 /// ValueVT (ISD::AssertSext). 350 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 351 const SDValue *Parts, unsigned NumParts, 352 MVT PartVT, EVT ValueVT, const Value *V, 353 Optional<CallingConv::ID> CallConv) { 354 assert(ValueVT.isVector() && "Not a vector value"); 355 assert(NumParts > 0 && "No parts to assemble!"); 356 const bool IsABIRegCopy = CallConv.hasValue(); 357 358 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 359 SDValue Val = Parts[0]; 360 361 // Handle a multi-element vector. 362 if (NumParts > 1) { 363 EVT IntermediateVT; 364 MVT RegisterVT; 365 unsigned NumIntermediates; 366 unsigned NumRegs; 367 368 if (IsABIRegCopy) { 369 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 370 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 371 NumIntermediates, RegisterVT); 372 } else { 373 NumRegs = 374 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 375 NumIntermediates, RegisterVT); 376 } 377 378 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 379 NumParts = NumRegs; // Silence a compiler warning. 380 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 381 assert(RegisterVT.getSizeInBits() == 382 Parts[0].getSimpleValueType().getSizeInBits() && 383 "Part type sizes don't match!"); 384 385 // Assemble the parts into intermediate operands. 386 SmallVector<SDValue, 8> Ops(NumIntermediates); 387 if (NumIntermediates == NumParts) { 388 // If the register was not expanded, truncate or copy the value, 389 // as appropriate. 390 for (unsigned i = 0; i != NumParts; ++i) 391 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 392 PartVT, IntermediateVT, V, CallConv); 393 } else if (NumParts > 0) { 394 // If the intermediate type was expanded, build the intermediate 395 // operands from the parts. 396 assert(NumParts % NumIntermediates == 0 && 397 "Must expand into a divisible number of parts!"); 398 unsigned Factor = NumParts / NumIntermediates; 399 for (unsigned i = 0; i != NumIntermediates; ++i) 400 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 401 PartVT, IntermediateVT, V, CallConv); 402 } 403 404 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 405 // intermediate operands. 406 EVT BuiltVectorTy = 407 IntermediateVT.isVector() 408 ? EVT::getVectorVT( 409 *DAG.getContext(), IntermediateVT.getScalarType(), 410 IntermediateVT.getVectorElementCount() * NumParts) 411 : EVT::getVectorVT(*DAG.getContext(), 412 IntermediateVT.getScalarType(), 413 NumIntermediates); 414 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 415 : ISD::BUILD_VECTOR, 416 DL, BuiltVectorTy, Ops); 417 } 418 419 // There is now one part, held in Val. Correct it to match ValueVT. 420 EVT PartEVT = Val.getValueType(); 421 422 if (PartEVT == ValueVT) 423 return Val; 424 425 if (PartEVT.isVector()) { 426 // If the element type of the source/dest vectors are the same, but the 427 // parts vector has more elements than the value vector, then we have a 428 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 429 // elements we want. 430 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 431 assert((PartEVT.getVectorElementCount().Min > 432 ValueVT.getVectorElementCount().Min) && 433 (PartEVT.getVectorElementCount().Scalable == 434 ValueVT.getVectorElementCount().Scalable) && 435 "Cannot narrow, it would be a lossy transformation"); 436 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 437 DAG.getVectorIdxConstant(0, DL)); 438 } 439 440 // Vector/Vector bitcast. 441 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 442 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 443 444 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 445 "Cannot handle this kind of promotion"); 446 // Promoted vector extract 447 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 448 449 } 450 451 // Trivial bitcast if the types are the same size and the destination 452 // vector type is legal. 453 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 454 TLI.isTypeLegal(ValueVT)) 455 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 456 457 if (ValueVT.getVectorNumElements() != 1) { 458 // Certain ABIs require that vectors are passed as integers. For vectors 459 // are the same size, this is an obvious bitcast. 460 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 461 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 462 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 463 // Bitcast Val back the original type and extract the corresponding 464 // vector we want. 465 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 466 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 467 ValueVT.getVectorElementType(), Elts); 468 Val = DAG.getBitcast(WiderVecType, Val); 469 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 470 DAG.getVectorIdxConstant(0, DL)); 471 } 472 473 diagnosePossiblyInvalidConstraint( 474 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 475 return DAG.getUNDEF(ValueVT); 476 } 477 478 // Handle cases such as i8 -> <1 x i1> 479 EVT ValueSVT = ValueVT.getVectorElementType(); 480 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 481 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 482 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 483 else 484 Val = ValueVT.isFloatingPoint() 485 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 486 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 487 } 488 489 return DAG.getBuildVector(ValueVT, DL, Val); 490 } 491 492 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 493 SDValue Val, SDValue *Parts, unsigned NumParts, 494 MVT PartVT, const Value *V, 495 Optional<CallingConv::ID> CallConv); 496 497 /// getCopyToParts - Create a series of nodes that contain the specified value 498 /// split into legal parts. If the parts contain more bits than Val, then, for 499 /// integers, ExtendKind can be used to specify how to generate the extra bits. 500 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 501 SDValue *Parts, unsigned NumParts, MVT PartVT, 502 const Value *V, 503 Optional<CallingConv::ID> CallConv = None, 504 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 505 // Let the target split the parts if it wants to 506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 507 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 508 CallConv)) 509 return; 510 EVT ValueVT = Val.getValueType(); 511 512 // Handle the vector case separately. 513 if (ValueVT.isVector()) 514 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 515 CallConv); 516 517 unsigned PartBits = PartVT.getSizeInBits(); 518 unsigned OrigNumParts = NumParts; 519 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 520 "Copying to an illegal type!"); 521 522 if (NumParts == 0) 523 return; 524 525 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 526 EVT PartEVT = PartVT; 527 if (PartEVT == ValueVT) { 528 assert(NumParts == 1 && "No-op copy with multiple parts!"); 529 Parts[0] = Val; 530 return; 531 } 532 533 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 534 // If the parts cover more bits than the value has, promote the value. 535 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 536 assert(NumParts == 1 && "Do not know what to promote to!"); 537 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 538 } else { 539 if (ValueVT.isFloatingPoint()) { 540 // FP values need to be bitcast, then extended if they are being put 541 // into a larger container. 542 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 543 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 544 } 545 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 546 ValueVT.isInteger() && 547 "Unknown mismatch!"); 548 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 549 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 550 if (PartVT == MVT::x86mmx) 551 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 552 } 553 } else if (PartBits == ValueVT.getSizeInBits()) { 554 // Different types of the same size. 555 assert(NumParts == 1 && PartEVT != ValueVT); 556 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 557 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 558 // If the parts cover less bits than value has, truncate the value. 559 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 560 ValueVT.isInteger() && 561 "Unknown mismatch!"); 562 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 563 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 564 if (PartVT == MVT::x86mmx) 565 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 566 } 567 568 // The value may have changed - recompute ValueVT. 569 ValueVT = Val.getValueType(); 570 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 571 "Failed to tile the value with PartVT!"); 572 573 if (NumParts == 1) { 574 if (PartEVT != ValueVT) { 575 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 576 "scalar-to-vector conversion failed"); 577 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 578 } 579 580 Parts[0] = Val; 581 return; 582 } 583 584 // Expand the value into multiple parts. 585 if (NumParts & (NumParts - 1)) { 586 // The number of parts is not a power of 2. Split off and copy the tail. 587 assert(PartVT.isInteger() && ValueVT.isInteger() && 588 "Do not know what to expand to!"); 589 unsigned RoundParts = 1 << Log2_32(NumParts); 590 unsigned RoundBits = RoundParts * PartBits; 591 unsigned OddParts = NumParts - RoundParts; 592 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 593 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 594 595 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 596 CallConv); 597 598 if (DAG.getDataLayout().isBigEndian()) 599 // The odd parts were reversed by getCopyToParts - unreverse them. 600 std::reverse(Parts + RoundParts, Parts + NumParts); 601 602 NumParts = RoundParts; 603 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 604 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 605 } 606 607 // The number of parts is a power of 2. Repeatedly bisect the value using 608 // EXTRACT_ELEMENT. 609 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 610 EVT::getIntegerVT(*DAG.getContext(), 611 ValueVT.getSizeInBits()), 612 Val); 613 614 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 615 for (unsigned i = 0; i < NumParts; i += StepSize) { 616 unsigned ThisBits = StepSize * PartBits / 2; 617 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 618 SDValue &Part0 = Parts[i]; 619 SDValue &Part1 = Parts[i+StepSize/2]; 620 621 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 622 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 623 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 624 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 625 626 if (ThisBits == PartBits && ThisVT != PartVT) { 627 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 628 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 629 } 630 } 631 } 632 633 if (DAG.getDataLayout().isBigEndian()) 634 std::reverse(Parts, Parts + OrigNumParts); 635 } 636 637 static SDValue widenVectorToPartType(SelectionDAG &DAG, 638 SDValue Val, const SDLoc &DL, EVT PartVT) { 639 if (!PartVT.isFixedLengthVector()) 640 return SDValue(); 641 642 EVT ValueVT = Val.getValueType(); 643 unsigned PartNumElts = PartVT.getVectorNumElements(); 644 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 645 if (PartNumElts > ValueNumElts && 646 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 647 EVT ElementVT = PartVT.getVectorElementType(); 648 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 649 // undef elements. 650 SmallVector<SDValue, 16> Ops; 651 DAG.ExtractVectorElements(Val, Ops); 652 SDValue EltUndef = DAG.getUNDEF(ElementVT); 653 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 654 Ops.push_back(EltUndef); 655 656 // FIXME: Use CONCAT for 2x -> 4x. 657 return DAG.getBuildVector(PartVT, DL, Ops); 658 } 659 660 return SDValue(); 661 } 662 663 /// getCopyToPartsVector - Create a series of nodes that contain the specified 664 /// value split into legal parts. 665 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 666 SDValue Val, SDValue *Parts, unsigned NumParts, 667 MVT PartVT, const Value *V, 668 Optional<CallingConv::ID> CallConv) { 669 EVT ValueVT = Val.getValueType(); 670 assert(ValueVT.isVector() && "Not a vector"); 671 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 672 const bool IsABIRegCopy = CallConv.hasValue(); 673 674 if (NumParts == 1) { 675 EVT PartEVT = PartVT; 676 if (PartEVT == ValueVT) { 677 // Nothing to do. 678 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 679 // Bitconvert vector->vector case. 680 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 681 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 682 Val = Widened; 683 } else if (PartVT.isVector() && 684 PartEVT.getVectorElementType().bitsGE( 685 ValueVT.getVectorElementType()) && 686 PartEVT.getVectorElementCount() == 687 ValueVT.getVectorElementCount()) { 688 689 // Promoted vector extract 690 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 691 } else { 692 if (ValueVT.getVectorNumElements() == 1) { 693 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 694 DAG.getVectorIdxConstant(0, DL)); 695 } else { 696 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 697 "lossy conversion of vector to scalar type"); 698 EVT IntermediateType = 699 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 700 Val = DAG.getBitcast(IntermediateType, Val); 701 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 702 } 703 } 704 705 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 706 Parts[0] = Val; 707 return; 708 } 709 710 // Handle a multi-element vector. 711 EVT IntermediateVT; 712 MVT RegisterVT; 713 unsigned NumIntermediates; 714 unsigned NumRegs; 715 if (IsABIRegCopy) { 716 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 717 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 718 NumIntermediates, RegisterVT); 719 } else { 720 NumRegs = 721 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 722 NumIntermediates, RegisterVT); 723 } 724 725 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 726 NumParts = NumRegs; // Silence a compiler warning. 727 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 728 729 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 730 "Mixing scalable and fixed vectors when copying in parts"); 731 732 Optional<ElementCount> DestEltCnt; 733 734 if (IntermediateVT.isVector()) 735 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 736 else 737 DestEltCnt = ElementCount::getFixed(NumIntermediates); 738 739 EVT BuiltVectorTy = EVT::getVectorVT( 740 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 741 if (ValueVT != BuiltVectorTy) { 742 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 743 Val = Widened; 744 745 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 746 } 747 748 // Split the vector into intermediate operands. 749 SmallVector<SDValue, 8> Ops(NumIntermediates); 750 for (unsigned i = 0; i != NumIntermediates; ++i) { 751 if (IntermediateVT.isVector()) { 752 // This does something sensible for scalable vectors - see the 753 // definition of EXTRACT_SUBVECTOR for further details. 754 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 755 Ops[i] = 756 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 757 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 758 } else { 759 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 760 DAG.getVectorIdxConstant(i, DL)); 761 } 762 } 763 764 // Split the intermediate operands into legal parts. 765 if (NumParts == NumIntermediates) { 766 // If the register was not expanded, promote or copy the value, 767 // as appropriate. 768 for (unsigned i = 0; i != NumParts; ++i) 769 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 770 } else if (NumParts > 0) { 771 // If the intermediate type was expanded, split each the value into 772 // legal parts. 773 assert(NumIntermediates != 0 && "division by zero"); 774 assert(NumParts % NumIntermediates == 0 && 775 "Must expand into a divisible number of parts!"); 776 unsigned Factor = NumParts / NumIntermediates; 777 for (unsigned i = 0; i != NumIntermediates; ++i) 778 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 779 CallConv); 780 } 781 } 782 783 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 784 EVT valuevt, Optional<CallingConv::ID> CC) 785 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 786 RegCount(1, regs.size()), CallConv(CC) {} 787 788 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 789 const DataLayout &DL, unsigned Reg, Type *Ty, 790 Optional<CallingConv::ID> CC) { 791 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 792 793 CallConv = CC; 794 795 for (EVT ValueVT : ValueVTs) { 796 unsigned NumRegs = 797 isABIMangled() 798 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 799 : TLI.getNumRegisters(Context, ValueVT); 800 MVT RegisterVT = 801 isABIMangled() 802 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 803 : TLI.getRegisterType(Context, ValueVT); 804 for (unsigned i = 0; i != NumRegs; ++i) 805 Regs.push_back(Reg + i); 806 RegVTs.push_back(RegisterVT); 807 RegCount.push_back(NumRegs); 808 Reg += NumRegs; 809 } 810 } 811 812 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 813 FunctionLoweringInfo &FuncInfo, 814 const SDLoc &dl, SDValue &Chain, 815 SDValue *Flag, const Value *V) const { 816 // A Value with type {} or [0 x %t] needs no registers. 817 if (ValueVTs.empty()) 818 return SDValue(); 819 820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 821 822 // Assemble the legal parts into the final values. 823 SmallVector<SDValue, 4> Values(ValueVTs.size()); 824 SmallVector<SDValue, 8> Parts; 825 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 826 // Copy the legal parts from the registers. 827 EVT ValueVT = ValueVTs[Value]; 828 unsigned NumRegs = RegCount[Value]; 829 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 830 *DAG.getContext(), 831 CallConv.getValue(), RegVTs[Value]) 832 : RegVTs[Value]; 833 834 Parts.resize(NumRegs); 835 for (unsigned i = 0; i != NumRegs; ++i) { 836 SDValue P; 837 if (!Flag) { 838 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 839 } else { 840 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 841 *Flag = P.getValue(2); 842 } 843 844 Chain = P.getValue(1); 845 Parts[i] = P; 846 847 // If the source register was virtual and if we know something about it, 848 // add an assert node. 849 if (!Register::isVirtualRegister(Regs[Part + i]) || 850 !RegisterVT.isInteger()) 851 continue; 852 853 const FunctionLoweringInfo::LiveOutInfo *LOI = 854 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 855 if (!LOI) 856 continue; 857 858 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 859 unsigned NumSignBits = LOI->NumSignBits; 860 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 861 862 if (NumZeroBits == RegSize) { 863 // The current value is a zero. 864 // Explicitly express that as it would be easier for 865 // optimizations to kick in. 866 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 867 continue; 868 } 869 870 // FIXME: We capture more information than the dag can represent. For 871 // now, just use the tightest assertzext/assertsext possible. 872 bool isSExt; 873 EVT FromVT(MVT::Other); 874 if (NumZeroBits) { 875 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 876 isSExt = false; 877 } else if (NumSignBits > 1) { 878 FromVT = 879 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 880 isSExt = true; 881 } else { 882 continue; 883 } 884 // Add an assertion node. 885 assert(FromVT != MVT::Other); 886 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 887 RegisterVT, P, DAG.getValueType(FromVT)); 888 } 889 890 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 891 RegisterVT, ValueVT, V, CallConv); 892 Part += NumRegs; 893 Parts.clear(); 894 } 895 896 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 897 } 898 899 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 900 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 901 const Value *V, 902 ISD::NodeType PreferredExtendType) const { 903 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 904 ISD::NodeType ExtendKind = PreferredExtendType; 905 906 // Get the list of the values's legal parts. 907 unsigned NumRegs = Regs.size(); 908 SmallVector<SDValue, 8> Parts(NumRegs); 909 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 910 unsigned NumParts = RegCount[Value]; 911 912 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 913 *DAG.getContext(), 914 CallConv.getValue(), RegVTs[Value]) 915 : RegVTs[Value]; 916 917 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 918 ExtendKind = ISD::ZERO_EXTEND; 919 920 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 921 NumParts, RegisterVT, V, CallConv, ExtendKind); 922 Part += NumParts; 923 } 924 925 // Copy the parts into the registers. 926 SmallVector<SDValue, 8> Chains(NumRegs); 927 for (unsigned i = 0; i != NumRegs; ++i) { 928 SDValue Part; 929 if (!Flag) { 930 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 931 } else { 932 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 933 *Flag = Part.getValue(1); 934 } 935 936 Chains[i] = Part.getValue(0); 937 } 938 939 if (NumRegs == 1 || Flag) 940 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 941 // flagged to it. That is the CopyToReg nodes and the user are considered 942 // a single scheduling unit. If we create a TokenFactor and return it as 943 // chain, then the TokenFactor is both a predecessor (operand) of the 944 // user as well as a successor (the TF operands are flagged to the user). 945 // c1, f1 = CopyToReg 946 // c2, f2 = CopyToReg 947 // c3 = TokenFactor c1, c2 948 // ... 949 // = op c3, ..., f2 950 Chain = Chains[NumRegs-1]; 951 else 952 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 953 } 954 955 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 956 unsigned MatchingIdx, const SDLoc &dl, 957 SelectionDAG &DAG, 958 std::vector<SDValue> &Ops) const { 959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 960 961 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 962 if (HasMatching) 963 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 964 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 965 // Put the register class of the virtual registers in the flag word. That 966 // way, later passes can recompute register class constraints for inline 967 // assembly as well as normal instructions. 968 // Don't do this for tied operands that can use the regclass information 969 // from the def. 970 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 971 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 972 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 973 } 974 975 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 976 Ops.push_back(Res); 977 978 if (Code == InlineAsm::Kind_Clobber) { 979 // Clobbers should always have a 1:1 mapping with registers, and may 980 // reference registers that have illegal (e.g. vector) types. Hence, we 981 // shouldn't try to apply any sort of splitting logic to them. 982 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 983 "No 1:1 mapping from clobbers to regs?"); 984 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 985 (void)SP; 986 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 987 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 988 assert( 989 (Regs[I] != SP || 990 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 991 "If we clobbered the stack pointer, MFI should know about it."); 992 } 993 return; 994 } 995 996 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 997 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 998 MVT RegisterVT = RegVTs[Value]; 999 for (unsigned i = 0; i != NumRegs; ++i) { 1000 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1001 unsigned TheReg = Regs[Reg++]; 1002 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1003 } 1004 } 1005 } 1006 1007 SmallVector<std::pair<unsigned, unsigned>, 4> 1008 RegsForValue::getRegsAndSizes() const { 1009 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1010 unsigned I = 0; 1011 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1012 unsigned RegCount = std::get<0>(CountAndVT); 1013 MVT RegisterVT = std::get<1>(CountAndVT); 1014 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1015 for (unsigned E = I + RegCount; I != E; ++I) 1016 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1017 } 1018 return OutVec; 1019 } 1020 1021 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1022 const TargetLibraryInfo *li) { 1023 AA = aa; 1024 GFI = gfi; 1025 LibInfo = li; 1026 DL = &DAG.getDataLayout(); 1027 Context = DAG.getContext(); 1028 LPadToCallSiteMap.clear(); 1029 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1030 } 1031 1032 void SelectionDAGBuilder::clear() { 1033 NodeMap.clear(); 1034 UnusedArgNodeMap.clear(); 1035 PendingLoads.clear(); 1036 PendingExports.clear(); 1037 PendingConstrainedFP.clear(); 1038 PendingConstrainedFPStrict.clear(); 1039 CurInst = nullptr; 1040 HasTailCall = false; 1041 SDNodeOrder = LowestSDNodeOrder; 1042 StatepointLowering.clear(); 1043 } 1044 1045 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1046 DanglingDebugInfoMap.clear(); 1047 } 1048 1049 // Update DAG root to include dependencies on Pending chains. 1050 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1051 SDValue Root = DAG.getRoot(); 1052 1053 if (Pending.empty()) 1054 return Root; 1055 1056 // Add current root to PendingChains, unless we already indirectly 1057 // depend on it. 1058 if (Root.getOpcode() != ISD::EntryToken) { 1059 unsigned i = 0, e = Pending.size(); 1060 for (; i != e; ++i) { 1061 assert(Pending[i].getNode()->getNumOperands() > 1); 1062 if (Pending[i].getNode()->getOperand(0) == Root) 1063 break; // Don't add the root if we already indirectly depend on it. 1064 } 1065 1066 if (i == e) 1067 Pending.push_back(Root); 1068 } 1069 1070 if (Pending.size() == 1) 1071 Root = Pending[0]; 1072 else 1073 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1074 1075 DAG.setRoot(Root); 1076 Pending.clear(); 1077 return Root; 1078 } 1079 1080 SDValue SelectionDAGBuilder::getMemoryRoot() { 1081 return updateRoot(PendingLoads); 1082 } 1083 1084 SDValue SelectionDAGBuilder::getRoot() { 1085 // Chain up all pending constrained intrinsics together with all 1086 // pending loads, by simply appending them to PendingLoads and 1087 // then calling getMemoryRoot(). 1088 PendingLoads.reserve(PendingLoads.size() + 1089 PendingConstrainedFP.size() + 1090 PendingConstrainedFPStrict.size()); 1091 PendingLoads.append(PendingConstrainedFP.begin(), 1092 PendingConstrainedFP.end()); 1093 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1094 PendingConstrainedFPStrict.end()); 1095 PendingConstrainedFP.clear(); 1096 PendingConstrainedFPStrict.clear(); 1097 return getMemoryRoot(); 1098 } 1099 1100 SDValue SelectionDAGBuilder::getControlRoot() { 1101 // We need to emit pending fpexcept.strict constrained intrinsics, 1102 // so append them to the PendingExports list. 1103 PendingExports.append(PendingConstrainedFPStrict.begin(), 1104 PendingConstrainedFPStrict.end()); 1105 PendingConstrainedFPStrict.clear(); 1106 return updateRoot(PendingExports); 1107 } 1108 1109 void SelectionDAGBuilder::visit(const Instruction &I) { 1110 // Set up outgoing PHI node register values before emitting the terminator. 1111 if (I.isTerminator()) { 1112 HandlePHINodesInSuccessorBlocks(I.getParent()); 1113 } 1114 1115 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1116 if (!isa<DbgInfoIntrinsic>(I)) 1117 ++SDNodeOrder; 1118 1119 CurInst = &I; 1120 1121 visit(I.getOpcode(), I); 1122 1123 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1124 // ConstrainedFPIntrinsics handle their own FMF. 1125 if (!isa<ConstrainedFPIntrinsic>(&I)) { 1126 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1127 // maps to this instruction. 1128 // TODO: We could handle all flags (nsw, etc) here. 1129 // TODO: If an IR instruction maps to >1 node, only the final node will have 1130 // flags set. 1131 if (SDNode *Node = getNodeForIRValue(&I)) { 1132 SDNodeFlags IncomingFlags; 1133 IncomingFlags.copyFMF(*FPMO); 1134 if (!Node->getFlags().isDefined()) 1135 Node->setFlags(IncomingFlags); 1136 else 1137 Node->intersectFlagsWith(IncomingFlags); 1138 } 1139 } 1140 } 1141 1142 if (!I.isTerminator() && !HasTailCall && 1143 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1144 CopyToExportRegsIfNeeded(&I); 1145 1146 CurInst = nullptr; 1147 } 1148 1149 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1150 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1151 } 1152 1153 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1154 // Note: this doesn't use InstVisitor, because it has to work with 1155 // ConstantExpr's in addition to instructions. 1156 switch (Opcode) { 1157 default: llvm_unreachable("Unknown instruction type encountered!"); 1158 // Build the switch statement using the Instruction.def file. 1159 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1160 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1161 #include "llvm/IR/Instruction.def" 1162 } 1163 } 1164 1165 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1166 const DIExpression *Expr) { 1167 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1168 const DbgValueInst *DI = DDI.getDI(); 1169 DIVariable *DanglingVariable = DI->getVariable(); 1170 DIExpression *DanglingExpr = DI->getExpression(); 1171 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1172 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1173 return true; 1174 } 1175 return false; 1176 }; 1177 1178 for (auto &DDIMI : DanglingDebugInfoMap) { 1179 DanglingDebugInfoVector &DDIV = DDIMI.second; 1180 1181 // If debug info is to be dropped, run it through final checks to see 1182 // whether it can be salvaged. 1183 for (auto &DDI : DDIV) 1184 if (isMatchingDbgValue(DDI)) 1185 salvageUnresolvedDbgValue(DDI); 1186 1187 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1188 } 1189 } 1190 1191 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1192 // generate the debug data structures now that we've seen its definition. 1193 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1194 SDValue Val) { 1195 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1196 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1197 return; 1198 1199 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1200 for (auto &DDI : DDIV) { 1201 const DbgValueInst *DI = DDI.getDI(); 1202 assert(DI && "Ill-formed DanglingDebugInfo"); 1203 DebugLoc dl = DDI.getdl(); 1204 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1205 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1206 DILocalVariable *Variable = DI->getVariable(); 1207 DIExpression *Expr = DI->getExpression(); 1208 assert(Variable->isValidLocationForIntrinsic(dl) && 1209 "Expected inlined-at fields to agree"); 1210 SDDbgValue *SDV; 1211 if (Val.getNode()) { 1212 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1213 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1214 // we couldn't resolve it directly when examining the DbgValue intrinsic 1215 // in the first place we should not be more successful here). Unless we 1216 // have some test case that prove this to be correct we should avoid 1217 // calling EmitFuncArgumentDbgValue here. 1218 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1219 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1220 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1221 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1222 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1223 // inserted after the definition of Val when emitting the instructions 1224 // after ISel. An alternative could be to teach 1225 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1226 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1227 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1228 << ValSDNodeOrder << "\n"); 1229 SDV = getDbgValue(Val, Variable, Expr, dl, 1230 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1231 DAG.AddDbgValue(SDV, Val.getNode(), false); 1232 } else 1233 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1234 << "in EmitFuncArgumentDbgValue\n"); 1235 } else { 1236 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1237 auto Undef = 1238 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1239 auto SDV = 1240 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1241 DAG.AddDbgValue(SDV, nullptr, false); 1242 } 1243 } 1244 DDIV.clear(); 1245 } 1246 1247 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1248 Value *V = DDI.getDI()->getValue(); 1249 DILocalVariable *Var = DDI.getDI()->getVariable(); 1250 DIExpression *Expr = DDI.getDI()->getExpression(); 1251 DebugLoc DL = DDI.getdl(); 1252 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1253 unsigned SDOrder = DDI.getSDNodeOrder(); 1254 1255 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1256 // that DW_OP_stack_value is desired. 1257 assert(isa<DbgValueInst>(DDI.getDI())); 1258 bool StackValue = true; 1259 1260 // Can this Value can be encoded without any further work? 1261 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1262 return; 1263 1264 // Attempt to salvage back through as many instructions as possible. Bail if 1265 // a non-instruction is seen, such as a constant expression or global 1266 // variable. FIXME: Further work could recover those too. 1267 while (isa<Instruction>(V)) { 1268 Instruction &VAsInst = *cast<Instruction>(V); 1269 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1270 1271 // If we cannot salvage any further, and haven't yet found a suitable debug 1272 // expression, bail out. 1273 if (!NewExpr) 1274 break; 1275 1276 // New value and expr now represent this debuginfo. 1277 V = VAsInst.getOperand(0); 1278 Expr = NewExpr; 1279 1280 // Some kind of simplification occurred: check whether the operand of the 1281 // salvaged debug expression can be encoded in this DAG. 1282 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1283 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1284 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1285 return; 1286 } 1287 } 1288 1289 // This was the final opportunity to salvage this debug information, and it 1290 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1291 // any earlier variable location. 1292 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1293 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1294 DAG.AddDbgValue(SDV, nullptr, false); 1295 1296 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1297 << "\n"); 1298 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1299 << "\n"); 1300 } 1301 1302 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1303 DIExpression *Expr, DebugLoc dl, 1304 DebugLoc InstDL, unsigned Order) { 1305 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1306 SDDbgValue *SDV; 1307 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1308 isa<ConstantPointerNull>(V)) { 1309 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1310 DAG.AddDbgValue(SDV, nullptr, false); 1311 return true; 1312 } 1313 1314 // If the Value is a frame index, we can create a FrameIndex debug value 1315 // without relying on the DAG at all. 1316 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1317 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1318 if (SI != FuncInfo.StaticAllocaMap.end()) { 1319 auto SDV = 1320 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1321 /*IsIndirect*/ false, dl, SDNodeOrder); 1322 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1323 // is still available even if the SDNode gets optimized out. 1324 DAG.AddDbgValue(SDV, nullptr, false); 1325 return true; 1326 } 1327 } 1328 1329 // Do not use getValue() in here; we don't want to generate code at 1330 // this point if it hasn't been done yet. 1331 SDValue N = NodeMap[V]; 1332 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1333 N = UnusedArgNodeMap[V]; 1334 if (N.getNode()) { 1335 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1336 return true; 1337 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1338 DAG.AddDbgValue(SDV, N.getNode(), false); 1339 return true; 1340 } 1341 1342 // Special rules apply for the first dbg.values of parameter variables in a 1343 // function. Identify them by the fact they reference Argument Values, that 1344 // they're parameters, and they are parameters of the current function. We 1345 // need to let them dangle until they get an SDNode. 1346 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1347 !InstDL.getInlinedAt(); 1348 if (!IsParamOfFunc) { 1349 // The value is not used in this block yet (or it would have an SDNode). 1350 // We still want the value to appear for the user if possible -- if it has 1351 // an associated VReg, we can refer to that instead. 1352 auto VMI = FuncInfo.ValueMap.find(V); 1353 if (VMI != FuncInfo.ValueMap.end()) { 1354 unsigned Reg = VMI->second; 1355 // If this is a PHI node, it may be split up into several MI PHI nodes 1356 // (in FunctionLoweringInfo::set). 1357 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1358 V->getType(), None); 1359 if (RFV.occupiesMultipleRegs()) { 1360 unsigned Offset = 0; 1361 unsigned BitsToDescribe = 0; 1362 if (auto VarSize = Var->getSizeInBits()) 1363 BitsToDescribe = *VarSize; 1364 if (auto Fragment = Expr->getFragmentInfo()) 1365 BitsToDescribe = Fragment->SizeInBits; 1366 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1367 unsigned RegisterSize = RegAndSize.second; 1368 // Bail out if all bits are described already. 1369 if (Offset >= BitsToDescribe) 1370 break; 1371 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1372 ? BitsToDescribe - Offset 1373 : RegisterSize; 1374 auto FragmentExpr = DIExpression::createFragmentExpression( 1375 Expr, Offset, FragmentSize); 1376 if (!FragmentExpr) 1377 continue; 1378 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1379 false, dl, SDNodeOrder); 1380 DAG.AddDbgValue(SDV, nullptr, false); 1381 Offset += RegisterSize; 1382 } 1383 } else { 1384 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1385 DAG.AddDbgValue(SDV, nullptr, false); 1386 } 1387 return true; 1388 } 1389 } 1390 1391 return false; 1392 } 1393 1394 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1395 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1396 for (auto &Pair : DanglingDebugInfoMap) 1397 for (auto &DDI : Pair.second) 1398 salvageUnresolvedDbgValue(DDI); 1399 clearDanglingDebugInfo(); 1400 } 1401 1402 /// getCopyFromRegs - If there was virtual register allocated for the value V 1403 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1404 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1405 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1406 SDValue Result; 1407 1408 if (It != FuncInfo.ValueMap.end()) { 1409 Register InReg = It->second; 1410 1411 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1412 DAG.getDataLayout(), InReg, Ty, 1413 None); // This is not an ABI copy. 1414 SDValue Chain = DAG.getEntryNode(); 1415 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1416 V); 1417 resolveDanglingDebugInfo(V, Result); 1418 } 1419 1420 return Result; 1421 } 1422 1423 /// getValue - Return an SDValue for the given Value. 1424 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1425 // If we already have an SDValue for this value, use it. It's important 1426 // to do this first, so that we don't create a CopyFromReg if we already 1427 // have a regular SDValue. 1428 SDValue &N = NodeMap[V]; 1429 if (N.getNode()) return N; 1430 1431 // If there's a virtual register allocated and initialized for this 1432 // value, use it. 1433 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1434 return copyFromReg; 1435 1436 // Otherwise create a new SDValue and remember it. 1437 SDValue Val = getValueImpl(V); 1438 NodeMap[V] = Val; 1439 resolveDanglingDebugInfo(V, Val); 1440 return Val; 1441 } 1442 1443 /// getNonRegisterValue - Return an SDValue for the given Value, but 1444 /// don't look in FuncInfo.ValueMap for a virtual register. 1445 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1446 // If we already have an SDValue for this value, use it. 1447 SDValue &N = NodeMap[V]; 1448 if (N.getNode()) { 1449 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1450 // Remove the debug location from the node as the node is about to be used 1451 // in a location which may differ from the original debug location. This 1452 // is relevant to Constant and ConstantFP nodes because they can appear 1453 // as constant expressions inside PHI nodes. 1454 N->setDebugLoc(DebugLoc()); 1455 } 1456 return N; 1457 } 1458 1459 // Otherwise create a new SDValue and remember it. 1460 SDValue Val = getValueImpl(V); 1461 NodeMap[V] = Val; 1462 resolveDanglingDebugInfo(V, Val); 1463 return Val; 1464 } 1465 1466 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1467 /// Create an SDValue for the given value. 1468 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1469 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1470 1471 if (const Constant *C = dyn_cast<Constant>(V)) { 1472 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1473 1474 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1475 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1476 1477 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1478 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1479 1480 if (isa<ConstantPointerNull>(C)) { 1481 unsigned AS = V->getType()->getPointerAddressSpace(); 1482 return DAG.getConstant(0, getCurSDLoc(), 1483 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1484 } 1485 1486 if (match(C, m_VScale(DAG.getDataLayout()))) 1487 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1488 1489 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1490 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1491 1492 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1493 return DAG.getUNDEF(VT); 1494 1495 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1496 visit(CE->getOpcode(), *CE); 1497 SDValue N1 = NodeMap[V]; 1498 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1499 return N1; 1500 } 1501 1502 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1503 SmallVector<SDValue, 4> Constants; 1504 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1505 OI != OE; ++OI) { 1506 SDNode *Val = getValue(*OI).getNode(); 1507 // If the operand is an empty aggregate, there are no values. 1508 if (!Val) continue; 1509 // Add each leaf value from the operand to the Constants list 1510 // to form a flattened list of all the values. 1511 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1512 Constants.push_back(SDValue(Val, i)); 1513 } 1514 1515 return DAG.getMergeValues(Constants, getCurSDLoc()); 1516 } 1517 1518 if (const ConstantDataSequential *CDS = 1519 dyn_cast<ConstantDataSequential>(C)) { 1520 SmallVector<SDValue, 4> Ops; 1521 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1522 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1523 // Add each leaf value from the operand to the Constants list 1524 // to form a flattened list of all the values. 1525 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1526 Ops.push_back(SDValue(Val, i)); 1527 } 1528 1529 if (isa<ArrayType>(CDS->getType())) 1530 return DAG.getMergeValues(Ops, getCurSDLoc()); 1531 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1532 } 1533 1534 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1535 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1536 "Unknown struct or array constant!"); 1537 1538 SmallVector<EVT, 4> ValueVTs; 1539 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1540 unsigned NumElts = ValueVTs.size(); 1541 if (NumElts == 0) 1542 return SDValue(); // empty struct 1543 SmallVector<SDValue, 4> Constants(NumElts); 1544 for (unsigned i = 0; i != NumElts; ++i) { 1545 EVT EltVT = ValueVTs[i]; 1546 if (isa<UndefValue>(C)) 1547 Constants[i] = DAG.getUNDEF(EltVT); 1548 else if (EltVT.isFloatingPoint()) 1549 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1550 else 1551 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1552 } 1553 1554 return DAG.getMergeValues(Constants, getCurSDLoc()); 1555 } 1556 1557 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1558 return DAG.getBlockAddress(BA, VT); 1559 1560 VectorType *VecTy = cast<VectorType>(V->getType()); 1561 1562 // Now that we know the number and type of the elements, get that number of 1563 // elements into the Ops array based on what kind of constant it is. 1564 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1565 SmallVector<SDValue, 16> Ops; 1566 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1567 for (unsigned i = 0; i != NumElements; ++i) 1568 Ops.push_back(getValue(CV->getOperand(i))); 1569 1570 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1571 } else if (isa<ConstantAggregateZero>(C)) { 1572 EVT EltVT = 1573 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1574 1575 SDValue Op; 1576 if (EltVT.isFloatingPoint()) 1577 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1578 else 1579 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1580 1581 if (isa<ScalableVectorType>(VecTy)) 1582 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1583 else { 1584 SmallVector<SDValue, 16> Ops; 1585 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1586 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1587 } 1588 } 1589 llvm_unreachable("Unknown vector constant"); 1590 } 1591 1592 // If this is a static alloca, generate it as the frameindex instead of 1593 // computation. 1594 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1595 DenseMap<const AllocaInst*, int>::iterator SI = 1596 FuncInfo.StaticAllocaMap.find(AI); 1597 if (SI != FuncInfo.StaticAllocaMap.end()) 1598 return DAG.getFrameIndex(SI->second, 1599 TLI.getFrameIndexTy(DAG.getDataLayout())); 1600 } 1601 1602 // If this is an instruction which fast-isel has deferred, select it now. 1603 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1604 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1605 1606 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1607 Inst->getType(), getABIRegCopyCC(V)); 1608 SDValue Chain = DAG.getEntryNode(); 1609 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1610 } 1611 1612 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1613 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1614 } 1615 llvm_unreachable("Can't get register for value!"); 1616 } 1617 1618 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1619 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1620 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1621 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1622 bool IsSEH = isAsynchronousEHPersonality(Pers); 1623 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1624 if (!IsSEH) 1625 CatchPadMBB->setIsEHScopeEntry(); 1626 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1627 if (IsMSVCCXX || IsCoreCLR) 1628 CatchPadMBB->setIsEHFuncletEntry(); 1629 } 1630 1631 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1632 // Update machine-CFG edge. 1633 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1634 FuncInfo.MBB->addSuccessor(TargetMBB); 1635 1636 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1637 bool IsSEH = isAsynchronousEHPersonality(Pers); 1638 if (IsSEH) { 1639 // If this is not a fall-through branch or optimizations are switched off, 1640 // emit the branch. 1641 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1642 TM.getOptLevel() == CodeGenOpt::None) 1643 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1644 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1645 return; 1646 } 1647 1648 // Figure out the funclet membership for the catchret's successor. 1649 // This will be used by the FuncletLayout pass to determine how to order the 1650 // BB's. 1651 // A 'catchret' returns to the outer scope's color. 1652 Value *ParentPad = I.getCatchSwitchParentPad(); 1653 const BasicBlock *SuccessorColor; 1654 if (isa<ConstantTokenNone>(ParentPad)) 1655 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1656 else 1657 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1658 assert(SuccessorColor && "No parent funclet for catchret!"); 1659 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1660 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1661 1662 // Create the terminator node. 1663 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1664 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1665 DAG.getBasicBlock(SuccessorColorMBB)); 1666 DAG.setRoot(Ret); 1667 } 1668 1669 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1670 // Don't emit any special code for the cleanuppad instruction. It just marks 1671 // the start of an EH scope/funclet. 1672 FuncInfo.MBB->setIsEHScopeEntry(); 1673 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1674 if (Pers != EHPersonality::Wasm_CXX) { 1675 FuncInfo.MBB->setIsEHFuncletEntry(); 1676 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1677 } 1678 } 1679 1680 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1681 // the control flow always stops at the single catch pad, as it does for a 1682 // cleanup pad. In case the exception caught is not of the types the catch pad 1683 // catches, it will be rethrown by a rethrow. 1684 static void findWasmUnwindDestinations( 1685 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1686 BranchProbability Prob, 1687 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1688 &UnwindDests) { 1689 while (EHPadBB) { 1690 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1691 if (isa<CleanupPadInst>(Pad)) { 1692 // Stop on cleanup pads. 1693 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1694 UnwindDests.back().first->setIsEHScopeEntry(); 1695 break; 1696 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1697 // Add the catchpad handlers to the possible destinations. We don't 1698 // continue to the unwind destination of the catchswitch for wasm. 1699 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1700 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1701 UnwindDests.back().first->setIsEHScopeEntry(); 1702 } 1703 break; 1704 } else { 1705 continue; 1706 } 1707 } 1708 } 1709 1710 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1711 /// many places it could ultimately go. In the IR, we have a single unwind 1712 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1713 /// This function skips over imaginary basic blocks that hold catchswitch 1714 /// instructions, and finds all the "real" machine 1715 /// basic block destinations. As those destinations may not be successors of 1716 /// EHPadBB, here we also calculate the edge probability to those destinations. 1717 /// The passed-in Prob is the edge probability to EHPadBB. 1718 static void findUnwindDestinations( 1719 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1720 BranchProbability Prob, 1721 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1722 &UnwindDests) { 1723 EHPersonality Personality = 1724 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1725 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1726 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1727 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1728 bool IsSEH = isAsynchronousEHPersonality(Personality); 1729 1730 if (IsWasmCXX) { 1731 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1732 assert(UnwindDests.size() <= 1 && 1733 "There should be at most one unwind destination for wasm"); 1734 return; 1735 } 1736 1737 while (EHPadBB) { 1738 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1739 BasicBlock *NewEHPadBB = nullptr; 1740 if (isa<LandingPadInst>(Pad)) { 1741 // Stop on landingpads. They are not funclets. 1742 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1743 break; 1744 } else if (isa<CleanupPadInst>(Pad)) { 1745 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1746 // personalities. 1747 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1748 UnwindDests.back().first->setIsEHScopeEntry(); 1749 UnwindDests.back().first->setIsEHFuncletEntry(); 1750 break; 1751 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1752 // Add the catchpad handlers to the possible destinations. 1753 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1754 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1755 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1756 if (IsMSVCCXX || IsCoreCLR) 1757 UnwindDests.back().first->setIsEHFuncletEntry(); 1758 if (!IsSEH) 1759 UnwindDests.back().first->setIsEHScopeEntry(); 1760 } 1761 NewEHPadBB = CatchSwitch->getUnwindDest(); 1762 } else { 1763 continue; 1764 } 1765 1766 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1767 if (BPI && NewEHPadBB) 1768 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1769 EHPadBB = NewEHPadBB; 1770 } 1771 } 1772 1773 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1774 // Update successor info. 1775 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1776 auto UnwindDest = I.getUnwindDest(); 1777 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1778 BranchProbability UnwindDestProb = 1779 (BPI && UnwindDest) 1780 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1781 : BranchProbability::getZero(); 1782 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1783 for (auto &UnwindDest : UnwindDests) { 1784 UnwindDest.first->setIsEHPad(); 1785 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1786 } 1787 FuncInfo.MBB->normalizeSuccProbs(); 1788 1789 // Create the terminator node. 1790 SDValue Ret = 1791 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1792 DAG.setRoot(Ret); 1793 } 1794 1795 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1796 report_fatal_error("visitCatchSwitch not yet implemented!"); 1797 } 1798 1799 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1800 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1801 auto &DL = DAG.getDataLayout(); 1802 SDValue Chain = getControlRoot(); 1803 SmallVector<ISD::OutputArg, 8> Outs; 1804 SmallVector<SDValue, 8> OutVals; 1805 1806 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1807 // lower 1808 // 1809 // %val = call <ty> @llvm.experimental.deoptimize() 1810 // ret <ty> %val 1811 // 1812 // differently. 1813 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1814 LowerDeoptimizingReturn(); 1815 return; 1816 } 1817 1818 if (!FuncInfo.CanLowerReturn) { 1819 unsigned DemoteReg = FuncInfo.DemoteRegister; 1820 const Function *F = I.getParent()->getParent(); 1821 1822 // Emit a store of the return value through the virtual register. 1823 // Leave Outs empty so that LowerReturn won't try to load return 1824 // registers the usual way. 1825 SmallVector<EVT, 1> PtrValueVTs; 1826 ComputeValueVTs(TLI, DL, 1827 F->getReturnType()->getPointerTo( 1828 DAG.getDataLayout().getAllocaAddrSpace()), 1829 PtrValueVTs); 1830 1831 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1832 DemoteReg, PtrValueVTs[0]); 1833 SDValue RetOp = getValue(I.getOperand(0)); 1834 1835 SmallVector<EVT, 4> ValueVTs, MemVTs; 1836 SmallVector<uint64_t, 4> Offsets; 1837 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1838 &Offsets); 1839 unsigned NumValues = ValueVTs.size(); 1840 1841 SmallVector<SDValue, 4> Chains(NumValues); 1842 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1843 for (unsigned i = 0; i != NumValues; ++i) { 1844 // An aggregate return value cannot wrap around the address space, so 1845 // offsets to its parts don't wrap either. 1846 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1847 TypeSize::Fixed(Offsets[i])); 1848 1849 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1850 if (MemVTs[i] != ValueVTs[i]) 1851 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1852 Chains[i] = DAG.getStore( 1853 Chain, getCurSDLoc(), Val, 1854 // FIXME: better loc info would be nice. 1855 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1856 commonAlignment(BaseAlign, Offsets[i])); 1857 } 1858 1859 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1860 MVT::Other, Chains); 1861 } else if (I.getNumOperands() != 0) { 1862 SmallVector<EVT, 4> ValueVTs; 1863 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1864 unsigned NumValues = ValueVTs.size(); 1865 if (NumValues) { 1866 SDValue RetOp = getValue(I.getOperand(0)); 1867 1868 const Function *F = I.getParent()->getParent(); 1869 1870 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1871 I.getOperand(0)->getType(), F->getCallingConv(), 1872 /*IsVarArg*/ false); 1873 1874 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1875 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1876 Attribute::SExt)) 1877 ExtendKind = ISD::SIGN_EXTEND; 1878 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1879 Attribute::ZExt)) 1880 ExtendKind = ISD::ZERO_EXTEND; 1881 1882 LLVMContext &Context = F->getContext(); 1883 bool RetInReg = F->getAttributes().hasAttribute( 1884 AttributeList::ReturnIndex, Attribute::InReg); 1885 1886 for (unsigned j = 0; j != NumValues; ++j) { 1887 EVT VT = ValueVTs[j]; 1888 1889 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1890 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1891 1892 CallingConv::ID CC = F->getCallingConv(); 1893 1894 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1895 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1896 SmallVector<SDValue, 4> Parts(NumParts); 1897 getCopyToParts(DAG, getCurSDLoc(), 1898 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1899 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1900 1901 // 'inreg' on function refers to return value 1902 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1903 if (RetInReg) 1904 Flags.setInReg(); 1905 1906 if (I.getOperand(0)->getType()->isPointerTy()) { 1907 Flags.setPointer(); 1908 Flags.setPointerAddrSpace( 1909 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1910 } 1911 1912 if (NeedsRegBlock) { 1913 Flags.setInConsecutiveRegs(); 1914 if (j == NumValues - 1) 1915 Flags.setInConsecutiveRegsLast(); 1916 } 1917 1918 // Propagate extension type if any 1919 if (ExtendKind == ISD::SIGN_EXTEND) 1920 Flags.setSExt(); 1921 else if (ExtendKind == ISD::ZERO_EXTEND) 1922 Flags.setZExt(); 1923 1924 for (unsigned i = 0; i < NumParts; ++i) { 1925 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1926 VT, /*isfixed=*/true, 0, 0)); 1927 OutVals.push_back(Parts[i]); 1928 } 1929 } 1930 } 1931 } 1932 1933 // Push in swifterror virtual register as the last element of Outs. This makes 1934 // sure swifterror virtual register will be returned in the swifterror 1935 // physical register. 1936 const Function *F = I.getParent()->getParent(); 1937 if (TLI.supportSwiftError() && 1938 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1939 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1940 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1941 Flags.setSwiftError(); 1942 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1943 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1944 true /*isfixed*/, 1 /*origidx*/, 1945 0 /*partOffs*/)); 1946 // Create SDNode for the swifterror virtual register. 1947 OutVals.push_back( 1948 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1949 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1950 EVT(TLI.getPointerTy(DL)))); 1951 } 1952 1953 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1954 CallingConv::ID CallConv = 1955 DAG.getMachineFunction().getFunction().getCallingConv(); 1956 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1957 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1958 1959 // Verify that the target's LowerReturn behaved as expected. 1960 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1961 "LowerReturn didn't return a valid chain!"); 1962 1963 // Update the DAG with the new chain value resulting from return lowering. 1964 DAG.setRoot(Chain); 1965 } 1966 1967 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1968 /// created for it, emit nodes to copy the value into the virtual 1969 /// registers. 1970 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1971 // Skip empty types 1972 if (V->getType()->isEmptyTy()) 1973 return; 1974 1975 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 1976 if (VMI != FuncInfo.ValueMap.end()) { 1977 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1978 CopyValueToVirtualRegister(V, VMI->second); 1979 } 1980 } 1981 1982 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1983 /// the current basic block, add it to ValueMap now so that we'll get a 1984 /// CopyTo/FromReg. 1985 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1986 // No need to export constants. 1987 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1988 1989 // Already exported? 1990 if (FuncInfo.isExportedInst(V)) return; 1991 1992 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1993 CopyValueToVirtualRegister(V, Reg); 1994 } 1995 1996 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1997 const BasicBlock *FromBB) { 1998 // The operands of the setcc have to be in this block. We don't know 1999 // how to export them from some other block. 2000 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2001 // Can export from current BB. 2002 if (VI->getParent() == FromBB) 2003 return true; 2004 2005 // Is already exported, noop. 2006 return FuncInfo.isExportedInst(V); 2007 } 2008 2009 // If this is an argument, we can export it if the BB is the entry block or 2010 // if it is already exported. 2011 if (isa<Argument>(V)) { 2012 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2013 return true; 2014 2015 // Otherwise, can only export this if it is already exported. 2016 return FuncInfo.isExportedInst(V); 2017 } 2018 2019 // Otherwise, constants can always be exported. 2020 return true; 2021 } 2022 2023 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2024 BranchProbability 2025 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2026 const MachineBasicBlock *Dst) const { 2027 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2028 const BasicBlock *SrcBB = Src->getBasicBlock(); 2029 const BasicBlock *DstBB = Dst->getBasicBlock(); 2030 if (!BPI) { 2031 // If BPI is not available, set the default probability as 1 / N, where N is 2032 // the number of successors. 2033 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2034 return BranchProbability(1, SuccSize); 2035 } 2036 return BPI->getEdgeProbability(SrcBB, DstBB); 2037 } 2038 2039 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2040 MachineBasicBlock *Dst, 2041 BranchProbability Prob) { 2042 if (!FuncInfo.BPI) 2043 Src->addSuccessorWithoutProb(Dst); 2044 else { 2045 if (Prob.isUnknown()) 2046 Prob = getEdgeProbability(Src, Dst); 2047 Src->addSuccessor(Dst, Prob); 2048 } 2049 } 2050 2051 static bool InBlock(const Value *V, const BasicBlock *BB) { 2052 if (const Instruction *I = dyn_cast<Instruction>(V)) 2053 return I->getParent() == BB; 2054 return true; 2055 } 2056 2057 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2058 /// This function emits a branch and is used at the leaves of an OR or an 2059 /// AND operator tree. 2060 void 2061 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2062 MachineBasicBlock *TBB, 2063 MachineBasicBlock *FBB, 2064 MachineBasicBlock *CurBB, 2065 MachineBasicBlock *SwitchBB, 2066 BranchProbability TProb, 2067 BranchProbability FProb, 2068 bool InvertCond) { 2069 const BasicBlock *BB = CurBB->getBasicBlock(); 2070 2071 // If the leaf of the tree is a comparison, merge the condition into 2072 // the caseblock. 2073 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2074 // The operands of the cmp have to be in this block. We don't know 2075 // how to export them from some other block. If this is the first block 2076 // of the sequence, no exporting is needed. 2077 if (CurBB == SwitchBB || 2078 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2079 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2080 ISD::CondCode Condition; 2081 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2082 ICmpInst::Predicate Pred = 2083 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2084 Condition = getICmpCondCode(Pred); 2085 } else { 2086 const FCmpInst *FC = cast<FCmpInst>(Cond); 2087 FCmpInst::Predicate Pred = 2088 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2089 Condition = getFCmpCondCode(Pred); 2090 if (TM.Options.NoNaNsFPMath) 2091 Condition = getFCmpCodeWithoutNaN(Condition); 2092 } 2093 2094 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2095 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2096 SL->SwitchCases.push_back(CB); 2097 return; 2098 } 2099 } 2100 2101 // Create a CaseBlock record representing this branch. 2102 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2103 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2104 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2105 SL->SwitchCases.push_back(CB); 2106 } 2107 2108 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2109 MachineBasicBlock *TBB, 2110 MachineBasicBlock *FBB, 2111 MachineBasicBlock *CurBB, 2112 MachineBasicBlock *SwitchBB, 2113 Instruction::BinaryOps Opc, 2114 BranchProbability TProb, 2115 BranchProbability FProb, 2116 bool InvertCond) { 2117 // Skip over not part of the tree and remember to invert op and operands at 2118 // next level. 2119 Value *NotCond; 2120 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2121 InBlock(NotCond, CurBB->getBasicBlock())) { 2122 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2123 !InvertCond); 2124 return; 2125 } 2126 2127 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2128 // Compute the effective opcode for Cond, taking into account whether it needs 2129 // to be inverted, e.g. 2130 // and (not (or A, B)), C 2131 // gets lowered as 2132 // and (and (not A, not B), C) 2133 unsigned BOpc = 0; 2134 if (BOp) { 2135 BOpc = BOp->getOpcode(); 2136 if (InvertCond) { 2137 if (BOpc == Instruction::And) 2138 BOpc = Instruction::Or; 2139 else if (BOpc == Instruction::Or) 2140 BOpc = Instruction::And; 2141 } 2142 } 2143 2144 // If this node is not part of the or/and tree, emit it as a branch. 2145 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2146 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2147 BOp->getParent() != CurBB->getBasicBlock() || 2148 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2149 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2150 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2151 TProb, FProb, InvertCond); 2152 return; 2153 } 2154 2155 // Create TmpBB after CurBB. 2156 MachineFunction::iterator BBI(CurBB); 2157 MachineFunction &MF = DAG.getMachineFunction(); 2158 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2159 CurBB->getParent()->insert(++BBI, TmpBB); 2160 2161 if (Opc == Instruction::Or) { 2162 // Codegen X | Y as: 2163 // BB1: 2164 // jmp_if_X TBB 2165 // jmp TmpBB 2166 // TmpBB: 2167 // jmp_if_Y TBB 2168 // jmp FBB 2169 // 2170 2171 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2172 // The requirement is that 2173 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2174 // = TrueProb for original BB. 2175 // Assuming the original probabilities are A and B, one choice is to set 2176 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2177 // A/(1+B) and 2B/(1+B). This choice assumes that 2178 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2179 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2180 // TmpBB, but the math is more complicated. 2181 2182 auto NewTrueProb = TProb / 2; 2183 auto NewFalseProb = TProb / 2 + FProb; 2184 // Emit the LHS condition. 2185 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2186 NewTrueProb, NewFalseProb, InvertCond); 2187 2188 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2189 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2190 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2191 // Emit the RHS condition into TmpBB. 2192 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2193 Probs[0], Probs[1], InvertCond); 2194 } else { 2195 assert(Opc == Instruction::And && "Unknown merge op!"); 2196 // Codegen X & Y as: 2197 // BB1: 2198 // jmp_if_X TmpBB 2199 // jmp FBB 2200 // TmpBB: 2201 // jmp_if_Y TBB 2202 // jmp FBB 2203 // 2204 // This requires creation of TmpBB after CurBB. 2205 2206 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2207 // The requirement is that 2208 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2209 // = FalseProb for original BB. 2210 // Assuming the original probabilities are A and B, one choice is to set 2211 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2212 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2213 // TrueProb for BB1 * FalseProb for TmpBB. 2214 2215 auto NewTrueProb = TProb + FProb / 2; 2216 auto NewFalseProb = FProb / 2; 2217 // Emit the LHS condition. 2218 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2219 NewTrueProb, NewFalseProb, InvertCond); 2220 2221 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2222 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2223 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2224 // Emit the RHS condition into TmpBB. 2225 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2226 Probs[0], Probs[1], InvertCond); 2227 } 2228 } 2229 2230 /// If the set of cases should be emitted as a series of branches, return true. 2231 /// If we should emit this as a bunch of and/or'd together conditions, return 2232 /// false. 2233 bool 2234 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2235 if (Cases.size() != 2) return true; 2236 2237 // If this is two comparisons of the same values or'd or and'd together, they 2238 // will get folded into a single comparison, so don't emit two blocks. 2239 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2240 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2241 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2242 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2243 return false; 2244 } 2245 2246 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2247 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2248 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2249 Cases[0].CC == Cases[1].CC && 2250 isa<Constant>(Cases[0].CmpRHS) && 2251 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2252 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2253 return false; 2254 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2255 return false; 2256 } 2257 2258 return true; 2259 } 2260 2261 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2262 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2263 2264 // Update machine-CFG edges. 2265 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2266 2267 if (I.isUnconditional()) { 2268 // Update machine-CFG edges. 2269 BrMBB->addSuccessor(Succ0MBB); 2270 2271 // If this is not a fall-through branch or optimizations are switched off, 2272 // emit the branch. 2273 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2274 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2275 MVT::Other, getControlRoot(), 2276 DAG.getBasicBlock(Succ0MBB))); 2277 2278 return; 2279 } 2280 2281 // If this condition is one of the special cases we handle, do special stuff 2282 // now. 2283 const Value *CondVal = I.getCondition(); 2284 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2285 2286 // If this is a series of conditions that are or'd or and'd together, emit 2287 // this as a sequence of branches instead of setcc's with and/or operations. 2288 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2289 // unpredictable branches, and vector extracts because those jumps are likely 2290 // expensive for any target), this should improve performance. 2291 // For example, instead of something like: 2292 // cmp A, B 2293 // C = seteq 2294 // cmp D, E 2295 // F = setle 2296 // or C, F 2297 // jnz foo 2298 // Emit: 2299 // cmp A, B 2300 // je foo 2301 // cmp D, E 2302 // jle foo 2303 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2304 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2305 Value *Vec, *BOp0 = BOp->getOperand(0), *BOp1 = BOp->getOperand(1); 2306 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2307 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2308 (Opcode == Instruction::And || Opcode == Instruction::Or) && 2309 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2310 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2311 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2312 Opcode, 2313 getEdgeProbability(BrMBB, Succ0MBB), 2314 getEdgeProbability(BrMBB, Succ1MBB), 2315 /*InvertCond=*/false); 2316 // If the compares in later blocks need to use values not currently 2317 // exported from this block, export them now. This block should always 2318 // be the first entry. 2319 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2320 2321 // Allow some cases to be rejected. 2322 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2323 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2324 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2325 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2326 } 2327 2328 // Emit the branch for this block. 2329 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2330 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2331 return; 2332 } 2333 2334 // Okay, we decided not to do this, remove any inserted MBB's and clear 2335 // SwitchCases. 2336 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2337 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2338 2339 SL->SwitchCases.clear(); 2340 } 2341 } 2342 2343 // Create a CaseBlock record representing this branch. 2344 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2345 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2346 2347 // Use visitSwitchCase to actually insert the fast branch sequence for this 2348 // cond branch. 2349 visitSwitchCase(CB, BrMBB); 2350 } 2351 2352 /// visitSwitchCase - Emits the necessary code to represent a single node in 2353 /// the binary search tree resulting from lowering a switch instruction. 2354 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2355 MachineBasicBlock *SwitchBB) { 2356 SDValue Cond; 2357 SDValue CondLHS = getValue(CB.CmpLHS); 2358 SDLoc dl = CB.DL; 2359 2360 if (CB.CC == ISD::SETTRUE) { 2361 // Branch or fall through to TrueBB. 2362 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2363 SwitchBB->normalizeSuccProbs(); 2364 if (CB.TrueBB != NextBlock(SwitchBB)) { 2365 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2366 DAG.getBasicBlock(CB.TrueBB))); 2367 } 2368 return; 2369 } 2370 2371 auto &TLI = DAG.getTargetLoweringInfo(); 2372 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2373 2374 // Build the setcc now. 2375 if (!CB.CmpMHS) { 2376 // Fold "(X == true)" to X and "(X == false)" to !X to 2377 // handle common cases produced by branch lowering. 2378 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2379 CB.CC == ISD::SETEQ) 2380 Cond = CondLHS; 2381 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2382 CB.CC == ISD::SETEQ) { 2383 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2384 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2385 } else { 2386 SDValue CondRHS = getValue(CB.CmpRHS); 2387 2388 // If a pointer's DAG type is larger than its memory type then the DAG 2389 // values are zero-extended. This breaks signed comparisons so truncate 2390 // back to the underlying type before doing the compare. 2391 if (CondLHS.getValueType() != MemVT) { 2392 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2393 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2394 } 2395 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2396 } 2397 } else { 2398 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2399 2400 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2401 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2402 2403 SDValue CmpOp = getValue(CB.CmpMHS); 2404 EVT VT = CmpOp.getValueType(); 2405 2406 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2407 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2408 ISD::SETLE); 2409 } else { 2410 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2411 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2412 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2413 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2414 } 2415 } 2416 2417 // Update successor info 2418 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2419 // TrueBB and FalseBB are always different unless the incoming IR is 2420 // degenerate. This only happens when running llc on weird IR. 2421 if (CB.TrueBB != CB.FalseBB) 2422 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2423 SwitchBB->normalizeSuccProbs(); 2424 2425 // If the lhs block is the next block, invert the condition so that we can 2426 // fall through to the lhs instead of the rhs block. 2427 if (CB.TrueBB == NextBlock(SwitchBB)) { 2428 std::swap(CB.TrueBB, CB.FalseBB); 2429 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2430 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2431 } 2432 2433 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2434 MVT::Other, getControlRoot(), Cond, 2435 DAG.getBasicBlock(CB.TrueBB)); 2436 2437 // Insert the false branch. Do this even if it's a fall through branch, 2438 // this makes it easier to do DAG optimizations which require inverting 2439 // the branch condition. 2440 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2441 DAG.getBasicBlock(CB.FalseBB)); 2442 2443 DAG.setRoot(BrCond); 2444 } 2445 2446 /// visitJumpTable - Emit JumpTable node in the current MBB 2447 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2448 // Emit the code for the jump table 2449 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2450 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2451 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2452 JT.Reg, PTy); 2453 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2454 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2455 MVT::Other, Index.getValue(1), 2456 Table, Index); 2457 DAG.setRoot(BrJumpTable); 2458 } 2459 2460 /// visitJumpTableHeader - This function emits necessary code to produce index 2461 /// in the JumpTable from switch case. 2462 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2463 JumpTableHeader &JTH, 2464 MachineBasicBlock *SwitchBB) { 2465 SDLoc dl = getCurSDLoc(); 2466 2467 // Subtract the lowest switch case value from the value being switched on. 2468 SDValue SwitchOp = getValue(JTH.SValue); 2469 EVT VT = SwitchOp.getValueType(); 2470 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2471 DAG.getConstant(JTH.First, dl, VT)); 2472 2473 // The SDNode we just created, which holds the value being switched on minus 2474 // the smallest case value, needs to be copied to a virtual register so it 2475 // can be used as an index into the jump table in a subsequent basic block. 2476 // This value may be smaller or larger than the target's pointer type, and 2477 // therefore require extension or truncating. 2478 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2479 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2480 2481 unsigned JumpTableReg = 2482 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2483 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2484 JumpTableReg, SwitchOp); 2485 JT.Reg = JumpTableReg; 2486 2487 if (!JTH.OmitRangeCheck) { 2488 // Emit the range check for the jump table, and branch to the default block 2489 // for the switch statement if the value being switched on exceeds the 2490 // largest case in the switch. 2491 SDValue CMP = DAG.getSetCC( 2492 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2493 Sub.getValueType()), 2494 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2495 2496 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2497 MVT::Other, CopyTo, CMP, 2498 DAG.getBasicBlock(JT.Default)); 2499 2500 // Avoid emitting unnecessary branches to the next block. 2501 if (JT.MBB != NextBlock(SwitchBB)) 2502 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2503 DAG.getBasicBlock(JT.MBB)); 2504 2505 DAG.setRoot(BrCond); 2506 } else { 2507 // Avoid emitting unnecessary branches to the next block. 2508 if (JT.MBB != NextBlock(SwitchBB)) 2509 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2510 DAG.getBasicBlock(JT.MBB))); 2511 else 2512 DAG.setRoot(CopyTo); 2513 } 2514 } 2515 2516 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2517 /// variable if there exists one. 2518 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2519 SDValue &Chain) { 2520 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2521 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2522 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2523 MachineFunction &MF = DAG.getMachineFunction(); 2524 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2525 MachineSDNode *Node = 2526 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2527 if (Global) { 2528 MachinePointerInfo MPInfo(Global); 2529 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2530 MachineMemOperand::MODereferenceable; 2531 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2532 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2533 DAG.setNodeMemRefs(Node, {MemRef}); 2534 } 2535 if (PtrTy != PtrMemTy) 2536 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2537 return SDValue(Node, 0); 2538 } 2539 2540 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2541 /// tail spliced into a stack protector check success bb. 2542 /// 2543 /// For a high level explanation of how this fits into the stack protector 2544 /// generation see the comment on the declaration of class 2545 /// StackProtectorDescriptor. 2546 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2547 MachineBasicBlock *ParentBB) { 2548 2549 // First create the loads to the guard/stack slot for the comparison. 2550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2551 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2552 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2553 2554 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2555 int FI = MFI.getStackProtectorIndex(); 2556 2557 SDValue Guard; 2558 SDLoc dl = getCurSDLoc(); 2559 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2560 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2561 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2562 2563 // Generate code to load the content of the guard slot. 2564 SDValue GuardVal = DAG.getLoad( 2565 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2566 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2567 MachineMemOperand::MOVolatile); 2568 2569 if (TLI.useStackGuardXorFP()) 2570 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2571 2572 // Retrieve guard check function, nullptr if instrumentation is inlined. 2573 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2574 // The target provides a guard check function to validate the guard value. 2575 // Generate a call to that function with the content of the guard slot as 2576 // argument. 2577 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2578 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2579 2580 TargetLowering::ArgListTy Args; 2581 TargetLowering::ArgListEntry Entry; 2582 Entry.Node = GuardVal; 2583 Entry.Ty = FnTy->getParamType(0); 2584 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2585 Entry.IsInReg = true; 2586 Args.push_back(Entry); 2587 2588 TargetLowering::CallLoweringInfo CLI(DAG); 2589 CLI.setDebugLoc(getCurSDLoc()) 2590 .setChain(DAG.getEntryNode()) 2591 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2592 getValue(GuardCheckFn), std::move(Args)); 2593 2594 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2595 DAG.setRoot(Result.second); 2596 return; 2597 } 2598 2599 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2600 // Otherwise, emit a volatile load to retrieve the stack guard value. 2601 SDValue Chain = DAG.getEntryNode(); 2602 if (TLI.useLoadStackGuardNode()) { 2603 Guard = getLoadStackGuard(DAG, dl, Chain); 2604 } else { 2605 const Value *IRGuard = TLI.getSDagStackGuard(M); 2606 SDValue GuardPtr = getValue(IRGuard); 2607 2608 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2609 MachinePointerInfo(IRGuard, 0), Align, 2610 MachineMemOperand::MOVolatile); 2611 } 2612 2613 // Perform the comparison via a getsetcc. 2614 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2615 *DAG.getContext(), 2616 Guard.getValueType()), 2617 Guard, GuardVal, ISD::SETNE); 2618 2619 // If the guard/stackslot do not equal, branch to failure MBB. 2620 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2621 MVT::Other, GuardVal.getOperand(0), 2622 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2623 // Otherwise branch to success MBB. 2624 SDValue Br = DAG.getNode(ISD::BR, dl, 2625 MVT::Other, BrCond, 2626 DAG.getBasicBlock(SPD.getSuccessMBB())); 2627 2628 DAG.setRoot(Br); 2629 } 2630 2631 /// Codegen the failure basic block for a stack protector check. 2632 /// 2633 /// A failure stack protector machine basic block consists simply of a call to 2634 /// __stack_chk_fail(). 2635 /// 2636 /// For a high level explanation of how this fits into the stack protector 2637 /// generation see the comment on the declaration of class 2638 /// StackProtectorDescriptor. 2639 void 2640 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2641 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2642 TargetLowering::MakeLibCallOptions CallOptions; 2643 CallOptions.setDiscardResult(true); 2644 SDValue Chain = 2645 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2646 None, CallOptions, getCurSDLoc()).second; 2647 // On PS4, the "return address" must still be within the calling function, 2648 // even if it's at the very end, so emit an explicit TRAP here. 2649 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2650 if (TM.getTargetTriple().isPS4CPU()) 2651 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2652 // WebAssembly needs an unreachable instruction after a non-returning call, 2653 // because the function return type can be different from __stack_chk_fail's 2654 // return type (void). 2655 if (TM.getTargetTriple().isWasm()) 2656 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2657 2658 DAG.setRoot(Chain); 2659 } 2660 2661 /// visitBitTestHeader - This function emits necessary code to produce value 2662 /// suitable for "bit tests" 2663 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2664 MachineBasicBlock *SwitchBB) { 2665 SDLoc dl = getCurSDLoc(); 2666 2667 // Subtract the minimum value. 2668 SDValue SwitchOp = getValue(B.SValue); 2669 EVT VT = SwitchOp.getValueType(); 2670 SDValue RangeSub = 2671 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2672 2673 // Determine the type of the test operands. 2674 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2675 bool UsePtrType = false; 2676 if (!TLI.isTypeLegal(VT)) { 2677 UsePtrType = true; 2678 } else { 2679 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2680 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2681 // Switch table case range are encoded into series of masks. 2682 // Just use pointer type, it's guaranteed to fit. 2683 UsePtrType = true; 2684 break; 2685 } 2686 } 2687 SDValue Sub = RangeSub; 2688 if (UsePtrType) { 2689 VT = TLI.getPointerTy(DAG.getDataLayout()); 2690 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2691 } 2692 2693 B.RegVT = VT.getSimpleVT(); 2694 B.Reg = FuncInfo.CreateReg(B.RegVT); 2695 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2696 2697 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2698 2699 if (!B.OmitRangeCheck) 2700 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2701 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2702 SwitchBB->normalizeSuccProbs(); 2703 2704 SDValue Root = CopyTo; 2705 if (!B.OmitRangeCheck) { 2706 // Conditional branch to the default block. 2707 SDValue RangeCmp = DAG.getSetCC(dl, 2708 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2709 RangeSub.getValueType()), 2710 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2711 ISD::SETUGT); 2712 2713 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2714 DAG.getBasicBlock(B.Default)); 2715 } 2716 2717 // Avoid emitting unnecessary branches to the next block. 2718 if (MBB != NextBlock(SwitchBB)) 2719 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2720 2721 DAG.setRoot(Root); 2722 } 2723 2724 /// visitBitTestCase - this function produces one "bit test" 2725 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2726 MachineBasicBlock* NextMBB, 2727 BranchProbability BranchProbToNext, 2728 unsigned Reg, 2729 BitTestCase &B, 2730 MachineBasicBlock *SwitchBB) { 2731 SDLoc dl = getCurSDLoc(); 2732 MVT VT = BB.RegVT; 2733 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2734 SDValue Cmp; 2735 unsigned PopCount = countPopulation(B.Mask); 2736 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2737 if (PopCount == 1) { 2738 // Testing for a single bit; just compare the shift count with what it 2739 // would need to be to shift a 1 bit in that position. 2740 Cmp = DAG.getSetCC( 2741 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2742 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2743 ISD::SETEQ); 2744 } else if (PopCount == BB.Range) { 2745 // There is only one zero bit in the range, test for it directly. 2746 Cmp = DAG.getSetCC( 2747 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2748 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2749 ISD::SETNE); 2750 } else { 2751 // Make desired shift 2752 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2753 DAG.getConstant(1, dl, VT), ShiftOp); 2754 2755 // Emit bit tests and jumps 2756 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2757 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2758 Cmp = DAG.getSetCC( 2759 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2760 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2761 } 2762 2763 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2764 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2765 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2766 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2767 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2768 // one as they are relative probabilities (and thus work more like weights), 2769 // and hence we need to normalize them to let the sum of them become one. 2770 SwitchBB->normalizeSuccProbs(); 2771 2772 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2773 MVT::Other, getControlRoot(), 2774 Cmp, DAG.getBasicBlock(B.TargetBB)); 2775 2776 // Avoid emitting unnecessary branches to the next block. 2777 if (NextMBB != NextBlock(SwitchBB)) 2778 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2779 DAG.getBasicBlock(NextMBB)); 2780 2781 DAG.setRoot(BrAnd); 2782 } 2783 2784 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2785 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2786 2787 // Retrieve successors. Look through artificial IR level blocks like 2788 // catchswitch for successors. 2789 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2790 const BasicBlock *EHPadBB = I.getSuccessor(1); 2791 2792 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2793 // have to do anything here to lower funclet bundles. 2794 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2795 LLVMContext::OB_gc_transition, 2796 LLVMContext::OB_gc_live, 2797 LLVMContext::OB_funclet, 2798 LLVMContext::OB_cfguardtarget}) && 2799 "Cannot lower invokes with arbitrary operand bundles yet!"); 2800 2801 const Value *Callee(I.getCalledOperand()); 2802 const Function *Fn = dyn_cast<Function>(Callee); 2803 if (isa<InlineAsm>(Callee)) 2804 visitInlineAsm(I); 2805 else if (Fn && Fn->isIntrinsic()) { 2806 switch (Fn->getIntrinsicID()) { 2807 default: 2808 llvm_unreachable("Cannot invoke this intrinsic"); 2809 case Intrinsic::donothing: 2810 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2811 break; 2812 case Intrinsic::experimental_patchpoint_void: 2813 case Intrinsic::experimental_patchpoint_i64: 2814 visitPatchpoint(I, EHPadBB); 2815 break; 2816 case Intrinsic::experimental_gc_statepoint: 2817 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2818 break; 2819 case Intrinsic::wasm_rethrow_in_catch: { 2820 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2821 // special because it can be invoked, so we manually lower it to a DAG 2822 // node here. 2823 SmallVector<SDValue, 8> Ops; 2824 Ops.push_back(getRoot()); // inchain 2825 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2826 Ops.push_back( 2827 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2828 TLI.getPointerTy(DAG.getDataLayout()))); 2829 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2830 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2831 break; 2832 } 2833 } 2834 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2835 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2836 // Eventually we will support lowering the @llvm.experimental.deoptimize 2837 // intrinsic, and right now there are no plans to support other intrinsics 2838 // with deopt state. 2839 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2840 } else { 2841 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2842 } 2843 2844 // If the value of the invoke is used outside of its defining block, make it 2845 // available as a virtual register. 2846 // We already took care of the exported value for the statepoint instruction 2847 // during call to the LowerStatepoint. 2848 if (!isa<GCStatepointInst>(I)) { 2849 CopyToExportRegsIfNeeded(&I); 2850 } 2851 2852 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2853 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2854 BranchProbability EHPadBBProb = 2855 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2856 : BranchProbability::getZero(); 2857 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2858 2859 // Update successor info. 2860 addSuccessorWithProb(InvokeMBB, Return); 2861 for (auto &UnwindDest : UnwindDests) { 2862 UnwindDest.first->setIsEHPad(); 2863 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2864 } 2865 InvokeMBB->normalizeSuccProbs(); 2866 2867 // Drop into normal successor. 2868 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2869 DAG.getBasicBlock(Return))); 2870 } 2871 2872 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2873 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2874 2875 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2876 // have to do anything here to lower funclet bundles. 2877 assert(!I.hasOperandBundlesOtherThan( 2878 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2879 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2880 2881 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2882 visitInlineAsm(I); 2883 CopyToExportRegsIfNeeded(&I); 2884 2885 // Retrieve successors. 2886 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2887 2888 // Update successor info. 2889 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2890 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2891 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2892 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2893 Target->setIsInlineAsmBrIndirectTarget(); 2894 } 2895 CallBrMBB->normalizeSuccProbs(); 2896 2897 // Drop into default successor. 2898 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2899 MVT::Other, getControlRoot(), 2900 DAG.getBasicBlock(Return))); 2901 } 2902 2903 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2904 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2905 } 2906 2907 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2908 assert(FuncInfo.MBB->isEHPad() && 2909 "Call to landingpad not in landing pad!"); 2910 2911 // If there aren't registers to copy the values into (e.g., during SjLj 2912 // exceptions), then don't bother to create these DAG nodes. 2913 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2914 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2915 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2916 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2917 return; 2918 2919 // If landingpad's return type is token type, we don't create DAG nodes 2920 // for its exception pointer and selector value. The extraction of exception 2921 // pointer or selector value from token type landingpads is not currently 2922 // supported. 2923 if (LP.getType()->isTokenTy()) 2924 return; 2925 2926 SmallVector<EVT, 2> ValueVTs; 2927 SDLoc dl = getCurSDLoc(); 2928 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2929 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2930 2931 // Get the two live-in registers as SDValues. The physregs have already been 2932 // copied into virtual registers. 2933 SDValue Ops[2]; 2934 if (FuncInfo.ExceptionPointerVirtReg) { 2935 Ops[0] = DAG.getZExtOrTrunc( 2936 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2937 FuncInfo.ExceptionPointerVirtReg, 2938 TLI.getPointerTy(DAG.getDataLayout())), 2939 dl, ValueVTs[0]); 2940 } else { 2941 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2942 } 2943 Ops[1] = DAG.getZExtOrTrunc( 2944 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2945 FuncInfo.ExceptionSelectorVirtReg, 2946 TLI.getPointerTy(DAG.getDataLayout())), 2947 dl, ValueVTs[1]); 2948 2949 // Merge into one. 2950 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2951 DAG.getVTList(ValueVTs), Ops); 2952 setValue(&LP, Res); 2953 } 2954 2955 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2956 MachineBasicBlock *Last) { 2957 // Update JTCases. 2958 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2959 if (SL->JTCases[i].first.HeaderBB == First) 2960 SL->JTCases[i].first.HeaderBB = Last; 2961 2962 // Update BitTestCases. 2963 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2964 if (SL->BitTestCases[i].Parent == First) 2965 SL->BitTestCases[i].Parent = Last; 2966 } 2967 2968 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2969 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2970 2971 // Update machine-CFG edges with unique successors. 2972 SmallSet<BasicBlock*, 32> Done; 2973 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2974 BasicBlock *BB = I.getSuccessor(i); 2975 bool Inserted = Done.insert(BB).second; 2976 if (!Inserted) 2977 continue; 2978 2979 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2980 addSuccessorWithProb(IndirectBrMBB, Succ); 2981 } 2982 IndirectBrMBB->normalizeSuccProbs(); 2983 2984 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2985 MVT::Other, getControlRoot(), 2986 getValue(I.getAddress()))); 2987 } 2988 2989 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2990 if (!DAG.getTarget().Options.TrapUnreachable) 2991 return; 2992 2993 // We may be able to ignore unreachable behind a noreturn call. 2994 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2995 const BasicBlock &BB = *I.getParent(); 2996 if (&I != &BB.front()) { 2997 BasicBlock::const_iterator PredI = 2998 std::prev(BasicBlock::const_iterator(&I)); 2999 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3000 if (Call->doesNotReturn()) 3001 return; 3002 } 3003 } 3004 } 3005 3006 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3007 } 3008 3009 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3010 SDNodeFlags Flags; 3011 3012 SDValue Op = getValue(I.getOperand(0)); 3013 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3014 Op, Flags); 3015 setValue(&I, UnNodeValue); 3016 } 3017 3018 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3019 SDNodeFlags Flags; 3020 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3021 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3022 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3023 } 3024 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3025 Flags.setExact(ExactOp->isExact()); 3026 } 3027 3028 SDValue Op1 = getValue(I.getOperand(0)); 3029 SDValue Op2 = getValue(I.getOperand(1)); 3030 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3031 Op1, Op2, Flags); 3032 setValue(&I, BinNodeValue); 3033 } 3034 3035 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3036 SDValue Op1 = getValue(I.getOperand(0)); 3037 SDValue Op2 = getValue(I.getOperand(1)); 3038 3039 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3040 Op1.getValueType(), DAG.getDataLayout()); 3041 3042 // Coerce the shift amount to the right type if we can. 3043 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3044 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3045 unsigned Op2Size = Op2.getValueSizeInBits(); 3046 SDLoc DL = getCurSDLoc(); 3047 3048 // If the operand is smaller than the shift count type, promote it. 3049 if (ShiftSize > Op2Size) 3050 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3051 3052 // If the operand is larger than the shift count type but the shift 3053 // count type has enough bits to represent any shift value, truncate 3054 // it now. This is a common case and it exposes the truncate to 3055 // optimization early. 3056 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3057 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3058 // Otherwise we'll need to temporarily settle for some other convenient 3059 // type. Type legalization will make adjustments once the shiftee is split. 3060 else 3061 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3062 } 3063 3064 bool nuw = false; 3065 bool nsw = false; 3066 bool exact = false; 3067 3068 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3069 3070 if (const OverflowingBinaryOperator *OFBinOp = 3071 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3072 nuw = OFBinOp->hasNoUnsignedWrap(); 3073 nsw = OFBinOp->hasNoSignedWrap(); 3074 } 3075 if (const PossiblyExactOperator *ExactOp = 3076 dyn_cast<const PossiblyExactOperator>(&I)) 3077 exact = ExactOp->isExact(); 3078 } 3079 SDNodeFlags Flags; 3080 Flags.setExact(exact); 3081 Flags.setNoSignedWrap(nsw); 3082 Flags.setNoUnsignedWrap(nuw); 3083 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3084 Flags); 3085 setValue(&I, Res); 3086 } 3087 3088 void SelectionDAGBuilder::visitSDiv(const User &I) { 3089 SDValue Op1 = getValue(I.getOperand(0)); 3090 SDValue Op2 = getValue(I.getOperand(1)); 3091 3092 SDNodeFlags Flags; 3093 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3094 cast<PossiblyExactOperator>(&I)->isExact()); 3095 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3096 Op2, Flags)); 3097 } 3098 3099 void SelectionDAGBuilder::visitICmp(const User &I) { 3100 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3101 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3102 predicate = IC->getPredicate(); 3103 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3104 predicate = ICmpInst::Predicate(IC->getPredicate()); 3105 SDValue Op1 = getValue(I.getOperand(0)); 3106 SDValue Op2 = getValue(I.getOperand(1)); 3107 ISD::CondCode Opcode = getICmpCondCode(predicate); 3108 3109 auto &TLI = DAG.getTargetLoweringInfo(); 3110 EVT MemVT = 3111 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3112 3113 // If a pointer's DAG type is larger than its memory type then the DAG values 3114 // are zero-extended. This breaks signed comparisons so truncate back to the 3115 // underlying type before doing the compare. 3116 if (Op1.getValueType() != MemVT) { 3117 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3118 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3119 } 3120 3121 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3122 I.getType()); 3123 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3124 } 3125 3126 void SelectionDAGBuilder::visitFCmp(const User &I) { 3127 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3128 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3129 predicate = FC->getPredicate(); 3130 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3131 predicate = FCmpInst::Predicate(FC->getPredicate()); 3132 SDValue Op1 = getValue(I.getOperand(0)); 3133 SDValue Op2 = getValue(I.getOperand(1)); 3134 3135 ISD::CondCode Condition = getFCmpCondCode(predicate); 3136 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3137 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3138 Condition = getFCmpCodeWithoutNaN(Condition); 3139 3140 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3141 I.getType()); 3142 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3143 } 3144 3145 // Check if the condition of the select has one use or two users that are both 3146 // selects with the same condition. 3147 static bool hasOnlySelectUsers(const Value *Cond) { 3148 return llvm::all_of(Cond->users(), [](const Value *V) { 3149 return isa<SelectInst>(V); 3150 }); 3151 } 3152 3153 void SelectionDAGBuilder::visitSelect(const User &I) { 3154 SmallVector<EVT, 4> ValueVTs; 3155 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3156 ValueVTs); 3157 unsigned NumValues = ValueVTs.size(); 3158 if (NumValues == 0) return; 3159 3160 SmallVector<SDValue, 4> Values(NumValues); 3161 SDValue Cond = getValue(I.getOperand(0)); 3162 SDValue LHSVal = getValue(I.getOperand(1)); 3163 SDValue RHSVal = getValue(I.getOperand(2)); 3164 SmallVector<SDValue, 1> BaseOps(1, Cond); 3165 ISD::NodeType OpCode = 3166 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3167 3168 bool IsUnaryAbs = false; 3169 3170 // Min/max matching is only viable if all output VTs are the same. 3171 if (is_splat(ValueVTs)) { 3172 EVT VT = ValueVTs[0]; 3173 LLVMContext &Ctx = *DAG.getContext(); 3174 auto &TLI = DAG.getTargetLoweringInfo(); 3175 3176 // We care about the legality of the operation after it has been type 3177 // legalized. 3178 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3179 VT = TLI.getTypeToTransformTo(Ctx, VT); 3180 3181 // If the vselect is legal, assume we want to leave this as a vector setcc + 3182 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3183 // min/max is legal on the scalar type. 3184 bool UseScalarMinMax = VT.isVector() && 3185 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3186 3187 Value *LHS, *RHS; 3188 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3189 ISD::NodeType Opc = ISD::DELETED_NODE; 3190 switch (SPR.Flavor) { 3191 case SPF_UMAX: Opc = ISD::UMAX; break; 3192 case SPF_UMIN: Opc = ISD::UMIN; break; 3193 case SPF_SMAX: Opc = ISD::SMAX; break; 3194 case SPF_SMIN: Opc = ISD::SMIN; break; 3195 case SPF_FMINNUM: 3196 switch (SPR.NaNBehavior) { 3197 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3198 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3199 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3200 case SPNB_RETURNS_ANY: { 3201 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3202 Opc = ISD::FMINNUM; 3203 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3204 Opc = ISD::FMINIMUM; 3205 else if (UseScalarMinMax) 3206 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3207 ISD::FMINNUM : ISD::FMINIMUM; 3208 break; 3209 } 3210 } 3211 break; 3212 case SPF_FMAXNUM: 3213 switch (SPR.NaNBehavior) { 3214 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3215 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3216 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3217 case SPNB_RETURNS_ANY: 3218 3219 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3220 Opc = ISD::FMAXNUM; 3221 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3222 Opc = ISD::FMAXIMUM; 3223 else if (UseScalarMinMax) 3224 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3225 ISD::FMAXNUM : ISD::FMAXIMUM; 3226 break; 3227 } 3228 break; 3229 case SPF_ABS: 3230 IsUnaryAbs = true; 3231 Opc = ISD::ABS; 3232 break; 3233 case SPF_NABS: 3234 // TODO: we need to produce sub(0, abs(X)). 3235 default: break; 3236 } 3237 3238 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3239 (TLI.isOperationLegalOrCustom(Opc, VT) || 3240 (UseScalarMinMax && 3241 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3242 // If the underlying comparison instruction is used by any other 3243 // instruction, the consumed instructions won't be destroyed, so it is 3244 // not profitable to convert to a min/max. 3245 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3246 OpCode = Opc; 3247 LHSVal = getValue(LHS); 3248 RHSVal = getValue(RHS); 3249 BaseOps.clear(); 3250 } 3251 3252 if (IsUnaryAbs) { 3253 OpCode = Opc; 3254 LHSVal = getValue(LHS); 3255 BaseOps.clear(); 3256 } 3257 } 3258 3259 if (IsUnaryAbs) { 3260 for (unsigned i = 0; i != NumValues; ++i) { 3261 Values[i] = 3262 DAG.getNode(OpCode, getCurSDLoc(), 3263 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3264 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3265 } 3266 } else { 3267 for (unsigned i = 0; i != NumValues; ++i) { 3268 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3269 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3270 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3271 Values[i] = DAG.getNode( 3272 OpCode, getCurSDLoc(), 3273 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3274 } 3275 } 3276 3277 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3278 DAG.getVTList(ValueVTs), Values)); 3279 } 3280 3281 void SelectionDAGBuilder::visitTrunc(const User &I) { 3282 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3283 SDValue N = getValue(I.getOperand(0)); 3284 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3285 I.getType()); 3286 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3287 } 3288 3289 void SelectionDAGBuilder::visitZExt(const User &I) { 3290 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3291 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3292 SDValue N = getValue(I.getOperand(0)); 3293 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3294 I.getType()); 3295 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3296 } 3297 3298 void SelectionDAGBuilder::visitSExt(const User &I) { 3299 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3300 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3301 SDValue N = getValue(I.getOperand(0)); 3302 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3303 I.getType()); 3304 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3305 } 3306 3307 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3308 // FPTrunc is never a no-op cast, no need to check 3309 SDValue N = getValue(I.getOperand(0)); 3310 SDLoc dl = getCurSDLoc(); 3311 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3312 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3313 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3314 DAG.getTargetConstant( 3315 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3316 } 3317 3318 void SelectionDAGBuilder::visitFPExt(const User &I) { 3319 // FPExt is never a no-op cast, no need to check 3320 SDValue N = getValue(I.getOperand(0)); 3321 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3322 I.getType()); 3323 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3324 } 3325 3326 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3327 // FPToUI is never a no-op cast, no need to check 3328 SDValue N = getValue(I.getOperand(0)); 3329 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3330 I.getType()); 3331 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3332 } 3333 3334 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3335 // FPToSI is never a no-op cast, no need to check 3336 SDValue N = getValue(I.getOperand(0)); 3337 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3338 I.getType()); 3339 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3340 } 3341 3342 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3343 // UIToFP is never a no-op cast, no need to check 3344 SDValue N = getValue(I.getOperand(0)); 3345 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3346 I.getType()); 3347 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3348 } 3349 3350 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3351 // SIToFP is never a no-op cast, no need to check 3352 SDValue N = getValue(I.getOperand(0)); 3353 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3354 I.getType()); 3355 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3356 } 3357 3358 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3359 // What to do depends on the size of the integer and the size of the pointer. 3360 // We can either truncate, zero extend, or no-op, accordingly. 3361 SDValue N = getValue(I.getOperand(0)); 3362 auto &TLI = DAG.getTargetLoweringInfo(); 3363 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3364 I.getType()); 3365 EVT PtrMemVT = 3366 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3367 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3368 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3369 setValue(&I, N); 3370 } 3371 3372 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3373 // What to do depends on the size of the integer and the size of the pointer. 3374 // We can either truncate, zero extend, or no-op, accordingly. 3375 SDValue N = getValue(I.getOperand(0)); 3376 auto &TLI = DAG.getTargetLoweringInfo(); 3377 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3378 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3379 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3380 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3381 setValue(&I, N); 3382 } 3383 3384 void SelectionDAGBuilder::visitBitCast(const User &I) { 3385 SDValue N = getValue(I.getOperand(0)); 3386 SDLoc dl = getCurSDLoc(); 3387 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3388 I.getType()); 3389 3390 // BitCast assures us that source and destination are the same size so this is 3391 // either a BITCAST or a no-op. 3392 if (DestVT != N.getValueType()) 3393 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3394 DestVT, N)); // convert types. 3395 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3396 // might fold any kind of constant expression to an integer constant and that 3397 // is not what we are looking for. Only recognize a bitcast of a genuine 3398 // constant integer as an opaque constant. 3399 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3400 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3401 /*isOpaque*/true)); 3402 else 3403 setValue(&I, N); // noop cast. 3404 } 3405 3406 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3407 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3408 const Value *SV = I.getOperand(0); 3409 SDValue N = getValue(SV); 3410 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3411 3412 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3413 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3414 3415 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3416 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3417 3418 setValue(&I, N); 3419 } 3420 3421 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3422 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3423 SDValue InVec = getValue(I.getOperand(0)); 3424 SDValue InVal = getValue(I.getOperand(1)); 3425 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3426 TLI.getVectorIdxTy(DAG.getDataLayout())); 3427 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3428 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3429 InVec, InVal, InIdx)); 3430 } 3431 3432 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3433 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3434 SDValue InVec = getValue(I.getOperand(0)); 3435 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3436 TLI.getVectorIdxTy(DAG.getDataLayout())); 3437 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3438 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3439 InVec, InIdx)); 3440 } 3441 3442 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3443 SDValue Src1 = getValue(I.getOperand(0)); 3444 SDValue Src2 = getValue(I.getOperand(1)); 3445 ArrayRef<int> Mask; 3446 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3447 Mask = SVI->getShuffleMask(); 3448 else 3449 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3450 SDLoc DL = getCurSDLoc(); 3451 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3452 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3453 EVT SrcVT = Src1.getValueType(); 3454 3455 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3456 VT.isScalableVector()) { 3457 // Canonical splat form of first element of first input vector. 3458 SDValue FirstElt = 3459 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3460 DAG.getVectorIdxConstant(0, DL)); 3461 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3462 return; 3463 } 3464 3465 // For now, we only handle splats for scalable vectors. 3466 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3467 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3468 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3469 3470 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3471 unsigned MaskNumElts = Mask.size(); 3472 3473 if (SrcNumElts == MaskNumElts) { 3474 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3475 return; 3476 } 3477 3478 // Normalize the shuffle vector since mask and vector length don't match. 3479 if (SrcNumElts < MaskNumElts) { 3480 // Mask is longer than the source vectors. We can use concatenate vector to 3481 // make the mask and vectors lengths match. 3482 3483 if (MaskNumElts % SrcNumElts == 0) { 3484 // Mask length is a multiple of the source vector length. 3485 // Check if the shuffle is some kind of concatenation of the input 3486 // vectors. 3487 unsigned NumConcat = MaskNumElts / SrcNumElts; 3488 bool IsConcat = true; 3489 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3490 for (unsigned i = 0; i != MaskNumElts; ++i) { 3491 int Idx = Mask[i]; 3492 if (Idx < 0) 3493 continue; 3494 // Ensure the indices in each SrcVT sized piece are sequential and that 3495 // the same source is used for the whole piece. 3496 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3497 (ConcatSrcs[i / SrcNumElts] >= 0 && 3498 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3499 IsConcat = false; 3500 break; 3501 } 3502 // Remember which source this index came from. 3503 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3504 } 3505 3506 // The shuffle is concatenating multiple vectors together. Just emit 3507 // a CONCAT_VECTORS operation. 3508 if (IsConcat) { 3509 SmallVector<SDValue, 8> ConcatOps; 3510 for (auto Src : ConcatSrcs) { 3511 if (Src < 0) 3512 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3513 else if (Src == 0) 3514 ConcatOps.push_back(Src1); 3515 else 3516 ConcatOps.push_back(Src2); 3517 } 3518 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3519 return; 3520 } 3521 } 3522 3523 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3524 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3525 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3526 PaddedMaskNumElts); 3527 3528 // Pad both vectors with undefs to make them the same length as the mask. 3529 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3530 3531 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3532 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3533 MOps1[0] = Src1; 3534 MOps2[0] = Src2; 3535 3536 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3537 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3538 3539 // Readjust mask for new input vector length. 3540 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3541 for (unsigned i = 0; i != MaskNumElts; ++i) { 3542 int Idx = Mask[i]; 3543 if (Idx >= (int)SrcNumElts) 3544 Idx -= SrcNumElts - PaddedMaskNumElts; 3545 MappedOps[i] = Idx; 3546 } 3547 3548 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3549 3550 // If the concatenated vector was padded, extract a subvector with the 3551 // correct number of elements. 3552 if (MaskNumElts != PaddedMaskNumElts) 3553 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3554 DAG.getVectorIdxConstant(0, DL)); 3555 3556 setValue(&I, Result); 3557 return; 3558 } 3559 3560 if (SrcNumElts > MaskNumElts) { 3561 // Analyze the access pattern of the vector to see if we can extract 3562 // two subvectors and do the shuffle. 3563 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3564 bool CanExtract = true; 3565 for (int Idx : Mask) { 3566 unsigned Input = 0; 3567 if (Idx < 0) 3568 continue; 3569 3570 if (Idx >= (int)SrcNumElts) { 3571 Input = 1; 3572 Idx -= SrcNumElts; 3573 } 3574 3575 // If all the indices come from the same MaskNumElts sized portion of 3576 // the sources we can use extract. Also make sure the extract wouldn't 3577 // extract past the end of the source. 3578 int NewStartIdx = alignDown(Idx, MaskNumElts); 3579 if (NewStartIdx + MaskNumElts > SrcNumElts || 3580 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3581 CanExtract = false; 3582 // Make sure we always update StartIdx as we use it to track if all 3583 // elements are undef. 3584 StartIdx[Input] = NewStartIdx; 3585 } 3586 3587 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3588 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3589 return; 3590 } 3591 if (CanExtract) { 3592 // Extract appropriate subvector and generate a vector shuffle 3593 for (unsigned Input = 0; Input < 2; ++Input) { 3594 SDValue &Src = Input == 0 ? Src1 : Src2; 3595 if (StartIdx[Input] < 0) 3596 Src = DAG.getUNDEF(VT); 3597 else { 3598 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3599 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3600 } 3601 } 3602 3603 // Calculate new mask. 3604 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3605 for (int &Idx : MappedOps) { 3606 if (Idx >= (int)SrcNumElts) 3607 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3608 else if (Idx >= 0) 3609 Idx -= StartIdx[0]; 3610 } 3611 3612 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3613 return; 3614 } 3615 } 3616 3617 // We can't use either concat vectors or extract subvectors so fall back to 3618 // replacing the shuffle with extract and build vector. 3619 // to insert and build vector. 3620 EVT EltVT = VT.getVectorElementType(); 3621 SmallVector<SDValue,8> Ops; 3622 for (int Idx : Mask) { 3623 SDValue Res; 3624 3625 if (Idx < 0) { 3626 Res = DAG.getUNDEF(EltVT); 3627 } else { 3628 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3629 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3630 3631 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3632 DAG.getVectorIdxConstant(Idx, DL)); 3633 } 3634 3635 Ops.push_back(Res); 3636 } 3637 3638 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3639 } 3640 3641 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3642 ArrayRef<unsigned> Indices; 3643 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3644 Indices = IV->getIndices(); 3645 else 3646 Indices = cast<ConstantExpr>(&I)->getIndices(); 3647 3648 const Value *Op0 = I.getOperand(0); 3649 const Value *Op1 = I.getOperand(1); 3650 Type *AggTy = I.getType(); 3651 Type *ValTy = Op1->getType(); 3652 bool IntoUndef = isa<UndefValue>(Op0); 3653 bool FromUndef = isa<UndefValue>(Op1); 3654 3655 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3656 3657 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3658 SmallVector<EVT, 4> AggValueVTs; 3659 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3660 SmallVector<EVT, 4> ValValueVTs; 3661 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3662 3663 unsigned NumAggValues = AggValueVTs.size(); 3664 unsigned NumValValues = ValValueVTs.size(); 3665 SmallVector<SDValue, 4> Values(NumAggValues); 3666 3667 // Ignore an insertvalue that produces an empty object 3668 if (!NumAggValues) { 3669 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3670 return; 3671 } 3672 3673 SDValue Agg = getValue(Op0); 3674 unsigned i = 0; 3675 // Copy the beginning value(s) from the original aggregate. 3676 for (; i != LinearIndex; ++i) 3677 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3678 SDValue(Agg.getNode(), Agg.getResNo() + i); 3679 // Copy values from the inserted value(s). 3680 if (NumValValues) { 3681 SDValue Val = getValue(Op1); 3682 for (; i != LinearIndex + NumValValues; ++i) 3683 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3684 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3685 } 3686 // Copy remaining value(s) from the original aggregate. 3687 for (; i != NumAggValues; ++i) 3688 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3689 SDValue(Agg.getNode(), Agg.getResNo() + i); 3690 3691 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3692 DAG.getVTList(AggValueVTs), Values)); 3693 } 3694 3695 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3696 ArrayRef<unsigned> Indices; 3697 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3698 Indices = EV->getIndices(); 3699 else 3700 Indices = cast<ConstantExpr>(&I)->getIndices(); 3701 3702 const Value *Op0 = I.getOperand(0); 3703 Type *AggTy = Op0->getType(); 3704 Type *ValTy = I.getType(); 3705 bool OutOfUndef = isa<UndefValue>(Op0); 3706 3707 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3708 3709 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3710 SmallVector<EVT, 4> ValValueVTs; 3711 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3712 3713 unsigned NumValValues = ValValueVTs.size(); 3714 3715 // Ignore a extractvalue that produces an empty object 3716 if (!NumValValues) { 3717 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3718 return; 3719 } 3720 3721 SmallVector<SDValue, 4> Values(NumValValues); 3722 3723 SDValue Agg = getValue(Op0); 3724 // Copy out the selected value(s). 3725 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3726 Values[i - LinearIndex] = 3727 OutOfUndef ? 3728 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3729 SDValue(Agg.getNode(), Agg.getResNo() + i); 3730 3731 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3732 DAG.getVTList(ValValueVTs), Values)); 3733 } 3734 3735 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3736 Value *Op0 = I.getOperand(0); 3737 // Note that the pointer operand may be a vector of pointers. Take the scalar 3738 // element which holds a pointer. 3739 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3740 SDValue N = getValue(Op0); 3741 SDLoc dl = getCurSDLoc(); 3742 auto &TLI = DAG.getTargetLoweringInfo(); 3743 3744 // Normalize Vector GEP - all scalar operands should be converted to the 3745 // splat vector. 3746 bool IsVectorGEP = I.getType()->isVectorTy(); 3747 ElementCount VectorElementCount = 3748 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3749 : ElementCount::getFixed(0); 3750 3751 if (IsVectorGEP && !N.getValueType().isVector()) { 3752 LLVMContext &Context = *DAG.getContext(); 3753 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3754 if (VectorElementCount.Scalable) 3755 N = DAG.getSplatVector(VT, dl, N); 3756 else 3757 N = DAG.getSplatBuildVector(VT, dl, N); 3758 } 3759 3760 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3761 GTI != E; ++GTI) { 3762 const Value *Idx = GTI.getOperand(); 3763 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3764 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3765 if (Field) { 3766 // N = N + Offset 3767 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3768 3769 // In an inbounds GEP with an offset that is nonnegative even when 3770 // interpreted as signed, assume there is no unsigned overflow. 3771 SDNodeFlags Flags; 3772 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3773 Flags.setNoUnsignedWrap(true); 3774 3775 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3776 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3777 } 3778 } else { 3779 // IdxSize is the width of the arithmetic according to IR semantics. 3780 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3781 // (and fix up the result later). 3782 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3783 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3784 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3785 // We intentionally mask away the high bits here; ElementSize may not 3786 // fit in IdxTy. 3787 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3788 bool ElementScalable = ElementSize.isScalable(); 3789 3790 // If this is a scalar constant or a splat vector of constants, 3791 // handle it quickly. 3792 const auto *C = dyn_cast<Constant>(Idx); 3793 if (C && isa<VectorType>(C->getType())) 3794 C = C->getSplatValue(); 3795 3796 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3797 if (CI && CI->isZero()) 3798 continue; 3799 if (CI && !ElementScalable) { 3800 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3801 LLVMContext &Context = *DAG.getContext(); 3802 SDValue OffsVal; 3803 if (IsVectorGEP) 3804 OffsVal = DAG.getConstant( 3805 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3806 else 3807 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3808 3809 // In an inbounds GEP with an offset that is nonnegative even when 3810 // interpreted as signed, assume there is no unsigned overflow. 3811 SDNodeFlags Flags; 3812 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3813 Flags.setNoUnsignedWrap(true); 3814 3815 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3816 3817 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3818 continue; 3819 } 3820 3821 // N = N + Idx * ElementMul; 3822 SDValue IdxN = getValue(Idx); 3823 3824 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3825 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3826 VectorElementCount); 3827 if (VectorElementCount.Scalable) 3828 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3829 else 3830 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3831 } 3832 3833 // If the index is smaller or larger than intptr_t, truncate or extend 3834 // it. 3835 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3836 3837 if (ElementScalable) { 3838 EVT VScaleTy = N.getValueType().getScalarType(); 3839 SDValue VScale = DAG.getNode( 3840 ISD::VSCALE, dl, VScaleTy, 3841 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3842 if (IsVectorGEP) 3843 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3844 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3845 } else { 3846 // If this is a multiply by a power of two, turn it into a shl 3847 // immediately. This is a very common case. 3848 if (ElementMul != 1) { 3849 if (ElementMul.isPowerOf2()) { 3850 unsigned Amt = ElementMul.logBase2(); 3851 IdxN = DAG.getNode(ISD::SHL, dl, 3852 N.getValueType(), IdxN, 3853 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3854 } else { 3855 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3856 IdxN.getValueType()); 3857 IdxN = DAG.getNode(ISD::MUL, dl, 3858 N.getValueType(), IdxN, Scale); 3859 } 3860 } 3861 } 3862 3863 N = DAG.getNode(ISD::ADD, dl, 3864 N.getValueType(), N, IdxN); 3865 } 3866 } 3867 3868 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3869 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3870 if (IsVectorGEP) { 3871 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3872 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3873 } 3874 3875 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3876 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3877 3878 setValue(&I, N); 3879 } 3880 3881 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3882 // If this is a fixed sized alloca in the entry block of the function, 3883 // allocate it statically on the stack. 3884 if (FuncInfo.StaticAllocaMap.count(&I)) 3885 return; // getValue will auto-populate this. 3886 3887 SDLoc dl = getCurSDLoc(); 3888 Type *Ty = I.getAllocatedType(); 3889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3890 auto &DL = DAG.getDataLayout(); 3891 uint64_t TySize = DL.getTypeAllocSize(Ty); 3892 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3893 3894 SDValue AllocSize = getValue(I.getArraySize()); 3895 3896 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3897 if (AllocSize.getValueType() != IntPtr) 3898 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3899 3900 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3901 AllocSize, 3902 DAG.getConstant(TySize, dl, IntPtr)); 3903 3904 // Handle alignment. If the requested alignment is less than or equal to 3905 // the stack alignment, ignore it. If the size is greater than or equal to 3906 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3907 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3908 if (*Alignment <= StackAlign) 3909 Alignment = None; 3910 3911 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3912 // Round the size of the allocation up to the stack alignment size 3913 // by add SA-1 to the size. This doesn't overflow because we're computing 3914 // an address inside an alloca. 3915 SDNodeFlags Flags; 3916 Flags.setNoUnsignedWrap(true); 3917 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3918 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3919 3920 // Mask out the low bits for alignment purposes. 3921 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3922 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3923 3924 SDValue Ops[] = { 3925 getRoot(), AllocSize, 3926 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3927 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3928 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3929 setValue(&I, DSA); 3930 DAG.setRoot(DSA.getValue(1)); 3931 3932 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3933 } 3934 3935 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3936 if (I.isAtomic()) 3937 return visitAtomicLoad(I); 3938 3939 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3940 const Value *SV = I.getOperand(0); 3941 if (TLI.supportSwiftError()) { 3942 // Swifterror values can come from either a function parameter with 3943 // swifterror attribute or an alloca with swifterror attribute. 3944 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3945 if (Arg->hasSwiftErrorAttr()) 3946 return visitLoadFromSwiftError(I); 3947 } 3948 3949 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3950 if (Alloca->isSwiftError()) 3951 return visitLoadFromSwiftError(I); 3952 } 3953 } 3954 3955 SDValue Ptr = getValue(SV); 3956 3957 Type *Ty = I.getType(); 3958 Align Alignment = I.getAlign(); 3959 3960 AAMDNodes AAInfo; 3961 I.getAAMetadata(AAInfo); 3962 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3963 3964 SmallVector<EVT, 4> ValueVTs, MemVTs; 3965 SmallVector<uint64_t, 4> Offsets; 3966 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3967 unsigned NumValues = ValueVTs.size(); 3968 if (NumValues == 0) 3969 return; 3970 3971 bool isVolatile = I.isVolatile(); 3972 3973 SDValue Root; 3974 bool ConstantMemory = false; 3975 if (isVolatile) 3976 // Serialize volatile loads with other side effects. 3977 Root = getRoot(); 3978 else if (NumValues > MaxParallelChains) 3979 Root = getMemoryRoot(); 3980 else if (AA && 3981 AA->pointsToConstantMemory(MemoryLocation( 3982 SV, 3983 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3984 AAInfo))) { 3985 // Do not serialize (non-volatile) loads of constant memory with anything. 3986 Root = DAG.getEntryNode(); 3987 ConstantMemory = true; 3988 } else { 3989 // Do not serialize non-volatile loads against each other. 3990 Root = DAG.getRoot(); 3991 } 3992 3993 SDLoc dl = getCurSDLoc(); 3994 3995 if (isVolatile) 3996 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3997 3998 // An aggregate load cannot wrap around the address space, so offsets to its 3999 // parts don't wrap either. 4000 SDNodeFlags Flags; 4001 Flags.setNoUnsignedWrap(true); 4002 4003 SmallVector<SDValue, 4> Values(NumValues); 4004 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4005 EVT PtrVT = Ptr.getValueType(); 4006 4007 MachineMemOperand::Flags MMOFlags 4008 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4009 4010 unsigned ChainI = 0; 4011 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4012 // Serializing loads here may result in excessive register pressure, and 4013 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4014 // could recover a bit by hoisting nodes upward in the chain by recognizing 4015 // they are side-effect free or do not alias. The optimizer should really 4016 // avoid this case by converting large object/array copies to llvm.memcpy 4017 // (MaxParallelChains should always remain as failsafe). 4018 if (ChainI == MaxParallelChains) { 4019 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4020 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4021 makeArrayRef(Chains.data(), ChainI)); 4022 Root = Chain; 4023 ChainI = 0; 4024 } 4025 SDValue A = DAG.getNode(ISD::ADD, dl, 4026 PtrVT, Ptr, 4027 DAG.getConstant(Offsets[i], dl, PtrVT), 4028 Flags); 4029 4030 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4031 MachinePointerInfo(SV, Offsets[i]), Alignment, 4032 MMOFlags, AAInfo, Ranges); 4033 Chains[ChainI] = L.getValue(1); 4034 4035 if (MemVTs[i] != ValueVTs[i]) 4036 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4037 4038 Values[i] = L; 4039 } 4040 4041 if (!ConstantMemory) { 4042 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4043 makeArrayRef(Chains.data(), ChainI)); 4044 if (isVolatile) 4045 DAG.setRoot(Chain); 4046 else 4047 PendingLoads.push_back(Chain); 4048 } 4049 4050 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4051 DAG.getVTList(ValueVTs), Values)); 4052 } 4053 4054 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4055 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4056 "call visitStoreToSwiftError when backend supports swifterror"); 4057 4058 SmallVector<EVT, 4> ValueVTs; 4059 SmallVector<uint64_t, 4> Offsets; 4060 const Value *SrcV = I.getOperand(0); 4061 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4062 SrcV->getType(), ValueVTs, &Offsets); 4063 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4064 "expect a single EVT for swifterror"); 4065 4066 SDValue Src = getValue(SrcV); 4067 // Create a virtual register, then update the virtual register. 4068 Register VReg = 4069 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4070 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4071 // Chain can be getRoot or getControlRoot. 4072 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4073 SDValue(Src.getNode(), Src.getResNo())); 4074 DAG.setRoot(CopyNode); 4075 } 4076 4077 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4078 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4079 "call visitLoadFromSwiftError when backend supports swifterror"); 4080 4081 assert(!I.isVolatile() && 4082 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4083 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4084 "Support volatile, non temporal, invariant for load_from_swift_error"); 4085 4086 const Value *SV = I.getOperand(0); 4087 Type *Ty = I.getType(); 4088 AAMDNodes AAInfo; 4089 I.getAAMetadata(AAInfo); 4090 assert( 4091 (!AA || 4092 !AA->pointsToConstantMemory(MemoryLocation( 4093 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4094 AAInfo))) && 4095 "load_from_swift_error should not be constant memory"); 4096 4097 SmallVector<EVT, 4> ValueVTs; 4098 SmallVector<uint64_t, 4> Offsets; 4099 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4100 ValueVTs, &Offsets); 4101 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4102 "expect a single EVT for swifterror"); 4103 4104 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4105 SDValue L = DAG.getCopyFromReg( 4106 getRoot(), getCurSDLoc(), 4107 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4108 4109 setValue(&I, L); 4110 } 4111 4112 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4113 if (I.isAtomic()) 4114 return visitAtomicStore(I); 4115 4116 const Value *SrcV = I.getOperand(0); 4117 const Value *PtrV = I.getOperand(1); 4118 4119 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4120 if (TLI.supportSwiftError()) { 4121 // Swifterror values can come from either a function parameter with 4122 // swifterror attribute or an alloca with swifterror attribute. 4123 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4124 if (Arg->hasSwiftErrorAttr()) 4125 return visitStoreToSwiftError(I); 4126 } 4127 4128 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4129 if (Alloca->isSwiftError()) 4130 return visitStoreToSwiftError(I); 4131 } 4132 } 4133 4134 SmallVector<EVT, 4> ValueVTs, MemVTs; 4135 SmallVector<uint64_t, 4> Offsets; 4136 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4137 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4138 unsigned NumValues = ValueVTs.size(); 4139 if (NumValues == 0) 4140 return; 4141 4142 // Get the lowered operands. Note that we do this after 4143 // checking if NumResults is zero, because with zero results 4144 // the operands won't have values in the map. 4145 SDValue Src = getValue(SrcV); 4146 SDValue Ptr = getValue(PtrV); 4147 4148 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4149 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4150 SDLoc dl = getCurSDLoc(); 4151 Align Alignment = I.getAlign(); 4152 AAMDNodes AAInfo; 4153 I.getAAMetadata(AAInfo); 4154 4155 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4156 4157 // An aggregate load cannot wrap around the address space, so offsets to its 4158 // parts don't wrap either. 4159 SDNodeFlags Flags; 4160 Flags.setNoUnsignedWrap(true); 4161 4162 unsigned ChainI = 0; 4163 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4164 // See visitLoad comments. 4165 if (ChainI == MaxParallelChains) { 4166 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4167 makeArrayRef(Chains.data(), ChainI)); 4168 Root = Chain; 4169 ChainI = 0; 4170 } 4171 SDValue Add = 4172 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4173 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4174 if (MemVTs[i] != ValueVTs[i]) 4175 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4176 SDValue St = 4177 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4178 Alignment, MMOFlags, AAInfo); 4179 Chains[ChainI] = St; 4180 } 4181 4182 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4183 makeArrayRef(Chains.data(), ChainI)); 4184 DAG.setRoot(StoreNode); 4185 } 4186 4187 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4188 bool IsCompressing) { 4189 SDLoc sdl = getCurSDLoc(); 4190 4191 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4192 MaybeAlign &Alignment) { 4193 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4194 Src0 = I.getArgOperand(0); 4195 Ptr = I.getArgOperand(1); 4196 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4197 Mask = I.getArgOperand(3); 4198 }; 4199 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4200 MaybeAlign &Alignment) { 4201 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4202 Src0 = I.getArgOperand(0); 4203 Ptr = I.getArgOperand(1); 4204 Mask = I.getArgOperand(2); 4205 Alignment = None; 4206 }; 4207 4208 Value *PtrOperand, *MaskOperand, *Src0Operand; 4209 MaybeAlign Alignment; 4210 if (IsCompressing) 4211 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4212 else 4213 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4214 4215 SDValue Ptr = getValue(PtrOperand); 4216 SDValue Src0 = getValue(Src0Operand); 4217 SDValue Mask = getValue(MaskOperand); 4218 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4219 4220 EVT VT = Src0.getValueType(); 4221 if (!Alignment) 4222 Alignment = DAG.getEVTAlign(VT); 4223 4224 AAMDNodes AAInfo; 4225 I.getAAMetadata(AAInfo); 4226 4227 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4228 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4229 // TODO: Make MachineMemOperands aware of scalable 4230 // vectors. 4231 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4232 SDValue StoreNode = 4233 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4234 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4235 DAG.setRoot(StoreNode); 4236 setValue(&I, StoreNode); 4237 } 4238 4239 // Get a uniform base for the Gather/Scatter intrinsic. 4240 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4241 // We try to represent it as a base pointer + vector of indices. 4242 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4243 // The first operand of the GEP may be a single pointer or a vector of pointers 4244 // Example: 4245 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4246 // or 4247 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4248 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4249 // 4250 // When the first GEP operand is a single pointer - it is the uniform base we 4251 // are looking for. If first operand of the GEP is a splat vector - we 4252 // extract the splat value and use it as a uniform base. 4253 // In all other cases the function returns 'false'. 4254 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4255 ISD::MemIndexType &IndexType, SDValue &Scale, 4256 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4257 SelectionDAG& DAG = SDB->DAG; 4258 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4259 const DataLayout &DL = DAG.getDataLayout(); 4260 4261 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4262 4263 // Handle splat constant pointer. 4264 if (auto *C = dyn_cast<Constant>(Ptr)) { 4265 C = C->getSplatValue(); 4266 if (!C) 4267 return false; 4268 4269 Base = SDB->getValue(C); 4270 4271 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4272 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4273 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4274 IndexType = ISD::SIGNED_SCALED; 4275 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4276 return true; 4277 } 4278 4279 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4280 if (!GEP || GEP->getParent() != CurBB) 4281 return false; 4282 4283 if (GEP->getNumOperands() != 2) 4284 return false; 4285 4286 const Value *BasePtr = GEP->getPointerOperand(); 4287 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4288 4289 // Make sure the base is scalar and the index is a vector. 4290 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4291 return false; 4292 4293 Base = SDB->getValue(BasePtr); 4294 Index = SDB->getValue(IndexVal); 4295 IndexType = ISD::SIGNED_SCALED; 4296 Scale = DAG.getTargetConstant( 4297 DL.getTypeAllocSize(GEP->getResultElementType()), 4298 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4299 return true; 4300 } 4301 4302 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4303 SDLoc sdl = getCurSDLoc(); 4304 4305 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4306 const Value *Ptr = I.getArgOperand(1); 4307 SDValue Src0 = getValue(I.getArgOperand(0)); 4308 SDValue Mask = getValue(I.getArgOperand(3)); 4309 EVT VT = Src0.getValueType(); 4310 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4311 ->getMaybeAlignValue() 4312 .getValueOr(DAG.getEVTAlign(VT)); 4313 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4314 4315 AAMDNodes AAInfo; 4316 I.getAAMetadata(AAInfo); 4317 4318 SDValue Base; 4319 SDValue Index; 4320 ISD::MemIndexType IndexType; 4321 SDValue Scale; 4322 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4323 I.getParent()); 4324 4325 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4326 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4327 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4328 // TODO: Make MachineMemOperands aware of scalable 4329 // vectors. 4330 MemoryLocation::UnknownSize, Alignment, AAInfo); 4331 if (!UniformBase) { 4332 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4333 Index = getValue(Ptr); 4334 IndexType = ISD::SIGNED_SCALED; 4335 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4336 } 4337 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4338 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4339 Ops, MMO, IndexType); 4340 DAG.setRoot(Scatter); 4341 setValue(&I, Scatter); 4342 } 4343 4344 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4345 SDLoc sdl = getCurSDLoc(); 4346 4347 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4348 MaybeAlign &Alignment) { 4349 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4350 Ptr = I.getArgOperand(0); 4351 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4352 Mask = I.getArgOperand(2); 4353 Src0 = I.getArgOperand(3); 4354 }; 4355 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4356 MaybeAlign &Alignment) { 4357 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4358 Ptr = I.getArgOperand(0); 4359 Alignment = None; 4360 Mask = I.getArgOperand(1); 4361 Src0 = I.getArgOperand(2); 4362 }; 4363 4364 Value *PtrOperand, *MaskOperand, *Src0Operand; 4365 MaybeAlign Alignment; 4366 if (IsExpanding) 4367 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4368 else 4369 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4370 4371 SDValue Ptr = getValue(PtrOperand); 4372 SDValue Src0 = getValue(Src0Operand); 4373 SDValue Mask = getValue(MaskOperand); 4374 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4375 4376 EVT VT = Src0.getValueType(); 4377 if (!Alignment) 4378 Alignment = DAG.getEVTAlign(VT); 4379 4380 AAMDNodes AAInfo; 4381 I.getAAMetadata(AAInfo); 4382 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4383 4384 // Do not serialize masked loads of constant memory with anything. 4385 MemoryLocation ML; 4386 if (VT.isScalableVector()) 4387 ML = MemoryLocation(PtrOperand); 4388 else 4389 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4390 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4391 AAInfo); 4392 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4393 4394 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4395 4396 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4397 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4398 // TODO: Make MachineMemOperands aware of scalable 4399 // vectors. 4400 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4401 4402 SDValue Load = 4403 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4404 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4405 if (AddToChain) 4406 PendingLoads.push_back(Load.getValue(1)); 4407 setValue(&I, Load); 4408 } 4409 4410 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4411 SDLoc sdl = getCurSDLoc(); 4412 4413 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4414 const Value *Ptr = I.getArgOperand(0); 4415 SDValue Src0 = getValue(I.getArgOperand(3)); 4416 SDValue Mask = getValue(I.getArgOperand(2)); 4417 4418 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4419 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4420 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4421 ->getMaybeAlignValue() 4422 .getValueOr(DAG.getEVTAlign(VT)); 4423 4424 AAMDNodes AAInfo; 4425 I.getAAMetadata(AAInfo); 4426 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4427 4428 SDValue Root = DAG.getRoot(); 4429 SDValue Base; 4430 SDValue Index; 4431 ISD::MemIndexType IndexType; 4432 SDValue Scale; 4433 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4434 I.getParent()); 4435 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4436 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4437 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4438 // TODO: Make MachineMemOperands aware of scalable 4439 // vectors. 4440 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4441 4442 if (!UniformBase) { 4443 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4444 Index = getValue(Ptr); 4445 IndexType = ISD::SIGNED_SCALED; 4446 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4447 } 4448 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4449 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4450 Ops, MMO, IndexType); 4451 4452 PendingLoads.push_back(Gather.getValue(1)); 4453 setValue(&I, Gather); 4454 } 4455 4456 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4457 SDLoc dl = getCurSDLoc(); 4458 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4459 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4460 SyncScope::ID SSID = I.getSyncScopeID(); 4461 4462 SDValue InChain = getRoot(); 4463 4464 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4465 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4466 4467 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4468 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4469 4470 MachineFunction &MF = DAG.getMachineFunction(); 4471 MachineMemOperand *MMO = MF.getMachineMemOperand( 4472 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4473 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4474 FailureOrdering); 4475 4476 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4477 dl, MemVT, VTs, InChain, 4478 getValue(I.getPointerOperand()), 4479 getValue(I.getCompareOperand()), 4480 getValue(I.getNewValOperand()), MMO); 4481 4482 SDValue OutChain = L.getValue(2); 4483 4484 setValue(&I, L); 4485 DAG.setRoot(OutChain); 4486 } 4487 4488 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4489 SDLoc dl = getCurSDLoc(); 4490 ISD::NodeType NT; 4491 switch (I.getOperation()) { 4492 default: llvm_unreachable("Unknown atomicrmw operation"); 4493 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4494 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4495 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4496 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4497 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4498 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4499 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4500 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4501 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4502 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4503 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4504 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4505 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4506 } 4507 AtomicOrdering Ordering = I.getOrdering(); 4508 SyncScope::ID SSID = I.getSyncScopeID(); 4509 4510 SDValue InChain = getRoot(); 4511 4512 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4513 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4514 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4515 4516 MachineFunction &MF = DAG.getMachineFunction(); 4517 MachineMemOperand *MMO = MF.getMachineMemOperand( 4518 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4519 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4520 4521 SDValue L = 4522 DAG.getAtomic(NT, dl, MemVT, InChain, 4523 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4524 MMO); 4525 4526 SDValue OutChain = L.getValue(1); 4527 4528 setValue(&I, L); 4529 DAG.setRoot(OutChain); 4530 } 4531 4532 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4533 SDLoc dl = getCurSDLoc(); 4534 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4535 SDValue Ops[3]; 4536 Ops[0] = getRoot(); 4537 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4538 TLI.getFenceOperandTy(DAG.getDataLayout())); 4539 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4540 TLI.getFenceOperandTy(DAG.getDataLayout())); 4541 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4542 } 4543 4544 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4545 SDLoc dl = getCurSDLoc(); 4546 AtomicOrdering Order = I.getOrdering(); 4547 SyncScope::ID SSID = I.getSyncScopeID(); 4548 4549 SDValue InChain = getRoot(); 4550 4551 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4552 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4553 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4554 4555 if (!TLI.supportsUnalignedAtomics() && 4556 I.getAlignment() < MemVT.getSizeInBits() / 8) 4557 report_fatal_error("Cannot generate unaligned atomic load"); 4558 4559 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4560 4561 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4562 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4563 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4564 4565 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4566 4567 SDValue Ptr = getValue(I.getPointerOperand()); 4568 4569 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4570 // TODO: Once this is better exercised by tests, it should be merged with 4571 // the normal path for loads to prevent future divergence. 4572 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4573 if (MemVT != VT) 4574 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4575 4576 setValue(&I, L); 4577 SDValue OutChain = L.getValue(1); 4578 if (!I.isUnordered()) 4579 DAG.setRoot(OutChain); 4580 else 4581 PendingLoads.push_back(OutChain); 4582 return; 4583 } 4584 4585 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4586 Ptr, MMO); 4587 4588 SDValue OutChain = L.getValue(1); 4589 if (MemVT != VT) 4590 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4591 4592 setValue(&I, L); 4593 DAG.setRoot(OutChain); 4594 } 4595 4596 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4597 SDLoc dl = getCurSDLoc(); 4598 4599 AtomicOrdering Ordering = I.getOrdering(); 4600 SyncScope::ID SSID = I.getSyncScopeID(); 4601 4602 SDValue InChain = getRoot(); 4603 4604 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4605 EVT MemVT = 4606 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4607 4608 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4609 report_fatal_error("Cannot generate unaligned atomic store"); 4610 4611 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4612 4613 MachineFunction &MF = DAG.getMachineFunction(); 4614 MachineMemOperand *MMO = MF.getMachineMemOperand( 4615 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4616 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4617 4618 SDValue Val = getValue(I.getValueOperand()); 4619 if (Val.getValueType() != MemVT) 4620 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4621 SDValue Ptr = getValue(I.getPointerOperand()); 4622 4623 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4624 // TODO: Once this is better exercised by tests, it should be merged with 4625 // the normal path for stores to prevent future divergence. 4626 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4627 DAG.setRoot(S); 4628 return; 4629 } 4630 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4631 Ptr, Val, MMO); 4632 4633 4634 DAG.setRoot(OutChain); 4635 } 4636 4637 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4638 /// node. 4639 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4640 unsigned Intrinsic) { 4641 // Ignore the callsite's attributes. A specific call site may be marked with 4642 // readnone, but the lowering code will expect the chain based on the 4643 // definition. 4644 const Function *F = I.getCalledFunction(); 4645 bool HasChain = !F->doesNotAccessMemory(); 4646 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4647 4648 // Build the operand list. 4649 SmallVector<SDValue, 8> Ops; 4650 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4651 if (OnlyLoad) { 4652 // We don't need to serialize loads against other loads. 4653 Ops.push_back(DAG.getRoot()); 4654 } else { 4655 Ops.push_back(getRoot()); 4656 } 4657 } 4658 4659 // Info is set by getTgtMemInstrinsic 4660 TargetLowering::IntrinsicInfo Info; 4661 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4662 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4663 DAG.getMachineFunction(), 4664 Intrinsic); 4665 4666 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4667 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4668 Info.opc == ISD::INTRINSIC_W_CHAIN) 4669 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4670 TLI.getPointerTy(DAG.getDataLayout()))); 4671 4672 // Add all operands of the call to the operand list. 4673 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4674 const Value *Arg = I.getArgOperand(i); 4675 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4676 Ops.push_back(getValue(Arg)); 4677 continue; 4678 } 4679 4680 // Use TargetConstant instead of a regular constant for immarg. 4681 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4682 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4683 assert(CI->getBitWidth() <= 64 && 4684 "large intrinsic immediates not handled"); 4685 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4686 } else { 4687 Ops.push_back( 4688 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4689 } 4690 } 4691 4692 SmallVector<EVT, 4> ValueVTs; 4693 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4694 4695 if (HasChain) 4696 ValueVTs.push_back(MVT::Other); 4697 4698 SDVTList VTs = DAG.getVTList(ValueVTs); 4699 4700 // Create the node. 4701 SDValue Result; 4702 if (IsTgtIntrinsic) { 4703 // This is target intrinsic that touches memory 4704 AAMDNodes AAInfo; 4705 I.getAAMetadata(AAInfo); 4706 Result = 4707 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4708 MachinePointerInfo(Info.ptrVal, Info.offset), 4709 Info.align, Info.flags, Info.size, AAInfo); 4710 } else if (!HasChain) { 4711 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4712 } else if (!I.getType()->isVoidTy()) { 4713 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4714 } else { 4715 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4716 } 4717 4718 if (HasChain) { 4719 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4720 if (OnlyLoad) 4721 PendingLoads.push_back(Chain); 4722 else 4723 DAG.setRoot(Chain); 4724 } 4725 4726 if (!I.getType()->isVoidTy()) { 4727 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4728 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4729 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4730 } else 4731 Result = lowerRangeToAssertZExt(DAG, I, Result); 4732 4733 MaybeAlign Alignment = I.getRetAlign(); 4734 if (!Alignment) 4735 Alignment = F->getAttributes().getRetAlignment(); 4736 // Insert `assertalign` node if there's an alignment. 4737 if (InsertAssertAlign && Alignment) { 4738 Result = 4739 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4740 } 4741 4742 setValue(&I, Result); 4743 } 4744 } 4745 4746 /// GetSignificand - Get the significand and build it into a floating-point 4747 /// number with exponent of 1: 4748 /// 4749 /// Op = (Op & 0x007fffff) | 0x3f800000; 4750 /// 4751 /// where Op is the hexadecimal representation of floating point value. 4752 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4753 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4754 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4755 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4756 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4757 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4758 } 4759 4760 /// GetExponent - Get the exponent: 4761 /// 4762 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4763 /// 4764 /// where Op is the hexadecimal representation of floating point value. 4765 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4766 const TargetLowering &TLI, const SDLoc &dl) { 4767 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4768 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4769 SDValue t1 = DAG.getNode( 4770 ISD::SRL, dl, MVT::i32, t0, 4771 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4772 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4773 DAG.getConstant(127, dl, MVT::i32)); 4774 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4775 } 4776 4777 /// getF32Constant - Get 32-bit floating point constant. 4778 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4779 const SDLoc &dl) { 4780 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4781 MVT::f32); 4782 } 4783 4784 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4785 SelectionDAG &DAG) { 4786 // TODO: What fast-math-flags should be set on the floating-point nodes? 4787 4788 // IntegerPartOfX = ((int32_t)(t0); 4789 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4790 4791 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4792 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4793 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4794 4795 // IntegerPartOfX <<= 23; 4796 IntegerPartOfX = DAG.getNode( 4797 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4798 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4799 DAG.getDataLayout()))); 4800 4801 SDValue TwoToFractionalPartOfX; 4802 if (LimitFloatPrecision <= 6) { 4803 // For floating-point precision of 6: 4804 // 4805 // TwoToFractionalPartOfX = 4806 // 0.997535578f + 4807 // (0.735607626f + 0.252464424f * x) * x; 4808 // 4809 // error 0.0144103317, which is 6 bits 4810 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4811 getF32Constant(DAG, 0x3e814304, dl)); 4812 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4813 getF32Constant(DAG, 0x3f3c50c8, dl)); 4814 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4815 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4816 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4817 } else if (LimitFloatPrecision <= 12) { 4818 // For floating-point precision of 12: 4819 // 4820 // TwoToFractionalPartOfX = 4821 // 0.999892986f + 4822 // (0.696457318f + 4823 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4824 // 4825 // error 0.000107046256, which is 13 to 14 bits 4826 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4827 getF32Constant(DAG, 0x3da235e3, dl)); 4828 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4829 getF32Constant(DAG, 0x3e65b8f3, dl)); 4830 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4831 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4832 getF32Constant(DAG, 0x3f324b07, dl)); 4833 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4834 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4835 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4836 } else { // LimitFloatPrecision <= 18 4837 // For floating-point precision of 18: 4838 // 4839 // TwoToFractionalPartOfX = 4840 // 0.999999982f + 4841 // (0.693148872f + 4842 // (0.240227044f + 4843 // (0.554906021e-1f + 4844 // (0.961591928e-2f + 4845 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4846 // error 2.47208000*10^(-7), which is better than 18 bits 4847 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4848 getF32Constant(DAG, 0x3924b03e, dl)); 4849 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4850 getF32Constant(DAG, 0x3ab24b87, dl)); 4851 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4852 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4853 getF32Constant(DAG, 0x3c1d8c17, dl)); 4854 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4855 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4856 getF32Constant(DAG, 0x3d634a1d, dl)); 4857 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4858 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4859 getF32Constant(DAG, 0x3e75fe14, dl)); 4860 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4861 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4862 getF32Constant(DAG, 0x3f317234, dl)); 4863 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4864 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4865 getF32Constant(DAG, 0x3f800000, dl)); 4866 } 4867 4868 // Add the exponent into the result in integer domain. 4869 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4870 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4871 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4872 } 4873 4874 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4875 /// limited-precision mode. 4876 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4877 const TargetLowering &TLI) { 4878 if (Op.getValueType() == MVT::f32 && 4879 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4880 4881 // Put the exponent in the right bit position for later addition to the 4882 // final result: 4883 // 4884 // t0 = Op * log2(e) 4885 4886 // TODO: What fast-math-flags should be set here? 4887 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4888 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4889 return getLimitedPrecisionExp2(t0, dl, DAG); 4890 } 4891 4892 // No special expansion. 4893 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4894 } 4895 4896 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4897 /// limited-precision mode. 4898 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4899 const TargetLowering &TLI) { 4900 // TODO: What fast-math-flags should be set on the floating-point nodes? 4901 4902 if (Op.getValueType() == MVT::f32 && 4903 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4904 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4905 4906 // Scale the exponent by log(2). 4907 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4908 SDValue LogOfExponent = 4909 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4910 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4911 4912 // Get the significand and build it into a floating-point number with 4913 // exponent of 1. 4914 SDValue X = GetSignificand(DAG, Op1, dl); 4915 4916 SDValue LogOfMantissa; 4917 if (LimitFloatPrecision <= 6) { 4918 // For floating-point precision of 6: 4919 // 4920 // LogofMantissa = 4921 // -1.1609546f + 4922 // (1.4034025f - 0.23903021f * x) * x; 4923 // 4924 // error 0.0034276066, which is better than 8 bits 4925 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4926 getF32Constant(DAG, 0xbe74c456, dl)); 4927 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4928 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4929 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4930 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4931 getF32Constant(DAG, 0x3f949a29, dl)); 4932 } else if (LimitFloatPrecision <= 12) { 4933 // For floating-point precision of 12: 4934 // 4935 // LogOfMantissa = 4936 // -1.7417939f + 4937 // (2.8212026f + 4938 // (-1.4699568f + 4939 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4940 // 4941 // error 0.000061011436, which is 14 bits 4942 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4943 getF32Constant(DAG, 0xbd67b6d6, dl)); 4944 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4945 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4946 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4947 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4948 getF32Constant(DAG, 0x3fbc278b, dl)); 4949 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4950 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4951 getF32Constant(DAG, 0x40348e95, dl)); 4952 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4953 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4954 getF32Constant(DAG, 0x3fdef31a, dl)); 4955 } else { // LimitFloatPrecision <= 18 4956 // For floating-point precision of 18: 4957 // 4958 // LogOfMantissa = 4959 // -2.1072184f + 4960 // (4.2372794f + 4961 // (-3.7029485f + 4962 // (2.2781945f + 4963 // (-0.87823314f + 4964 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4965 // 4966 // error 0.0000023660568, which is better than 18 bits 4967 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4968 getF32Constant(DAG, 0xbc91e5ac, dl)); 4969 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4970 getF32Constant(DAG, 0x3e4350aa, dl)); 4971 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4972 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4973 getF32Constant(DAG, 0x3f60d3e3, dl)); 4974 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4975 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4976 getF32Constant(DAG, 0x4011cdf0, dl)); 4977 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4978 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4979 getF32Constant(DAG, 0x406cfd1c, dl)); 4980 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4981 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4982 getF32Constant(DAG, 0x408797cb, dl)); 4983 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4984 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4985 getF32Constant(DAG, 0x4006dcab, dl)); 4986 } 4987 4988 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4989 } 4990 4991 // No special expansion. 4992 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4993 } 4994 4995 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4996 /// limited-precision mode. 4997 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4998 const TargetLowering &TLI) { 4999 // TODO: What fast-math-flags should be set on the floating-point nodes? 5000 5001 if (Op.getValueType() == MVT::f32 && 5002 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5003 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5004 5005 // Get the exponent. 5006 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5007 5008 // Get the significand and build it into a floating-point number with 5009 // exponent of 1. 5010 SDValue X = GetSignificand(DAG, Op1, dl); 5011 5012 // Different possible minimax approximations of significand in 5013 // floating-point for various degrees of accuracy over [1,2]. 5014 SDValue Log2ofMantissa; 5015 if (LimitFloatPrecision <= 6) { 5016 // For floating-point precision of 6: 5017 // 5018 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5019 // 5020 // error 0.0049451742, which is more than 7 bits 5021 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5022 getF32Constant(DAG, 0xbeb08fe0, dl)); 5023 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5024 getF32Constant(DAG, 0x40019463, dl)); 5025 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5026 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5027 getF32Constant(DAG, 0x3fd6633d, dl)); 5028 } else if (LimitFloatPrecision <= 12) { 5029 // For floating-point precision of 12: 5030 // 5031 // Log2ofMantissa = 5032 // -2.51285454f + 5033 // (4.07009056f + 5034 // (-2.12067489f + 5035 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5036 // 5037 // error 0.0000876136000, which is better than 13 bits 5038 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5039 getF32Constant(DAG, 0xbda7262e, dl)); 5040 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5041 getF32Constant(DAG, 0x3f25280b, dl)); 5042 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5043 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5044 getF32Constant(DAG, 0x4007b923, dl)); 5045 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5046 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5047 getF32Constant(DAG, 0x40823e2f, dl)); 5048 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5049 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5050 getF32Constant(DAG, 0x4020d29c, dl)); 5051 } else { // LimitFloatPrecision <= 18 5052 // For floating-point precision of 18: 5053 // 5054 // Log2ofMantissa = 5055 // -3.0400495f + 5056 // (6.1129976f + 5057 // (-5.3420409f + 5058 // (3.2865683f + 5059 // (-1.2669343f + 5060 // (0.27515199f - 5061 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5062 // 5063 // error 0.0000018516, which is better than 18 bits 5064 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5065 getF32Constant(DAG, 0xbcd2769e, dl)); 5066 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5067 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5068 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5069 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5070 getF32Constant(DAG, 0x3fa22ae7, dl)); 5071 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5072 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5073 getF32Constant(DAG, 0x40525723, dl)); 5074 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5075 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5076 getF32Constant(DAG, 0x40aaf200, dl)); 5077 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5078 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5079 getF32Constant(DAG, 0x40c39dad, dl)); 5080 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5081 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5082 getF32Constant(DAG, 0x4042902c, dl)); 5083 } 5084 5085 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5086 } 5087 5088 // No special expansion. 5089 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5090 } 5091 5092 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5093 /// limited-precision mode. 5094 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5095 const TargetLowering &TLI) { 5096 // TODO: What fast-math-flags should be set on the floating-point nodes? 5097 5098 if (Op.getValueType() == MVT::f32 && 5099 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5100 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5101 5102 // Scale the exponent by log10(2) [0.30102999f]. 5103 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5104 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5105 getF32Constant(DAG, 0x3e9a209a, dl)); 5106 5107 // Get the significand and build it into a floating-point number with 5108 // exponent of 1. 5109 SDValue X = GetSignificand(DAG, Op1, dl); 5110 5111 SDValue Log10ofMantissa; 5112 if (LimitFloatPrecision <= 6) { 5113 // For floating-point precision of 6: 5114 // 5115 // Log10ofMantissa = 5116 // -0.50419619f + 5117 // (0.60948995f - 0.10380950f * x) * x; 5118 // 5119 // error 0.0014886165, which is 6 bits 5120 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5121 getF32Constant(DAG, 0xbdd49a13, dl)); 5122 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5123 getF32Constant(DAG, 0x3f1c0789, dl)); 5124 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5125 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5126 getF32Constant(DAG, 0x3f011300, dl)); 5127 } else if (LimitFloatPrecision <= 12) { 5128 // For floating-point precision of 12: 5129 // 5130 // Log10ofMantissa = 5131 // -0.64831180f + 5132 // (0.91751397f + 5133 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5134 // 5135 // error 0.00019228036, which is better than 12 bits 5136 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5137 getF32Constant(DAG, 0x3d431f31, dl)); 5138 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5139 getF32Constant(DAG, 0x3ea21fb2, dl)); 5140 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5141 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5142 getF32Constant(DAG, 0x3f6ae232, dl)); 5143 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5144 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5145 getF32Constant(DAG, 0x3f25f7c3, dl)); 5146 } else { // LimitFloatPrecision <= 18 5147 // For floating-point precision of 18: 5148 // 5149 // Log10ofMantissa = 5150 // -0.84299375f + 5151 // (1.5327582f + 5152 // (-1.0688956f + 5153 // (0.49102474f + 5154 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5155 // 5156 // error 0.0000037995730, which is better than 18 bits 5157 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5158 getF32Constant(DAG, 0x3c5d51ce, dl)); 5159 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5160 getF32Constant(DAG, 0x3e00685a, dl)); 5161 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5162 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5163 getF32Constant(DAG, 0x3efb6798, dl)); 5164 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5165 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5166 getF32Constant(DAG, 0x3f88d192, dl)); 5167 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5168 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5169 getF32Constant(DAG, 0x3fc4316c, dl)); 5170 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5171 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5172 getF32Constant(DAG, 0x3f57ce70, dl)); 5173 } 5174 5175 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5176 } 5177 5178 // No special expansion. 5179 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5180 } 5181 5182 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5183 /// limited-precision mode. 5184 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5185 const TargetLowering &TLI) { 5186 if (Op.getValueType() == MVT::f32 && 5187 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5188 return getLimitedPrecisionExp2(Op, dl, DAG); 5189 5190 // No special expansion. 5191 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5192 } 5193 5194 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5195 /// limited-precision mode with x == 10.0f. 5196 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5197 SelectionDAG &DAG, const TargetLowering &TLI) { 5198 bool IsExp10 = false; 5199 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5200 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5201 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5202 APFloat Ten(10.0f); 5203 IsExp10 = LHSC->isExactlyValue(Ten); 5204 } 5205 } 5206 5207 // TODO: What fast-math-flags should be set on the FMUL node? 5208 if (IsExp10) { 5209 // Put the exponent in the right bit position for later addition to the 5210 // final result: 5211 // 5212 // #define LOG2OF10 3.3219281f 5213 // t0 = Op * LOG2OF10; 5214 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5215 getF32Constant(DAG, 0x40549a78, dl)); 5216 return getLimitedPrecisionExp2(t0, dl, DAG); 5217 } 5218 5219 // No special expansion. 5220 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5221 } 5222 5223 /// ExpandPowI - Expand a llvm.powi intrinsic. 5224 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5225 SelectionDAG &DAG) { 5226 // If RHS is a constant, we can expand this out to a multiplication tree, 5227 // otherwise we end up lowering to a call to __powidf2 (for example). When 5228 // optimizing for size, we only want to do this if the expansion would produce 5229 // a small number of multiplies, otherwise we do the full expansion. 5230 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5231 // Get the exponent as a positive value. 5232 unsigned Val = RHSC->getSExtValue(); 5233 if ((int)Val < 0) Val = -Val; 5234 5235 // powi(x, 0) -> 1.0 5236 if (Val == 0) 5237 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5238 5239 bool OptForSize = DAG.shouldOptForSize(); 5240 if (!OptForSize || 5241 // If optimizing for size, don't insert too many multiplies. 5242 // This inserts up to 5 multiplies. 5243 countPopulation(Val) + Log2_32(Val) < 7) { 5244 // We use the simple binary decomposition method to generate the multiply 5245 // sequence. There are more optimal ways to do this (for example, 5246 // powi(x,15) generates one more multiply than it should), but this has 5247 // the benefit of being both really simple and much better than a libcall. 5248 SDValue Res; // Logically starts equal to 1.0 5249 SDValue CurSquare = LHS; 5250 // TODO: Intrinsics should have fast-math-flags that propagate to these 5251 // nodes. 5252 while (Val) { 5253 if (Val & 1) { 5254 if (Res.getNode()) 5255 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5256 else 5257 Res = CurSquare; // 1.0*CurSquare. 5258 } 5259 5260 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5261 CurSquare, CurSquare); 5262 Val >>= 1; 5263 } 5264 5265 // If the original was negative, invert the result, producing 1/(x*x*x). 5266 if (RHSC->getSExtValue() < 0) 5267 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5268 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5269 return Res; 5270 } 5271 } 5272 5273 // Otherwise, expand to a libcall. 5274 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5275 } 5276 5277 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5278 SDValue LHS, SDValue RHS, SDValue Scale, 5279 SelectionDAG &DAG, const TargetLowering &TLI) { 5280 EVT VT = LHS.getValueType(); 5281 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5282 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5283 LLVMContext &Ctx = *DAG.getContext(); 5284 5285 // If the type is legal but the operation isn't, this node might survive all 5286 // the way to operation legalization. If we end up there and we do not have 5287 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5288 // node. 5289 5290 // Coax the legalizer into expanding the node during type legalization instead 5291 // by bumping the size by one bit. This will force it to Promote, enabling the 5292 // early expansion and avoiding the need to expand later. 5293 5294 // We don't have to do this if Scale is 0; that can always be expanded, unless 5295 // it's a saturating signed operation. Those can experience true integer 5296 // division overflow, a case which we must avoid. 5297 5298 // FIXME: We wouldn't have to do this (or any of the early 5299 // expansion/promotion) if it was possible to expand a libcall of an 5300 // illegal type during operation legalization. But it's not, so things 5301 // get a bit hacky. 5302 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5303 if ((ScaleInt > 0 || (Saturating && Signed)) && 5304 (TLI.isTypeLegal(VT) || 5305 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5306 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5307 Opcode, VT, ScaleInt); 5308 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5309 EVT PromVT; 5310 if (VT.isScalarInteger()) 5311 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5312 else if (VT.isVector()) { 5313 PromVT = VT.getVectorElementType(); 5314 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5315 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5316 } else 5317 llvm_unreachable("Wrong VT for DIVFIX?"); 5318 if (Signed) { 5319 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5320 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5321 } else { 5322 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5323 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5324 } 5325 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5326 // For saturating operations, we need to shift up the LHS to get the 5327 // proper saturation width, and then shift down again afterwards. 5328 if (Saturating) 5329 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5330 DAG.getConstant(1, DL, ShiftTy)); 5331 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5332 if (Saturating) 5333 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5334 DAG.getConstant(1, DL, ShiftTy)); 5335 return DAG.getZExtOrTrunc(Res, DL, VT); 5336 } 5337 } 5338 5339 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5340 } 5341 5342 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5343 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5344 static void 5345 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5346 const SDValue &N) { 5347 switch (N.getOpcode()) { 5348 case ISD::CopyFromReg: { 5349 SDValue Op = N.getOperand(1); 5350 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5351 Op.getValueType().getSizeInBits()); 5352 return; 5353 } 5354 case ISD::BITCAST: 5355 case ISD::AssertZext: 5356 case ISD::AssertSext: 5357 case ISD::TRUNCATE: 5358 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5359 return; 5360 case ISD::BUILD_PAIR: 5361 case ISD::BUILD_VECTOR: 5362 case ISD::CONCAT_VECTORS: 5363 for (SDValue Op : N->op_values()) 5364 getUnderlyingArgRegs(Regs, Op); 5365 return; 5366 default: 5367 return; 5368 } 5369 } 5370 5371 /// If the DbgValueInst is a dbg_value of a function argument, create the 5372 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5373 /// instruction selection, they will be inserted to the entry BB. 5374 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5375 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5376 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5377 const Argument *Arg = dyn_cast<Argument>(V); 5378 if (!Arg) 5379 return false; 5380 5381 if (!IsDbgDeclare) { 5382 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5383 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5384 // the entry block. 5385 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5386 if (!IsInEntryBlock) 5387 return false; 5388 5389 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5390 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5391 // variable that also is a param. 5392 // 5393 // Although, if we are at the top of the entry block already, we can still 5394 // emit using ArgDbgValue. This might catch some situations when the 5395 // dbg.value refers to an argument that isn't used in the entry block, so 5396 // any CopyToReg node would be optimized out and the only way to express 5397 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5398 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5399 // we should only emit as ArgDbgValue if the Variable is an argument to the 5400 // current function, and the dbg.value intrinsic is found in the entry 5401 // block. 5402 bool VariableIsFunctionInputArg = Variable->isParameter() && 5403 !DL->getInlinedAt(); 5404 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5405 if (!IsInPrologue && !VariableIsFunctionInputArg) 5406 return false; 5407 5408 // Here we assume that a function argument on IR level only can be used to 5409 // describe one input parameter on source level. If we for example have 5410 // source code like this 5411 // 5412 // struct A { long x, y; }; 5413 // void foo(struct A a, long b) { 5414 // ... 5415 // b = a.x; 5416 // ... 5417 // } 5418 // 5419 // and IR like this 5420 // 5421 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5422 // entry: 5423 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5424 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5425 // call void @llvm.dbg.value(metadata i32 %b, "b", 5426 // ... 5427 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5428 // ... 5429 // 5430 // then the last dbg.value is describing a parameter "b" using a value that 5431 // is an argument. But since we already has used %a1 to describe a parameter 5432 // we should not handle that last dbg.value here (that would result in an 5433 // incorrect hoisting of the DBG_VALUE to the function entry). 5434 // Notice that we allow one dbg.value per IR level argument, to accommodate 5435 // for the situation with fragments above. 5436 if (VariableIsFunctionInputArg) { 5437 unsigned ArgNo = Arg->getArgNo(); 5438 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5439 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5440 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5441 return false; 5442 FuncInfo.DescribedArgs.set(ArgNo); 5443 } 5444 } 5445 5446 MachineFunction &MF = DAG.getMachineFunction(); 5447 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5448 5449 bool IsIndirect = false; 5450 Optional<MachineOperand> Op; 5451 // Some arguments' frame index is recorded during argument lowering. 5452 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5453 if (FI != std::numeric_limits<int>::max()) 5454 Op = MachineOperand::CreateFI(FI); 5455 5456 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5457 if (!Op && N.getNode()) { 5458 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5459 Register Reg; 5460 if (ArgRegsAndSizes.size() == 1) 5461 Reg = ArgRegsAndSizes.front().first; 5462 5463 if (Reg && Reg.isVirtual()) { 5464 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5465 Register PR = RegInfo.getLiveInPhysReg(Reg); 5466 if (PR) 5467 Reg = PR; 5468 } 5469 if (Reg) { 5470 Op = MachineOperand::CreateReg(Reg, false); 5471 IsIndirect = IsDbgDeclare; 5472 } 5473 } 5474 5475 if (!Op && N.getNode()) { 5476 // Check if frame index is available. 5477 SDValue LCandidate = peekThroughBitcasts(N); 5478 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5479 if (FrameIndexSDNode *FINode = 5480 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5481 Op = MachineOperand::CreateFI(FINode->getIndex()); 5482 } 5483 5484 if (!Op) { 5485 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5486 auto splitMultiRegDbgValue 5487 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5488 unsigned Offset = 0; 5489 for (auto RegAndSize : SplitRegs) { 5490 // If the expression is already a fragment, the current register 5491 // offset+size might extend beyond the fragment. In this case, only 5492 // the register bits that are inside the fragment are relevant. 5493 int RegFragmentSizeInBits = RegAndSize.second; 5494 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5495 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5496 // The register is entirely outside the expression fragment, 5497 // so is irrelevant for debug info. 5498 if (Offset >= ExprFragmentSizeInBits) 5499 break; 5500 // The register is partially outside the expression fragment, only 5501 // the low bits within the fragment are relevant for debug info. 5502 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5503 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5504 } 5505 } 5506 5507 auto FragmentExpr = DIExpression::createFragmentExpression( 5508 Expr, Offset, RegFragmentSizeInBits); 5509 Offset += RegAndSize.second; 5510 // If a valid fragment expression cannot be created, the variable's 5511 // correct value cannot be determined and so it is set as Undef. 5512 if (!FragmentExpr) { 5513 SDDbgValue *SDV = DAG.getConstantDbgValue( 5514 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5515 DAG.AddDbgValue(SDV, nullptr, false); 5516 continue; 5517 } 5518 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5519 FuncInfo.ArgDbgValues.push_back( 5520 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5521 RegAndSize.first, Variable, *FragmentExpr)); 5522 } 5523 }; 5524 5525 // Check if ValueMap has reg number. 5526 DenseMap<const Value *, Register>::const_iterator 5527 VMI = FuncInfo.ValueMap.find(V); 5528 if (VMI != FuncInfo.ValueMap.end()) { 5529 const auto &TLI = DAG.getTargetLoweringInfo(); 5530 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5531 V->getType(), getABIRegCopyCC(V)); 5532 if (RFV.occupiesMultipleRegs()) { 5533 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5534 return true; 5535 } 5536 5537 Op = MachineOperand::CreateReg(VMI->second, false); 5538 IsIndirect = IsDbgDeclare; 5539 } else if (ArgRegsAndSizes.size() > 1) { 5540 // This was split due to the calling convention, and no virtual register 5541 // mapping exists for the value. 5542 splitMultiRegDbgValue(ArgRegsAndSizes); 5543 return true; 5544 } 5545 } 5546 5547 if (!Op) 5548 return false; 5549 5550 assert(Variable->isValidLocationForIntrinsic(DL) && 5551 "Expected inlined-at fields to agree"); 5552 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5553 FuncInfo.ArgDbgValues.push_back( 5554 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5555 *Op, Variable, Expr)); 5556 5557 return true; 5558 } 5559 5560 /// Return the appropriate SDDbgValue based on N. 5561 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5562 DILocalVariable *Variable, 5563 DIExpression *Expr, 5564 const DebugLoc &dl, 5565 unsigned DbgSDNodeOrder) { 5566 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5567 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5568 // stack slot locations. 5569 // 5570 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5571 // debug values here after optimization: 5572 // 5573 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5574 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5575 // 5576 // Both describe the direct values of their associated variables. 5577 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5578 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5579 } 5580 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5581 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5582 } 5583 5584 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5585 switch (Intrinsic) { 5586 case Intrinsic::smul_fix: 5587 return ISD::SMULFIX; 5588 case Intrinsic::umul_fix: 5589 return ISD::UMULFIX; 5590 case Intrinsic::smul_fix_sat: 5591 return ISD::SMULFIXSAT; 5592 case Intrinsic::umul_fix_sat: 5593 return ISD::UMULFIXSAT; 5594 case Intrinsic::sdiv_fix: 5595 return ISD::SDIVFIX; 5596 case Intrinsic::udiv_fix: 5597 return ISD::UDIVFIX; 5598 case Intrinsic::sdiv_fix_sat: 5599 return ISD::SDIVFIXSAT; 5600 case Intrinsic::udiv_fix_sat: 5601 return ISD::UDIVFIXSAT; 5602 default: 5603 llvm_unreachable("Unhandled fixed point intrinsic"); 5604 } 5605 } 5606 5607 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5608 const char *FunctionName) { 5609 assert(FunctionName && "FunctionName must not be nullptr"); 5610 SDValue Callee = DAG.getExternalSymbol( 5611 FunctionName, 5612 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5613 LowerCallTo(I, Callee, I.isTailCall()); 5614 } 5615 5616 /// Given a @llvm.call.preallocated.setup, return the corresponding 5617 /// preallocated call. 5618 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5619 assert(cast<CallBase>(PreallocatedSetup) 5620 ->getCalledFunction() 5621 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5622 "expected call_preallocated_setup Value"); 5623 for (auto *U : PreallocatedSetup->users()) { 5624 auto *UseCall = cast<CallBase>(U); 5625 const Function *Fn = UseCall->getCalledFunction(); 5626 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5627 return UseCall; 5628 } 5629 } 5630 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5631 } 5632 5633 /// Lower the call to the specified intrinsic function. 5634 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5635 unsigned Intrinsic) { 5636 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5637 SDLoc sdl = getCurSDLoc(); 5638 DebugLoc dl = getCurDebugLoc(); 5639 SDValue Res; 5640 5641 switch (Intrinsic) { 5642 default: 5643 // By default, turn this into a target intrinsic node. 5644 visitTargetIntrinsic(I, Intrinsic); 5645 return; 5646 case Intrinsic::vscale: { 5647 match(&I, m_VScale(DAG.getDataLayout())); 5648 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5649 setValue(&I, 5650 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5651 return; 5652 } 5653 case Intrinsic::vastart: visitVAStart(I); return; 5654 case Intrinsic::vaend: visitVAEnd(I); return; 5655 case Intrinsic::vacopy: visitVACopy(I); return; 5656 case Intrinsic::returnaddress: 5657 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5658 TLI.getPointerTy(DAG.getDataLayout()), 5659 getValue(I.getArgOperand(0)))); 5660 return; 5661 case Intrinsic::addressofreturnaddress: 5662 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5663 TLI.getPointerTy(DAG.getDataLayout()))); 5664 return; 5665 case Intrinsic::sponentry: 5666 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5667 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5668 return; 5669 case Intrinsic::frameaddress: 5670 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5671 TLI.getFrameIndexTy(DAG.getDataLayout()), 5672 getValue(I.getArgOperand(0)))); 5673 return; 5674 case Intrinsic::read_volatile_register: 5675 case Intrinsic::read_register: { 5676 Value *Reg = I.getArgOperand(0); 5677 SDValue Chain = getRoot(); 5678 SDValue RegName = 5679 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5680 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5681 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5682 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5683 setValue(&I, Res); 5684 DAG.setRoot(Res.getValue(1)); 5685 return; 5686 } 5687 case Intrinsic::write_register: { 5688 Value *Reg = I.getArgOperand(0); 5689 Value *RegValue = I.getArgOperand(1); 5690 SDValue Chain = getRoot(); 5691 SDValue RegName = 5692 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5693 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5694 RegName, getValue(RegValue))); 5695 return; 5696 } 5697 case Intrinsic::memcpy: { 5698 const auto &MCI = cast<MemCpyInst>(I); 5699 SDValue Op1 = getValue(I.getArgOperand(0)); 5700 SDValue Op2 = getValue(I.getArgOperand(1)); 5701 SDValue Op3 = getValue(I.getArgOperand(2)); 5702 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5703 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5704 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5705 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5706 bool isVol = MCI.isVolatile(); 5707 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5708 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5709 // node. 5710 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5711 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5712 /* AlwaysInline */ false, isTC, 5713 MachinePointerInfo(I.getArgOperand(0)), 5714 MachinePointerInfo(I.getArgOperand(1))); 5715 updateDAGForMaybeTailCall(MC); 5716 return; 5717 } 5718 case Intrinsic::memcpy_inline: { 5719 const auto &MCI = cast<MemCpyInlineInst>(I); 5720 SDValue Dst = getValue(I.getArgOperand(0)); 5721 SDValue Src = getValue(I.getArgOperand(1)); 5722 SDValue Size = getValue(I.getArgOperand(2)); 5723 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5724 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5725 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5726 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5727 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5728 bool isVol = MCI.isVolatile(); 5729 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5730 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5731 // node. 5732 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5733 /* AlwaysInline */ true, isTC, 5734 MachinePointerInfo(I.getArgOperand(0)), 5735 MachinePointerInfo(I.getArgOperand(1))); 5736 updateDAGForMaybeTailCall(MC); 5737 return; 5738 } 5739 case Intrinsic::memset: { 5740 const auto &MSI = cast<MemSetInst>(I); 5741 SDValue Op1 = getValue(I.getArgOperand(0)); 5742 SDValue Op2 = getValue(I.getArgOperand(1)); 5743 SDValue Op3 = getValue(I.getArgOperand(2)); 5744 // @llvm.memset defines 0 and 1 to both mean no alignment. 5745 Align Alignment = MSI.getDestAlign().valueOrOne(); 5746 bool isVol = MSI.isVolatile(); 5747 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5748 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5749 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5750 MachinePointerInfo(I.getArgOperand(0))); 5751 updateDAGForMaybeTailCall(MS); 5752 return; 5753 } 5754 case Intrinsic::memmove: { 5755 const auto &MMI = cast<MemMoveInst>(I); 5756 SDValue Op1 = getValue(I.getArgOperand(0)); 5757 SDValue Op2 = getValue(I.getArgOperand(1)); 5758 SDValue Op3 = getValue(I.getArgOperand(2)); 5759 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5760 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5761 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5762 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5763 bool isVol = MMI.isVolatile(); 5764 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5765 // FIXME: Support passing different dest/src alignments to the memmove DAG 5766 // node. 5767 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5768 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5769 isTC, MachinePointerInfo(I.getArgOperand(0)), 5770 MachinePointerInfo(I.getArgOperand(1))); 5771 updateDAGForMaybeTailCall(MM); 5772 return; 5773 } 5774 case Intrinsic::memcpy_element_unordered_atomic: { 5775 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5776 SDValue Dst = getValue(MI.getRawDest()); 5777 SDValue Src = getValue(MI.getRawSource()); 5778 SDValue Length = getValue(MI.getLength()); 5779 5780 unsigned DstAlign = MI.getDestAlignment(); 5781 unsigned SrcAlign = MI.getSourceAlignment(); 5782 Type *LengthTy = MI.getLength()->getType(); 5783 unsigned ElemSz = MI.getElementSizeInBytes(); 5784 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5785 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5786 SrcAlign, Length, LengthTy, ElemSz, isTC, 5787 MachinePointerInfo(MI.getRawDest()), 5788 MachinePointerInfo(MI.getRawSource())); 5789 updateDAGForMaybeTailCall(MC); 5790 return; 5791 } 5792 case Intrinsic::memmove_element_unordered_atomic: { 5793 auto &MI = cast<AtomicMemMoveInst>(I); 5794 SDValue Dst = getValue(MI.getRawDest()); 5795 SDValue Src = getValue(MI.getRawSource()); 5796 SDValue Length = getValue(MI.getLength()); 5797 5798 unsigned DstAlign = MI.getDestAlignment(); 5799 unsigned SrcAlign = MI.getSourceAlignment(); 5800 Type *LengthTy = MI.getLength()->getType(); 5801 unsigned ElemSz = MI.getElementSizeInBytes(); 5802 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5803 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5804 SrcAlign, Length, LengthTy, ElemSz, isTC, 5805 MachinePointerInfo(MI.getRawDest()), 5806 MachinePointerInfo(MI.getRawSource())); 5807 updateDAGForMaybeTailCall(MC); 5808 return; 5809 } 5810 case Intrinsic::memset_element_unordered_atomic: { 5811 auto &MI = cast<AtomicMemSetInst>(I); 5812 SDValue Dst = getValue(MI.getRawDest()); 5813 SDValue Val = getValue(MI.getValue()); 5814 SDValue Length = getValue(MI.getLength()); 5815 5816 unsigned DstAlign = MI.getDestAlignment(); 5817 Type *LengthTy = MI.getLength()->getType(); 5818 unsigned ElemSz = MI.getElementSizeInBytes(); 5819 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5820 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5821 LengthTy, ElemSz, isTC, 5822 MachinePointerInfo(MI.getRawDest())); 5823 updateDAGForMaybeTailCall(MC); 5824 return; 5825 } 5826 case Intrinsic::call_preallocated_setup: { 5827 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5828 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5829 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5830 getRoot(), SrcValue); 5831 setValue(&I, Res); 5832 DAG.setRoot(Res); 5833 return; 5834 } 5835 case Intrinsic::call_preallocated_arg: { 5836 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5837 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5838 SDValue Ops[3]; 5839 Ops[0] = getRoot(); 5840 Ops[1] = SrcValue; 5841 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5842 MVT::i32); // arg index 5843 SDValue Res = DAG.getNode( 5844 ISD::PREALLOCATED_ARG, sdl, 5845 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5846 setValue(&I, Res); 5847 DAG.setRoot(Res.getValue(1)); 5848 return; 5849 } 5850 case Intrinsic::dbg_addr: 5851 case Intrinsic::dbg_declare: { 5852 const auto &DI = cast<DbgVariableIntrinsic>(I); 5853 DILocalVariable *Variable = DI.getVariable(); 5854 DIExpression *Expression = DI.getExpression(); 5855 dropDanglingDebugInfo(Variable, Expression); 5856 assert(Variable && "Missing variable"); 5857 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5858 << "\n"); 5859 // Check if address has undef value. 5860 const Value *Address = DI.getVariableLocation(); 5861 if (!Address || isa<UndefValue>(Address) || 5862 (Address->use_empty() && !isa<Argument>(Address))) { 5863 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5864 << " (bad/undef/unused-arg address)\n"); 5865 return; 5866 } 5867 5868 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5869 5870 // Check if this variable can be described by a frame index, typically 5871 // either as a static alloca or a byval parameter. 5872 int FI = std::numeric_limits<int>::max(); 5873 if (const auto *AI = 5874 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5875 if (AI->isStaticAlloca()) { 5876 auto I = FuncInfo.StaticAllocaMap.find(AI); 5877 if (I != FuncInfo.StaticAllocaMap.end()) 5878 FI = I->second; 5879 } 5880 } else if (const auto *Arg = dyn_cast<Argument>( 5881 Address->stripInBoundsConstantOffsets())) { 5882 FI = FuncInfo.getArgumentFrameIndex(Arg); 5883 } 5884 5885 // llvm.dbg.addr is control dependent and always generates indirect 5886 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5887 // the MachineFunction variable table. 5888 if (FI != std::numeric_limits<int>::max()) { 5889 if (Intrinsic == Intrinsic::dbg_addr) { 5890 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5891 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5892 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5893 } else { 5894 LLVM_DEBUG(dbgs() << "Skipping " << DI 5895 << " (variable info stashed in MF side table)\n"); 5896 } 5897 return; 5898 } 5899 5900 SDValue &N = NodeMap[Address]; 5901 if (!N.getNode() && isa<Argument>(Address)) 5902 // Check unused arguments map. 5903 N = UnusedArgNodeMap[Address]; 5904 SDDbgValue *SDV; 5905 if (N.getNode()) { 5906 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5907 Address = BCI->getOperand(0); 5908 // Parameters are handled specially. 5909 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5910 if (isParameter && FINode) { 5911 // Byval parameter. We have a frame index at this point. 5912 SDV = 5913 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5914 /*IsIndirect*/ true, dl, SDNodeOrder); 5915 } else if (isa<Argument>(Address)) { 5916 // Address is an argument, so try to emit its dbg value using 5917 // virtual register info from the FuncInfo.ValueMap. 5918 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5919 return; 5920 } else { 5921 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5922 true, dl, SDNodeOrder); 5923 } 5924 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5925 } else { 5926 // If Address is an argument then try to emit its dbg value using 5927 // virtual register info from the FuncInfo.ValueMap. 5928 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5929 N)) { 5930 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5931 << " (could not emit func-arg dbg_value)\n"); 5932 } 5933 } 5934 return; 5935 } 5936 case Intrinsic::dbg_label: { 5937 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5938 DILabel *Label = DI.getLabel(); 5939 assert(Label && "Missing label"); 5940 5941 SDDbgLabel *SDV; 5942 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5943 DAG.AddDbgLabel(SDV); 5944 return; 5945 } 5946 case Intrinsic::dbg_value: { 5947 const DbgValueInst &DI = cast<DbgValueInst>(I); 5948 assert(DI.getVariable() && "Missing variable"); 5949 5950 DILocalVariable *Variable = DI.getVariable(); 5951 DIExpression *Expression = DI.getExpression(); 5952 dropDanglingDebugInfo(Variable, Expression); 5953 const Value *V = DI.getValue(); 5954 if (!V) 5955 return; 5956 5957 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5958 SDNodeOrder)) 5959 return; 5960 5961 // TODO: Dangling debug info will eventually either be resolved or produce 5962 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5963 // between the original dbg.value location and its resolved DBG_VALUE, which 5964 // we should ideally fill with an extra Undef DBG_VALUE. 5965 5966 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5967 return; 5968 } 5969 5970 case Intrinsic::eh_typeid_for: { 5971 // Find the type id for the given typeinfo. 5972 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5973 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5974 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5975 setValue(&I, Res); 5976 return; 5977 } 5978 5979 case Intrinsic::eh_return_i32: 5980 case Intrinsic::eh_return_i64: 5981 DAG.getMachineFunction().setCallsEHReturn(true); 5982 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5983 MVT::Other, 5984 getControlRoot(), 5985 getValue(I.getArgOperand(0)), 5986 getValue(I.getArgOperand(1)))); 5987 return; 5988 case Intrinsic::eh_unwind_init: 5989 DAG.getMachineFunction().setCallsUnwindInit(true); 5990 return; 5991 case Intrinsic::eh_dwarf_cfa: 5992 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5993 TLI.getPointerTy(DAG.getDataLayout()), 5994 getValue(I.getArgOperand(0)))); 5995 return; 5996 case Intrinsic::eh_sjlj_callsite: { 5997 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5998 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5999 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6000 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6001 6002 MMI.setCurrentCallSite(CI->getZExtValue()); 6003 return; 6004 } 6005 case Intrinsic::eh_sjlj_functioncontext: { 6006 // Get and store the index of the function context. 6007 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6008 AllocaInst *FnCtx = 6009 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6010 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6011 MFI.setFunctionContextIndex(FI); 6012 return; 6013 } 6014 case Intrinsic::eh_sjlj_setjmp: { 6015 SDValue Ops[2]; 6016 Ops[0] = getRoot(); 6017 Ops[1] = getValue(I.getArgOperand(0)); 6018 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6019 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6020 setValue(&I, Op.getValue(0)); 6021 DAG.setRoot(Op.getValue(1)); 6022 return; 6023 } 6024 case Intrinsic::eh_sjlj_longjmp: 6025 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6026 getRoot(), getValue(I.getArgOperand(0)))); 6027 return; 6028 case Intrinsic::eh_sjlj_setup_dispatch: 6029 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6030 getRoot())); 6031 return; 6032 case Intrinsic::masked_gather: 6033 visitMaskedGather(I); 6034 return; 6035 case Intrinsic::masked_load: 6036 visitMaskedLoad(I); 6037 return; 6038 case Intrinsic::masked_scatter: 6039 visitMaskedScatter(I); 6040 return; 6041 case Intrinsic::masked_store: 6042 visitMaskedStore(I); 6043 return; 6044 case Intrinsic::masked_expandload: 6045 visitMaskedLoad(I, true /* IsExpanding */); 6046 return; 6047 case Intrinsic::masked_compressstore: 6048 visitMaskedStore(I, true /* IsCompressing */); 6049 return; 6050 case Intrinsic::powi: 6051 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6052 getValue(I.getArgOperand(1)), DAG)); 6053 return; 6054 case Intrinsic::log: 6055 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6056 return; 6057 case Intrinsic::log2: 6058 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6059 return; 6060 case Intrinsic::log10: 6061 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6062 return; 6063 case Intrinsic::exp: 6064 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6065 return; 6066 case Intrinsic::exp2: 6067 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6068 return; 6069 case Intrinsic::pow: 6070 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6071 getValue(I.getArgOperand(1)), DAG, TLI)); 6072 return; 6073 case Intrinsic::sqrt: 6074 case Intrinsic::fabs: 6075 case Intrinsic::sin: 6076 case Intrinsic::cos: 6077 case Intrinsic::floor: 6078 case Intrinsic::ceil: 6079 case Intrinsic::trunc: 6080 case Intrinsic::rint: 6081 case Intrinsic::nearbyint: 6082 case Intrinsic::round: 6083 case Intrinsic::roundeven: 6084 case Intrinsic::canonicalize: { 6085 unsigned Opcode; 6086 switch (Intrinsic) { 6087 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6088 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6089 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6090 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6091 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6092 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6093 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6094 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6095 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6096 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6097 case Intrinsic::round: Opcode = ISD::FROUND; break; 6098 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6099 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6100 } 6101 6102 setValue(&I, DAG.getNode(Opcode, sdl, 6103 getValue(I.getArgOperand(0)).getValueType(), 6104 getValue(I.getArgOperand(0)))); 6105 return; 6106 } 6107 case Intrinsic::lround: 6108 case Intrinsic::llround: 6109 case Intrinsic::lrint: 6110 case Intrinsic::llrint: { 6111 unsigned Opcode; 6112 switch (Intrinsic) { 6113 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6114 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6115 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6116 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6117 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6118 } 6119 6120 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6121 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6122 getValue(I.getArgOperand(0)))); 6123 return; 6124 } 6125 case Intrinsic::minnum: 6126 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6127 getValue(I.getArgOperand(0)).getValueType(), 6128 getValue(I.getArgOperand(0)), 6129 getValue(I.getArgOperand(1)))); 6130 return; 6131 case Intrinsic::maxnum: 6132 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6133 getValue(I.getArgOperand(0)).getValueType(), 6134 getValue(I.getArgOperand(0)), 6135 getValue(I.getArgOperand(1)))); 6136 return; 6137 case Intrinsic::minimum: 6138 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6139 getValue(I.getArgOperand(0)).getValueType(), 6140 getValue(I.getArgOperand(0)), 6141 getValue(I.getArgOperand(1)))); 6142 return; 6143 case Intrinsic::maximum: 6144 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6145 getValue(I.getArgOperand(0)).getValueType(), 6146 getValue(I.getArgOperand(0)), 6147 getValue(I.getArgOperand(1)))); 6148 return; 6149 case Intrinsic::copysign: 6150 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6151 getValue(I.getArgOperand(0)).getValueType(), 6152 getValue(I.getArgOperand(0)), 6153 getValue(I.getArgOperand(1)))); 6154 return; 6155 case Intrinsic::fma: 6156 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6157 getValue(I.getArgOperand(0)).getValueType(), 6158 getValue(I.getArgOperand(0)), 6159 getValue(I.getArgOperand(1)), 6160 getValue(I.getArgOperand(2)))); 6161 return; 6162 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6163 case Intrinsic::INTRINSIC: 6164 #include "llvm/IR/ConstrainedOps.def" 6165 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6166 return; 6167 case Intrinsic::fmuladd: { 6168 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6169 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6170 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6171 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6172 getValue(I.getArgOperand(0)).getValueType(), 6173 getValue(I.getArgOperand(0)), 6174 getValue(I.getArgOperand(1)), 6175 getValue(I.getArgOperand(2)))); 6176 } else { 6177 // TODO: Intrinsic calls should have fast-math-flags. 6178 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6179 getValue(I.getArgOperand(0)).getValueType(), 6180 getValue(I.getArgOperand(0)), 6181 getValue(I.getArgOperand(1))); 6182 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6183 getValue(I.getArgOperand(0)).getValueType(), 6184 Mul, 6185 getValue(I.getArgOperand(2))); 6186 setValue(&I, Add); 6187 } 6188 return; 6189 } 6190 case Intrinsic::convert_to_fp16: 6191 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6192 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6193 getValue(I.getArgOperand(0)), 6194 DAG.getTargetConstant(0, sdl, 6195 MVT::i32)))); 6196 return; 6197 case Intrinsic::convert_from_fp16: 6198 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6199 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6200 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6201 getValue(I.getArgOperand(0))))); 6202 return; 6203 case Intrinsic::pcmarker: { 6204 SDValue Tmp = getValue(I.getArgOperand(0)); 6205 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6206 return; 6207 } 6208 case Intrinsic::readcyclecounter: { 6209 SDValue Op = getRoot(); 6210 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6211 DAG.getVTList(MVT::i64, MVT::Other), Op); 6212 setValue(&I, Res); 6213 DAG.setRoot(Res.getValue(1)); 6214 return; 6215 } 6216 case Intrinsic::bitreverse: 6217 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6218 getValue(I.getArgOperand(0)).getValueType(), 6219 getValue(I.getArgOperand(0)))); 6220 return; 6221 case Intrinsic::bswap: 6222 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6223 getValue(I.getArgOperand(0)).getValueType(), 6224 getValue(I.getArgOperand(0)))); 6225 return; 6226 case Intrinsic::cttz: { 6227 SDValue Arg = getValue(I.getArgOperand(0)); 6228 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6229 EVT Ty = Arg.getValueType(); 6230 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6231 sdl, Ty, Arg)); 6232 return; 6233 } 6234 case Intrinsic::ctlz: { 6235 SDValue Arg = getValue(I.getArgOperand(0)); 6236 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6237 EVT Ty = Arg.getValueType(); 6238 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6239 sdl, Ty, Arg)); 6240 return; 6241 } 6242 case Intrinsic::ctpop: { 6243 SDValue Arg = getValue(I.getArgOperand(0)); 6244 EVT Ty = Arg.getValueType(); 6245 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6246 return; 6247 } 6248 case Intrinsic::fshl: 6249 case Intrinsic::fshr: { 6250 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6251 SDValue X = getValue(I.getArgOperand(0)); 6252 SDValue Y = getValue(I.getArgOperand(1)); 6253 SDValue Z = getValue(I.getArgOperand(2)); 6254 EVT VT = X.getValueType(); 6255 6256 if (X == Y) { 6257 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6258 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6259 } else { 6260 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6261 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6262 } 6263 return; 6264 } 6265 case Intrinsic::sadd_sat: { 6266 SDValue Op1 = getValue(I.getArgOperand(0)); 6267 SDValue Op2 = getValue(I.getArgOperand(1)); 6268 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6269 return; 6270 } 6271 case Intrinsic::uadd_sat: { 6272 SDValue Op1 = getValue(I.getArgOperand(0)); 6273 SDValue Op2 = getValue(I.getArgOperand(1)); 6274 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6275 return; 6276 } 6277 case Intrinsic::ssub_sat: { 6278 SDValue Op1 = getValue(I.getArgOperand(0)); 6279 SDValue Op2 = getValue(I.getArgOperand(1)); 6280 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6281 return; 6282 } 6283 case Intrinsic::usub_sat: { 6284 SDValue Op1 = getValue(I.getArgOperand(0)); 6285 SDValue Op2 = getValue(I.getArgOperand(1)); 6286 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6287 return; 6288 } 6289 case Intrinsic::sshl_sat: { 6290 SDValue Op1 = getValue(I.getArgOperand(0)); 6291 SDValue Op2 = getValue(I.getArgOperand(1)); 6292 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6293 return; 6294 } 6295 case Intrinsic::ushl_sat: { 6296 SDValue Op1 = getValue(I.getArgOperand(0)); 6297 SDValue Op2 = getValue(I.getArgOperand(1)); 6298 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6299 return; 6300 } 6301 case Intrinsic::smul_fix: 6302 case Intrinsic::umul_fix: 6303 case Intrinsic::smul_fix_sat: 6304 case Intrinsic::umul_fix_sat: { 6305 SDValue Op1 = getValue(I.getArgOperand(0)); 6306 SDValue Op2 = getValue(I.getArgOperand(1)); 6307 SDValue Op3 = getValue(I.getArgOperand(2)); 6308 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6309 Op1.getValueType(), Op1, Op2, Op3)); 6310 return; 6311 } 6312 case Intrinsic::sdiv_fix: 6313 case Intrinsic::udiv_fix: 6314 case Intrinsic::sdiv_fix_sat: 6315 case Intrinsic::udiv_fix_sat: { 6316 SDValue Op1 = getValue(I.getArgOperand(0)); 6317 SDValue Op2 = getValue(I.getArgOperand(1)); 6318 SDValue Op3 = getValue(I.getArgOperand(2)); 6319 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6320 Op1, Op2, Op3, DAG, TLI)); 6321 return; 6322 } 6323 case Intrinsic::smax: { 6324 SDValue Op1 = getValue(I.getArgOperand(0)); 6325 SDValue Op2 = getValue(I.getArgOperand(1)); 6326 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6327 return; 6328 } 6329 case Intrinsic::smin: { 6330 SDValue Op1 = getValue(I.getArgOperand(0)); 6331 SDValue Op2 = getValue(I.getArgOperand(1)); 6332 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6333 return; 6334 } 6335 case Intrinsic::umax: { 6336 SDValue Op1 = getValue(I.getArgOperand(0)); 6337 SDValue Op2 = getValue(I.getArgOperand(1)); 6338 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6339 return; 6340 } 6341 case Intrinsic::umin: { 6342 SDValue Op1 = getValue(I.getArgOperand(0)); 6343 SDValue Op2 = getValue(I.getArgOperand(1)); 6344 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6345 return; 6346 } 6347 case Intrinsic::abs: { 6348 // TODO: Preserve "int min is poison" arg in SDAG? 6349 SDValue Op1 = getValue(I.getArgOperand(0)); 6350 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6351 return; 6352 } 6353 case Intrinsic::stacksave: { 6354 SDValue Op = getRoot(); 6355 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6356 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6357 setValue(&I, Res); 6358 DAG.setRoot(Res.getValue(1)); 6359 return; 6360 } 6361 case Intrinsic::stackrestore: 6362 Res = getValue(I.getArgOperand(0)); 6363 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6364 return; 6365 case Intrinsic::get_dynamic_area_offset: { 6366 SDValue Op = getRoot(); 6367 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6368 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6369 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6370 // target. 6371 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6372 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6373 " intrinsic!"); 6374 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6375 Op); 6376 DAG.setRoot(Op); 6377 setValue(&I, Res); 6378 return; 6379 } 6380 case Intrinsic::stackguard: { 6381 MachineFunction &MF = DAG.getMachineFunction(); 6382 const Module &M = *MF.getFunction().getParent(); 6383 SDValue Chain = getRoot(); 6384 if (TLI.useLoadStackGuardNode()) { 6385 Res = getLoadStackGuard(DAG, sdl, Chain); 6386 } else { 6387 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6388 const Value *Global = TLI.getSDagStackGuard(M); 6389 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6390 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6391 MachinePointerInfo(Global, 0), Align, 6392 MachineMemOperand::MOVolatile); 6393 } 6394 if (TLI.useStackGuardXorFP()) 6395 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6396 DAG.setRoot(Chain); 6397 setValue(&I, Res); 6398 return; 6399 } 6400 case Intrinsic::stackprotector: { 6401 // Emit code into the DAG to store the stack guard onto the stack. 6402 MachineFunction &MF = DAG.getMachineFunction(); 6403 MachineFrameInfo &MFI = MF.getFrameInfo(); 6404 SDValue Src, Chain = getRoot(); 6405 6406 if (TLI.useLoadStackGuardNode()) 6407 Src = getLoadStackGuard(DAG, sdl, Chain); 6408 else 6409 Src = getValue(I.getArgOperand(0)); // The guard's value. 6410 6411 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6412 6413 int FI = FuncInfo.StaticAllocaMap[Slot]; 6414 MFI.setStackProtectorIndex(FI); 6415 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6416 6417 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6418 6419 // Store the stack protector onto the stack. 6420 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6421 DAG.getMachineFunction(), FI), 6422 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6423 setValue(&I, Res); 6424 DAG.setRoot(Res); 6425 return; 6426 } 6427 case Intrinsic::objectsize: 6428 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6429 6430 case Intrinsic::is_constant: 6431 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6432 6433 case Intrinsic::annotation: 6434 case Intrinsic::ptr_annotation: 6435 case Intrinsic::launder_invariant_group: 6436 case Intrinsic::strip_invariant_group: 6437 // Drop the intrinsic, but forward the value 6438 setValue(&I, getValue(I.getOperand(0))); 6439 return; 6440 case Intrinsic::assume: 6441 case Intrinsic::var_annotation: 6442 case Intrinsic::sideeffect: 6443 // Discard annotate attributes, assumptions, and artificial side-effects. 6444 return; 6445 6446 case Intrinsic::codeview_annotation: { 6447 // Emit a label associated with this metadata. 6448 MachineFunction &MF = DAG.getMachineFunction(); 6449 MCSymbol *Label = 6450 MF.getMMI().getContext().createTempSymbol("annotation", true); 6451 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6452 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6453 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6454 DAG.setRoot(Res); 6455 return; 6456 } 6457 6458 case Intrinsic::init_trampoline: { 6459 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6460 6461 SDValue Ops[6]; 6462 Ops[0] = getRoot(); 6463 Ops[1] = getValue(I.getArgOperand(0)); 6464 Ops[2] = getValue(I.getArgOperand(1)); 6465 Ops[3] = getValue(I.getArgOperand(2)); 6466 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6467 Ops[5] = DAG.getSrcValue(F); 6468 6469 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6470 6471 DAG.setRoot(Res); 6472 return; 6473 } 6474 case Intrinsic::adjust_trampoline: 6475 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6476 TLI.getPointerTy(DAG.getDataLayout()), 6477 getValue(I.getArgOperand(0)))); 6478 return; 6479 case Intrinsic::gcroot: { 6480 assert(DAG.getMachineFunction().getFunction().hasGC() && 6481 "only valid in functions with gc specified, enforced by Verifier"); 6482 assert(GFI && "implied by previous"); 6483 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6484 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6485 6486 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6487 GFI->addStackRoot(FI->getIndex(), TypeMap); 6488 return; 6489 } 6490 case Intrinsic::gcread: 6491 case Intrinsic::gcwrite: 6492 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6493 case Intrinsic::flt_rounds: 6494 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6495 setValue(&I, Res); 6496 DAG.setRoot(Res.getValue(1)); 6497 return; 6498 6499 case Intrinsic::expect: 6500 // Just replace __builtin_expect(exp, c) with EXP. 6501 setValue(&I, getValue(I.getArgOperand(0))); 6502 return; 6503 6504 case Intrinsic::debugtrap: 6505 case Intrinsic::trap: { 6506 StringRef TrapFuncName = 6507 I.getAttributes() 6508 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6509 .getValueAsString(); 6510 if (TrapFuncName.empty()) { 6511 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6512 ISD::TRAP : ISD::DEBUGTRAP; 6513 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6514 return; 6515 } 6516 TargetLowering::ArgListTy Args; 6517 6518 TargetLowering::CallLoweringInfo CLI(DAG); 6519 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6520 CallingConv::C, I.getType(), 6521 DAG.getExternalSymbol(TrapFuncName.data(), 6522 TLI.getPointerTy(DAG.getDataLayout())), 6523 std::move(Args)); 6524 6525 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6526 DAG.setRoot(Result.second); 6527 return; 6528 } 6529 6530 case Intrinsic::uadd_with_overflow: 6531 case Intrinsic::sadd_with_overflow: 6532 case Intrinsic::usub_with_overflow: 6533 case Intrinsic::ssub_with_overflow: 6534 case Intrinsic::umul_with_overflow: 6535 case Intrinsic::smul_with_overflow: { 6536 ISD::NodeType Op; 6537 switch (Intrinsic) { 6538 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6539 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6540 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6541 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6542 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6543 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6544 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6545 } 6546 SDValue Op1 = getValue(I.getArgOperand(0)); 6547 SDValue Op2 = getValue(I.getArgOperand(1)); 6548 6549 EVT ResultVT = Op1.getValueType(); 6550 EVT OverflowVT = MVT::i1; 6551 if (ResultVT.isVector()) 6552 OverflowVT = EVT::getVectorVT( 6553 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6554 6555 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6556 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6557 return; 6558 } 6559 case Intrinsic::prefetch: { 6560 SDValue Ops[5]; 6561 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6562 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6563 Ops[0] = DAG.getRoot(); 6564 Ops[1] = getValue(I.getArgOperand(0)); 6565 Ops[2] = getValue(I.getArgOperand(1)); 6566 Ops[3] = getValue(I.getArgOperand(2)); 6567 Ops[4] = getValue(I.getArgOperand(3)); 6568 SDValue Result = DAG.getMemIntrinsicNode( 6569 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6570 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6571 /* align */ None, Flags); 6572 6573 // Chain the prefetch in parallell with any pending loads, to stay out of 6574 // the way of later optimizations. 6575 PendingLoads.push_back(Result); 6576 Result = getRoot(); 6577 DAG.setRoot(Result); 6578 return; 6579 } 6580 case Intrinsic::lifetime_start: 6581 case Intrinsic::lifetime_end: { 6582 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6583 // Stack coloring is not enabled in O0, discard region information. 6584 if (TM.getOptLevel() == CodeGenOpt::None) 6585 return; 6586 6587 const int64_t ObjectSize = 6588 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6589 Value *const ObjectPtr = I.getArgOperand(1); 6590 SmallVector<const Value *, 4> Allocas; 6591 getUnderlyingObjects(ObjectPtr, Allocas); 6592 6593 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6594 E = Allocas.end(); Object != E; ++Object) { 6595 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6596 6597 // Could not find an Alloca. 6598 if (!LifetimeObject) 6599 continue; 6600 6601 // First check that the Alloca is static, otherwise it won't have a 6602 // valid frame index. 6603 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6604 if (SI == FuncInfo.StaticAllocaMap.end()) 6605 return; 6606 6607 const int FrameIndex = SI->second; 6608 int64_t Offset; 6609 if (GetPointerBaseWithConstantOffset( 6610 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6611 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6612 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6613 Offset); 6614 DAG.setRoot(Res); 6615 } 6616 return; 6617 } 6618 case Intrinsic::invariant_start: 6619 // Discard region information. 6620 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6621 return; 6622 case Intrinsic::invariant_end: 6623 // Discard region information. 6624 return; 6625 case Intrinsic::clear_cache: 6626 /// FunctionName may be null. 6627 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6628 lowerCallToExternalSymbol(I, FunctionName); 6629 return; 6630 case Intrinsic::donothing: 6631 // ignore 6632 return; 6633 case Intrinsic::experimental_stackmap: 6634 visitStackmap(I); 6635 return; 6636 case Intrinsic::experimental_patchpoint_void: 6637 case Intrinsic::experimental_patchpoint_i64: 6638 visitPatchpoint(I); 6639 return; 6640 case Intrinsic::experimental_gc_statepoint: 6641 LowerStatepoint(cast<GCStatepointInst>(I)); 6642 return; 6643 case Intrinsic::experimental_gc_result: 6644 visitGCResult(cast<GCResultInst>(I)); 6645 return; 6646 case Intrinsic::experimental_gc_relocate: 6647 visitGCRelocate(cast<GCRelocateInst>(I)); 6648 return; 6649 case Intrinsic::instrprof_increment: 6650 llvm_unreachable("instrprof failed to lower an increment"); 6651 case Intrinsic::instrprof_value_profile: 6652 llvm_unreachable("instrprof failed to lower a value profiling call"); 6653 case Intrinsic::localescape: { 6654 MachineFunction &MF = DAG.getMachineFunction(); 6655 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6656 6657 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6658 // is the same on all targets. 6659 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6660 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6661 if (isa<ConstantPointerNull>(Arg)) 6662 continue; // Skip null pointers. They represent a hole in index space. 6663 AllocaInst *Slot = cast<AllocaInst>(Arg); 6664 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6665 "can only escape static allocas"); 6666 int FI = FuncInfo.StaticAllocaMap[Slot]; 6667 MCSymbol *FrameAllocSym = 6668 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6669 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6670 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6671 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6672 .addSym(FrameAllocSym) 6673 .addFrameIndex(FI); 6674 } 6675 6676 return; 6677 } 6678 6679 case Intrinsic::localrecover: { 6680 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6681 MachineFunction &MF = DAG.getMachineFunction(); 6682 6683 // Get the symbol that defines the frame offset. 6684 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6685 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6686 unsigned IdxVal = 6687 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6688 MCSymbol *FrameAllocSym = 6689 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6690 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6691 6692 Value *FP = I.getArgOperand(1); 6693 SDValue FPVal = getValue(FP); 6694 EVT PtrVT = FPVal.getValueType(); 6695 6696 // Create a MCSymbol for the label to avoid any target lowering 6697 // that would make this PC relative. 6698 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6699 SDValue OffsetVal = 6700 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6701 6702 // Add the offset to the FP. 6703 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6704 setValue(&I, Add); 6705 6706 return; 6707 } 6708 6709 case Intrinsic::eh_exceptionpointer: 6710 case Intrinsic::eh_exceptioncode: { 6711 // Get the exception pointer vreg, copy from it, and resize it to fit. 6712 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6713 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6714 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6715 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6716 SDValue N = 6717 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6718 if (Intrinsic == Intrinsic::eh_exceptioncode) 6719 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6720 setValue(&I, N); 6721 return; 6722 } 6723 case Intrinsic::xray_customevent: { 6724 // Here we want to make sure that the intrinsic behaves as if it has a 6725 // specific calling convention, and only for x86_64. 6726 // FIXME: Support other platforms later. 6727 const auto &Triple = DAG.getTarget().getTargetTriple(); 6728 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6729 return; 6730 6731 SDLoc DL = getCurSDLoc(); 6732 SmallVector<SDValue, 8> Ops; 6733 6734 // We want to say that we always want the arguments in registers. 6735 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6736 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6737 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6738 SDValue Chain = getRoot(); 6739 Ops.push_back(LogEntryVal); 6740 Ops.push_back(StrSizeVal); 6741 Ops.push_back(Chain); 6742 6743 // We need to enforce the calling convention for the callsite, so that 6744 // argument ordering is enforced correctly, and that register allocation can 6745 // see that some registers may be assumed clobbered and have to preserve 6746 // them across calls to the intrinsic. 6747 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6748 DL, NodeTys, Ops); 6749 SDValue patchableNode = SDValue(MN, 0); 6750 DAG.setRoot(patchableNode); 6751 setValue(&I, patchableNode); 6752 return; 6753 } 6754 case Intrinsic::xray_typedevent: { 6755 // Here we want to make sure that the intrinsic behaves as if it has a 6756 // specific calling convention, and only for x86_64. 6757 // FIXME: Support other platforms later. 6758 const auto &Triple = DAG.getTarget().getTargetTriple(); 6759 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6760 return; 6761 6762 SDLoc DL = getCurSDLoc(); 6763 SmallVector<SDValue, 8> Ops; 6764 6765 // We want to say that we always want the arguments in registers. 6766 // It's unclear to me how manipulating the selection DAG here forces callers 6767 // to provide arguments in registers instead of on the stack. 6768 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6769 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6770 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6771 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6772 SDValue Chain = getRoot(); 6773 Ops.push_back(LogTypeId); 6774 Ops.push_back(LogEntryVal); 6775 Ops.push_back(StrSizeVal); 6776 Ops.push_back(Chain); 6777 6778 // We need to enforce the calling convention for the callsite, so that 6779 // argument ordering is enforced correctly, and that register allocation can 6780 // see that some registers may be assumed clobbered and have to preserve 6781 // them across calls to the intrinsic. 6782 MachineSDNode *MN = DAG.getMachineNode( 6783 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6784 SDValue patchableNode = SDValue(MN, 0); 6785 DAG.setRoot(patchableNode); 6786 setValue(&I, patchableNode); 6787 return; 6788 } 6789 case Intrinsic::experimental_deoptimize: 6790 LowerDeoptimizeCall(&I); 6791 return; 6792 6793 case Intrinsic::experimental_vector_reduce_v2_fadd: 6794 case Intrinsic::experimental_vector_reduce_v2_fmul: 6795 case Intrinsic::experimental_vector_reduce_add: 6796 case Intrinsic::experimental_vector_reduce_mul: 6797 case Intrinsic::experimental_vector_reduce_and: 6798 case Intrinsic::experimental_vector_reduce_or: 6799 case Intrinsic::experimental_vector_reduce_xor: 6800 case Intrinsic::experimental_vector_reduce_smax: 6801 case Intrinsic::experimental_vector_reduce_smin: 6802 case Intrinsic::experimental_vector_reduce_umax: 6803 case Intrinsic::experimental_vector_reduce_umin: 6804 case Intrinsic::experimental_vector_reduce_fmax: 6805 case Intrinsic::experimental_vector_reduce_fmin: 6806 visitVectorReduce(I, Intrinsic); 6807 return; 6808 6809 case Intrinsic::icall_branch_funnel: { 6810 SmallVector<SDValue, 16> Ops; 6811 Ops.push_back(getValue(I.getArgOperand(0))); 6812 6813 int64_t Offset; 6814 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6815 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6816 if (!Base) 6817 report_fatal_error( 6818 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6819 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6820 6821 struct BranchFunnelTarget { 6822 int64_t Offset; 6823 SDValue Target; 6824 }; 6825 SmallVector<BranchFunnelTarget, 8> Targets; 6826 6827 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6828 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6829 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6830 if (ElemBase != Base) 6831 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6832 "to the same GlobalValue"); 6833 6834 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6835 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6836 if (!GA) 6837 report_fatal_error( 6838 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6839 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6840 GA->getGlobal(), getCurSDLoc(), 6841 Val.getValueType(), GA->getOffset())}); 6842 } 6843 llvm::sort(Targets, 6844 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6845 return T1.Offset < T2.Offset; 6846 }); 6847 6848 for (auto &T : Targets) { 6849 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6850 Ops.push_back(T.Target); 6851 } 6852 6853 Ops.push_back(DAG.getRoot()); // Chain 6854 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6855 getCurSDLoc(), MVT::Other, Ops), 6856 0); 6857 DAG.setRoot(N); 6858 setValue(&I, N); 6859 HasTailCall = true; 6860 return; 6861 } 6862 6863 case Intrinsic::wasm_landingpad_index: 6864 // Information this intrinsic contained has been transferred to 6865 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6866 // delete it now. 6867 return; 6868 6869 case Intrinsic::aarch64_settag: 6870 case Intrinsic::aarch64_settag_zero: { 6871 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6872 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6873 SDValue Val = TSI.EmitTargetCodeForSetTag( 6874 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6875 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6876 ZeroMemory); 6877 DAG.setRoot(Val); 6878 setValue(&I, Val); 6879 return; 6880 } 6881 case Intrinsic::ptrmask: { 6882 SDValue Ptr = getValue(I.getOperand(0)); 6883 SDValue Const = getValue(I.getOperand(1)); 6884 6885 EVT PtrVT = Ptr.getValueType(); 6886 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 6887 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 6888 return; 6889 } 6890 case Intrinsic::get_active_lane_mask: { 6891 auto DL = getCurSDLoc(); 6892 SDValue Index = getValue(I.getOperand(0)); 6893 SDValue TripCount = getValue(I.getOperand(1)); 6894 Type *ElementTy = I.getOperand(0)->getType(); 6895 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6896 unsigned VecWidth = VT.getVectorNumElements(); 6897 6898 SmallVector<SDValue, 16> OpsTripCount; 6899 SmallVector<SDValue, 16> OpsIndex; 6900 SmallVector<SDValue, 16> OpsStepConstants; 6901 for (unsigned i = 0; i < VecWidth; i++) { 6902 OpsTripCount.push_back(TripCount); 6903 OpsIndex.push_back(Index); 6904 OpsStepConstants.push_back( 6905 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 6906 } 6907 6908 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 6909 6910 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 6911 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 6912 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 6913 SDValue VectorInduction = DAG.getNode( 6914 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 6915 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 6916 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 6917 VectorTripCount, ISD::CondCode::SETULT); 6918 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 6919 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 6920 SetCC)); 6921 return; 6922 } 6923 } 6924 } 6925 6926 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6927 const ConstrainedFPIntrinsic &FPI) { 6928 SDLoc sdl = getCurSDLoc(); 6929 6930 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6931 SmallVector<EVT, 4> ValueVTs; 6932 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6933 ValueVTs.push_back(MVT::Other); // Out chain 6934 6935 // We do not need to serialize constrained FP intrinsics against 6936 // each other or against (nonvolatile) loads, so they can be 6937 // chained like loads. 6938 SDValue Chain = DAG.getRoot(); 6939 SmallVector<SDValue, 4> Opers; 6940 Opers.push_back(Chain); 6941 if (FPI.isUnaryOp()) { 6942 Opers.push_back(getValue(FPI.getArgOperand(0))); 6943 } else if (FPI.isTernaryOp()) { 6944 Opers.push_back(getValue(FPI.getArgOperand(0))); 6945 Opers.push_back(getValue(FPI.getArgOperand(1))); 6946 Opers.push_back(getValue(FPI.getArgOperand(2))); 6947 } else { 6948 Opers.push_back(getValue(FPI.getArgOperand(0))); 6949 Opers.push_back(getValue(FPI.getArgOperand(1))); 6950 } 6951 6952 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 6953 assert(Result.getNode()->getNumValues() == 2); 6954 6955 // Push node to the appropriate list so that future instructions can be 6956 // chained up correctly. 6957 SDValue OutChain = Result.getValue(1); 6958 switch (EB) { 6959 case fp::ExceptionBehavior::ebIgnore: 6960 // The only reason why ebIgnore nodes still need to be chained is that 6961 // they might depend on the current rounding mode, and therefore must 6962 // not be moved across instruction that may change that mode. 6963 LLVM_FALLTHROUGH; 6964 case fp::ExceptionBehavior::ebMayTrap: 6965 // These must not be moved across calls or instructions that may change 6966 // floating-point exception masks. 6967 PendingConstrainedFP.push_back(OutChain); 6968 break; 6969 case fp::ExceptionBehavior::ebStrict: 6970 // These must not be moved across calls or instructions that may change 6971 // floating-point exception masks or read floating-point exception flags. 6972 // In addition, they cannot be optimized out even if unused. 6973 PendingConstrainedFPStrict.push_back(OutChain); 6974 break; 6975 } 6976 }; 6977 6978 SDVTList VTs = DAG.getVTList(ValueVTs); 6979 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 6980 6981 SDNodeFlags Flags; 6982 if (EB == fp::ExceptionBehavior::ebIgnore) 6983 Flags.setNoFPExcept(true); 6984 6985 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 6986 Flags.copyFMF(*FPOp); 6987 6988 unsigned Opcode; 6989 switch (FPI.getIntrinsicID()) { 6990 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6991 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6992 case Intrinsic::INTRINSIC: \ 6993 Opcode = ISD::STRICT_##DAGN; \ 6994 break; 6995 #include "llvm/IR/ConstrainedOps.def" 6996 case Intrinsic::experimental_constrained_fmuladd: { 6997 Opcode = ISD::STRICT_FMA; 6998 // Break fmuladd into fmul and fadd. 6999 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7000 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7001 ValueVTs[0])) { 7002 Opers.pop_back(); 7003 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7004 pushOutChain(Mul, EB); 7005 Opcode = ISD::STRICT_FADD; 7006 Opers.clear(); 7007 Opers.push_back(Mul.getValue(1)); 7008 Opers.push_back(Mul.getValue(0)); 7009 Opers.push_back(getValue(FPI.getArgOperand(2))); 7010 } 7011 break; 7012 } 7013 } 7014 7015 // A few strict DAG nodes carry additional operands that are not 7016 // set up by the default code above. 7017 switch (Opcode) { 7018 default: break; 7019 case ISD::STRICT_FP_ROUND: 7020 Opers.push_back( 7021 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7022 break; 7023 case ISD::STRICT_FSETCC: 7024 case ISD::STRICT_FSETCCS: { 7025 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7026 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 7027 break; 7028 } 7029 } 7030 7031 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7032 pushOutChain(Result, EB); 7033 7034 SDValue FPResult = Result.getValue(0); 7035 setValue(&FPI, FPResult); 7036 } 7037 7038 std::pair<SDValue, SDValue> 7039 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7040 const BasicBlock *EHPadBB) { 7041 MachineFunction &MF = DAG.getMachineFunction(); 7042 MachineModuleInfo &MMI = MF.getMMI(); 7043 MCSymbol *BeginLabel = nullptr; 7044 7045 if (EHPadBB) { 7046 // Insert a label before the invoke call to mark the try range. This can be 7047 // used to detect deletion of the invoke via the MachineModuleInfo. 7048 BeginLabel = MMI.getContext().createTempSymbol(); 7049 7050 // For SjLj, keep track of which landing pads go with which invokes 7051 // so as to maintain the ordering of pads in the LSDA. 7052 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7053 if (CallSiteIndex) { 7054 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7055 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7056 7057 // Now that the call site is handled, stop tracking it. 7058 MMI.setCurrentCallSite(0); 7059 } 7060 7061 // Both PendingLoads and PendingExports must be flushed here; 7062 // this call might not return. 7063 (void)getRoot(); 7064 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7065 7066 CLI.setChain(getRoot()); 7067 } 7068 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7069 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7070 7071 assert((CLI.IsTailCall || Result.second.getNode()) && 7072 "Non-null chain expected with non-tail call!"); 7073 assert((Result.second.getNode() || !Result.first.getNode()) && 7074 "Null value expected with tail call!"); 7075 7076 if (!Result.second.getNode()) { 7077 // As a special case, a null chain means that a tail call has been emitted 7078 // and the DAG root is already updated. 7079 HasTailCall = true; 7080 7081 // Since there's no actual continuation from this block, nothing can be 7082 // relying on us setting vregs for them. 7083 PendingExports.clear(); 7084 } else { 7085 DAG.setRoot(Result.second); 7086 } 7087 7088 if (EHPadBB) { 7089 // Insert a label at the end of the invoke call to mark the try range. This 7090 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7091 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7092 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7093 7094 // Inform MachineModuleInfo of range. 7095 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7096 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7097 // actually use outlined funclets and their LSDA info style. 7098 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7099 assert(CLI.CB); 7100 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7101 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7102 } else if (!isScopedEHPersonality(Pers)) { 7103 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7104 } 7105 } 7106 7107 return Result; 7108 } 7109 7110 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7111 bool isTailCall, 7112 const BasicBlock *EHPadBB) { 7113 auto &DL = DAG.getDataLayout(); 7114 FunctionType *FTy = CB.getFunctionType(); 7115 Type *RetTy = CB.getType(); 7116 7117 TargetLowering::ArgListTy Args; 7118 Args.reserve(CB.arg_size()); 7119 7120 const Value *SwiftErrorVal = nullptr; 7121 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7122 7123 if (isTailCall) { 7124 // Avoid emitting tail calls in functions with the disable-tail-calls 7125 // attribute. 7126 auto *Caller = CB.getParent()->getParent(); 7127 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7128 "true") 7129 isTailCall = false; 7130 7131 // We can't tail call inside a function with a swifterror argument. Lowering 7132 // does not support this yet. It would have to move into the swifterror 7133 // register before the call. 7134 if (TLI.supportSwiftError() && 7135 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7136 isTailCall = false; 7137 } 7138 7139 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7140 TargetLowering::ArgListEntry Entry; 7141 const Value *V = *I; 7142 7143 // Skip empty types 7144 if (V->getType()->isEmptyTy()) 7145 continue; 7146 7147 SDValue ArgNode = getValue(V); 7148 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7149 7150 Entry.setAttributes(&CB, I - CB.arg_begin()); 7151 7152 // Use swifterror virtual register as input to the call. 7153 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7154 SwiftErrorVal = V; 7155 // We find the virtual register for the actual swifterror argument. 7156 // Instead of using the Value, we use the virtual register instead. 7157 Entry.Node = 7158 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7159 EVT(TLI.getPointerTy(DL))); 7160 } 7161 7162 Args.push_back(Entry); 7163 7164 // If we have an explicit sret argument that is an Instruction, (i.e., it 7165 // might point to function-local memory), we can't meaningfully tail-call. 7166 if (Entry.IsSRet && isa<Instruction>(V)) 7167 isTailCall = false; 7168 } 7169 7170 // If call site has a cfguardtarget operand bundle, create and add an 7171 // additional ArgListEntry. 7172 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7173 TargetLowering::ArgListEntry Entry; 7174 Value *V = Bundle->Inputs[0]; 7175 SDValue ArgNode = getValue(V); 7176 Entry.Node = ArgNode; 7177 Entry.Ty = V->getType(); 7178 Entry.IsCFGuardTarget = true; 7179 Args.push_back(Entry); 7180 } 7181 7182 // Check if target-independent constraints permit a tail call here. 7183 // Target-dependent constraints are checked within TLI->LowerCallTo. 7184 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7185 isTailCall = false; 7186 7187 // Disable tail calls if there is an swifterror argument. Targets have not 7188 // been updated to support tail calls. 7189 if (TLI.supportSwiftError() && SwiftErrorVal) 7190 isTailCall = false; 7191 7192 TargetLowering::CallLoweringInfo CLI(DAG); 7193 CLI.setDebugLoc(getCurSDLoc()) 7194 .setChain(getRoot()) 7195 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7196 .setTailCall(isTailCall) 7197 .setConvergent(CB.isConvergent()) 7198 .setIsPreallocated( 7199 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7200 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7201 7202 if (Result.first.getNode()) { 7203 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7204 setValue(&CB, Result.first); 7205 } 7206 7207 // The last element of CLI.InVals has the SDValue for swifterror return. 7208 // Here we copy it to a virtual register and update SwiftErrorMap for 7209 // book-keeping. 7210 if (SwiftErrorVal && TLI.supportSwiftError()) { 7211 // Get the last element of InVals. 7212 SDValue Src = CLI.InVals.back(); 7213 Register VReg = 7214 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7215 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7216 DAG.setRoot(CopyNode); 7217 } 7218 } 7219 7220 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7221 SelectionDAGBuilder &Builder) { 7222 // Check to see if this load can be trivially constant folded, e.g. if the 7223 // input is from a string literal. 7224 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7225 // Cast pointer to the type we really want to load. 7226 Type *LoadTy = 7227 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7228 if (LoadVT.isVector()) 7229 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7230 7231 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7232 PointerType::getUnqual(LoadTy)); 7233 7234 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7235 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7236 return Builder.getValue(LoadCst); 7237 } 7238 7239 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7240 // still constant memory, the input chain can be the entry node. 7241 SDValue Root; 7242 bool ConstantMemory = false; 7243 7244 // Do not serialize (non-volatile) loads of constant memory with anything. 7245 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7246 Root = Builder.DAG.getEntryNode(); 7247 ConstantMemory = true; 7248 } else { 7249 // Do not serialize non-volatile loads against each other. 7250 Root = Builder.DAG.getRoot(); 7251 } 7252 7253 SDValue Ptr = Builder.getValue(PtrVal); 7254 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7255 Ptr, MachinePointerInfo(PtrVal), 7256 /* Alignment = */ 1); 7257 7258 if (!ConstantMemory) 7259 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7260 return LoadVal; 7261 } 7262 7263 /// Record the value for an instruction that produces an integer result, 7264 /// converting the type where necessary. 7265 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7266 SDValue Value, 7267 bool IsSigned) { 7268 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7269 I.getType(), true); 7270 if (IsSigned) 7271 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7272 else 7273 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7274 setValue(&I, Value); 7275 } 7276 7277 /// See if we can lower a memcmp call into an optimized form. If so, return 7278 /// true and lower it. Otherwise return false, and it will be lowered like a 7279 /// normal call. 7280 /// The caller already checked that \p I calls the appropriate LibFunc with a 7281 /// correct prototype. 7282 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7283 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7284 const Value *Size = I.getArgOperand(2); 7285 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7286 if (CSize && CSize->getZExtValue() == 0) { 7287 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7288 I.getType(), true); 7289 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7290 return true; 7291 } 7292 7293 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7294 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7295 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7296 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7297 if (Res.first.getNode()) { 7298 processIntegerCallValue(I, Res.first, true); 7299 PendingLoads.push_back(Res.second); 7300 return true; 7301 } 7302 7303 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7304 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7305 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7306 return false; 7307 7308 // If the target has a fast compare for the given size, it will return a 7309 // preferred load type for that size. Require that the load VT is legal and 7310 // that the target supports unaligned loads of that type. Otherwise, return 7311 // INVALID. 7312 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7313 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7314 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7315 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7316 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7317 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7318 // TODO: Check alignment of src and dest ptrs. 7319 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7320 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7321 if (!TLI.isTypeLegal(LVT) || 7322 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7323 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7324 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7325 } 7326 7327 return LVT; 7328 }; 7329 7330 // This turns into unaligned loads. We only do this if the target natively 7331 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7332 // we'll only produce a small number of byte loads. 7333 MVT LoadVT; 7334 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7335 switch (NumBitsToCompare) { 7336 default: 7337 return false; 7338 case 16: 7339 LoadVT = MVT::i16; 7340 break; 7341 case 32: 7342 LoadVT = MVT::i32; 7343 break; 7344 case 64: 7345 case 128: 7346 case 256: 7347 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7348 break; 7349 } 7350 7351 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7352 return false; 7353 7354 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7355 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7356 7357 // Bitcast to a wide integer type if the loads are vectors. 7358 if (LoadVT.isVector()) { 7359 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7360 LoadL = DAG.getBitcast(CmpVT, LoadL); 7361 LoadR = DAG.getBitcast(CmpVT, LoadR); 7362 } 7363 7364 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7365 processIntegerCallValue(I, Cmp, false); 7366 return true; 7367 } 7368 7369 /// See if we can lower a memchr call into an optimized form. If so, return 7370 /// true and lower it. Otherwise return false, and it will be lowered like a 7371 /// normal call. 7372 /// The caller already checked that \p I calls the appropriate LibFunc with a 7373 /// correct prototype. 7374 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7375 const Value *Src = I.getArgOperand(0); 7376 const Value *Char = I.getArgOperand(1); 7377 const Value *Length = I.getArgOperand(2); 7378 7379 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7380 std::pair<SDValue, SDValue> Res = 7381 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7382 getValue(Src), getValue(Char), getValue(Length), 7383 MachinePointerInfo(Src)); 7384 if (Res.first.getNode()) { 7385 setValue(&I, Res.first); 7386 PendingLoads.push_back(Res.second); 7387 return true; 7388 } 7389 7390 return false; 7391 } 7392 7393 /// See if we can lower a mempcpy call into an optimized form. If so, return 7394 /// true and lower it. Otherwise return false, and it will be lowered like a 7395 /// normal call. 7396 /// The caller already checked that \p I calls the appropriate LibFunc with a 7397 /// correct prototype. 7398 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7399 SDValue Dst = getValue(I.getArgOperand(0)); 7400 SDValue Src = getValue(I.getArgOperand(1)); 7401 SDValue Size = getValue(I.getArgOperand(2)); 7402 7403 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7404 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7405 // DAG::getMemcpy needs Alignment to be defined. 7406 Align Alignment = std::min(DstAlign, SrcAlign); 7407 7408 bool isVol = false; 7409 SDLoc sdl = getCurSDLoc(); 7410 7411 // In the mempcpy context we need to pass in a false value for isTailCall 7412 // because the return pointer needs to be adjusted by the size of 7413 // the copied memory. 7414 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7415 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7416 /*isTailCall=*/false, 7417 MachinePointerInfo(I.getArgOperand(0)), 7418 MachinePointerInfo(I.getArgOperand(1))); 7419 assert(MC.getNode() != nullptr && 7420 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7421 DAG.setRoot(MC); 7422 7423 // Check if Size needs to be truncated or extended. 7424 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7425 7426 // Adjust return pointer to point just past the last dst byte. 7427 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7428 Dst, Size); 7429 setValue(&I, DstPlusSize); 7430 return true; 7431 } 7432 7433 /// See if we can lower a strcpy call into an optimized form. If so, return 7434 /// true and lower it, otherwise return false and it will be lowered like a 7435 /// normal call. 7436 /// The caller already checked that \p I calls the appropriate LibFunc with a 7437 /// correct prototype. 7438 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7439 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7440 7441 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7442 std::pair<SDValue, SDValue> Res = 7443 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7444 getValue(Arg0), getValue(Arg1), 7445 MachinePointerInfo(Arg0), 7446 MachinePointerInfo(Arg1), isStpcpy); 7447 if (Res.first.getNode()) { 7448 setValue(&I, Res.first); 7449 DAG.setRoot(Res.second); 7450 return true; 7451 } 7452 7453 return false; 7454 } 7455 7456 /// See if we can lower a strcmp call into an optimized form. If so, return 7457 /// true and lower it, otherwise return false and it will be lowered like a 7458 /// normal call. 7459 /// The caller already checked that \p I calls the appropriate LibFunc with a 7460 /// correct prototype. 7461 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7462 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7463 7464 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7465 std::pair<SDValue, SDValue> Res = 7466 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7467 getValue(Arg0), getValue(Arg1), 7468 MachinePointerInfo(Arg0), 7469 MachinePointerInfo(Arg1)); 7470 if (Res.first.getNode()) { 7471 processIntegerCallValue(I, Res.first, true); 7472 PendingLoads.push_back(Res.second); 7473 return true; 7474 } 7475 7476 return false; 7477 } 7478 7479 /// See if we can lower a strlen call into an optimized form. If so, return 7480 /// true and lower it, otherwise return false and it will be lowered like a 7481 /// normal call. 7482 /// The caller already checked that \p I calls the appropriate LibFunc with a 7483 /// correct prototype. 7484 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7485 const Value *Arg0 = I.getArgOperand(0); 7486 7487 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7488 std::pair<SDValue, SDValue> Res = 7489 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7490 getValue(Arg0), MachinePointerInfo(Arg0)); 7491 if (Res.first.getNode()) { 7492 processIntegerCallValue(I, Res.first, false); 7493 PendingLoads.push_back(Res.second); 7494 return true; 7495 } 7496 7497 return false; 7498 } 7499 7500 /// See if we can lower a strnlen call into an optimized form. If so, return 7501 /// true and lower it, otherwise return false and it will be lowered like a 7502 /// normal call. 7503 /// The caller already checked that \p I calls the appropriate LibFunc with a 7504 /// correct prototype. 7505 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7506 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7507 7508 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7509 std::pair<SDValue, SDValue> Res = 7510 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7511 getValue(Arg0), getValue(Arg1), 7512 MachinePointerInfo(Arg0)); 7513 if (Res.first.getNode()) { 7514 processIntegerCallValue(I, Res.first, false); 7515 PendingLoads.push_back(Res.second); 7516 return true; 7517 } 7518 7519 return false; 7520 } 7521 7522 /// See if we can lower a unary floating-point operation into an SDNode with 7523 /// the specified Opcode. If so, return true and lower it, otherwise return 7524 /// false and it will be lowered like a normal call. 7525 /// The caller already checked that \p I calls the appropriate LibFunc with a 7526 /// correct prototype. 7527 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7528 unsigned Opcode) { 7529 // We already checked this call's prototype; verify it doesn't modify errno. 7530 if (!I.onlyReadsMemory()) 7531 return false; 7532 7533 SDValue Tmp = getValue(I.getArgOperand(0)); 7534 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7535 return true; 7536 } 7537 7538 /// See if we can lower a binary floating-point operation into an SDNode with 7539 /// the specified Opcode. If so, return true and lower it. Otherwise return 7540 /// false, and it will be lowered like a normal call. 7541 /// The caller already checked that \p I calls the appropriate LibFunc with a 7542 /// correct prototype. 7543 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7544 unsigned Opcode) { 7545 // We already checked this call's prototype; verify it doesn't modify errno. 7546 if (!I.onlyReadsMemory()) 7547 return false; 7548 7549 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7550 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7551 EVT VT = Tmp0.getValueType(); 7552 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7553 return true; 7554 } 7555 7556 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7557 // Handle inline assembly differently. 7558 if (I.isInlineAsm()) { 7559 visitInlineAsm(I); 7560 return; 7561 } 7562 7563 if (Function *F = I.getCalledFunction()) { 7564 if (F->isDeclaration()) { 7565 // Is this an LLVM intrinsic or a target-specific intrinsic? 7566 unsigned IID = F->getIntrinsicID(); 7567 if (!IID) 7568 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7569 IID = II->getIntrinsicID(F); 7570 7571 if (IID) { 7572 visitIntrinsicCall(I, IID); 7573 return; 7574 } 7575 } 7576 7577 // Check for well-known libc/libm calls. If the function is internal, it 7578 // can't be a library call. Don't do the check if marked as nobuiltin for 7579 // some reason or the call site requires strict floating point semantics. 7580 LibFunc Func; 7581 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7582 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7583 LibInfo->hasOptimizedCodeGen(Func)) { 7584 switch (Func) { 7585 default: break; 7586 case LibFunc_copysign: 7587 case LibFunc_copysignf: 7588 case LibFunc_copysignl: 7589 // We already checked this call's prototype; verify it doesn't modify 7590 // errno. 7591 if (I.onlyReadsMemory()) { 7592 SDValue LHS = getValue(I.getArgOperand(0)); 7593 SDValue RHS = getValue(I.getArgOperand(1)); 7594 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7595 LHS.getValueType(), LHS, RHS)); 7596 return; 7597 } 7598 break; 7599 case LibFunc_fabs: 7600 case LibFunc_fabsf: 7601 case LibFunc_fabsl: 7602 if (visitUnaryFloatCall(I, ISD::FABS)) 7603 return; 7604 break; 7605 case LibFunc_fmin: 7606 case LibFunc_fminf: 7607 case LibFunc_fminl: 7608 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7609 return; 7610 break; 7611 case LibFunc_fmax: 7612 case LibFunc_fmaxf: 7613 case LibFunc_fmaxl: 7614 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7615 return; 7616 break; 7617 case LibFunc_sin: 7618 case LibFunc_sinf: 7619 case LibFunc_sinl: 7620 if (visitUnaryFloatCall(I, ISD::FSIN)) 7621 return; 7622 break; 7623 case LibFunc_cos: 7624 case LibFunc_cosf: 7625 case LibFunc_cosl: 7626 if (visitUnaryFloatCall(I, ISD::FCOS)) 7627 return; 7628 break; 7629 case LibFunc_sqrt: 7630 case LibFunc_sqrtf: 7631 case LibFunc_sqrtl: 7632 case LibFunc_sqrt_finite: 7633 case LibFunc_sqrtf_finite: 7634 case LibFunc_sqrtl_finite: 7635 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7636 return; 7637 break; 7638 case LibFunc_floor: 7639 case LibFunc_floorf: 7640 case LibFunc_floorl: 7641 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7642 return; 7643 break; 7644 case LibFunc_nearbyint: 7645 case LibFunc_nearbyintf: 7646 case LibFunc_nearbyintl: 7647 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7648 return; 7649 break; 7650 case LibFunc_ceil: 7651 case LibFunc_ceilf: 7652 case LibFunc_ceill: 7653 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7654 return; 7655 break; 7656 case LibFunc_rint: 7657 case LibFunc_rintf: 7658 case LibFunc_rintl: 7659 if (visitUnaryFloatCall(I, ISD::FRINT)) 7660 return; 7661 break; 7662 case LibFunc_round: 7663 case LibFunc_roundf: 7664 case LibFunc_roundl: 7665 if (visitUnaryFloatCall(I, ISD::FROUND)) 7666 return; 7667 break; 7668 case LibFunc_trunc: 7669 case LibFunc_truncf: 7670 case LibFunc_truncl: 7671 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7672 return; 7673 break; 7674 case LibFunc_log2: 7675 case LibFunc_log2f: 7676 case LibFunc_log2l: 7677 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7678 return; 7679 break; 7680 case LibFunc_exp2: 7681 case LibFunc_exp2f: 7682 case LibFunc_exp2l: 7683 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7684 return; 7685 break; 7686 case LibFunc_memcmp: 7687 if (visitMemCmpCall(I)) 7688 return; 7689 break; 7690 case LibFunc_mempcpy: 7691 if (visitMemPCpyCall(I)) 7692 return; 7693 break; 7694 case LibFunc_memchr: 7695 if (visitMemChrCall(I)) 7696 return; 7697 break; 7698 case LibFunc_strcpy: 7699 if (visitStrCpyCall(I, false)) 7700 return; 7701 break; 7702 case LibFunc_stpcpy: 7703 if (visitStrCpyCall(I, true)) 7704 return; 7705 break; 7706 case LibFunc_strcmp: 7707 if (visitStrCmpCall(I)) 7708 return; 7709 break; 7710 case LibFunc_strlen: 7711 if (visitStrLenCall(I)) 7712 return; 7713 break; 7714 case LibFunc_strnlen: 7715 if (visitStrNLenCall(I)) 7716 return; 7717 break; 7718 } 7719 } 7720 } 7721 7722 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7723 // have to do anything here to lower funclet bundles. 7724 // CFGuardTarget bundles are lowered in LowerCallTo. 7725 assert(!I.hasOperandBundlesOtherThan( 7726 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7727 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) && 7728 "Cannot lower calls with arbitrary operand bundles!"); 7729 7730 SDValue Callee = getValue(I.getCalledOperand()); 7731 7732 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7733 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7734 else 7735 // Check if we can potentially perform a tail call. More detailed checking 7736 // is be done within LowerCallTo, after more information about the call is 7737 // known. 7738 LowerCallTo(I, Callee, I.isTailCall()); 7739 } 7740 7741 namespace { 7742 7743 /// AsmOperandInfo - This contains information for each constraint that we are 7744 /// lowering. 7745 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7746 public: 7747 /// CallOperand - If this is the result output operand or a clobber 7748 /// this is null, otherwise it is the incoming operand to the CallInst. 7749 /// This gets modified as the asm is processed. 7750 SDValue CallOperand; 7751 7752 /// AssignedRegs - If this is a register or register class operand, this 7753 /// contains the set of register corresponding to the operand. 7754 RegsForValue AssignedRegs; 7755 7756 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7757 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7758 } 7759 7760 /// Whether or not this operand accesses memory 7761 bool hasMemory(const TargetLowering &TLI) const { 7762 // Indirect operand accesses access memory. 7763 if (isIndirect) 7764 return true; 7765 7766 for (const auto &Code : Codes) 7767 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7768 return true; 7769 7770 return false; 7771 } 7772 7773 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7774 /// corresponds to. If there is no Value* for this operand, it returns 7775 /// MVT::Other. 7776 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7777 const DataLayout &DL) const { 7778 if (!CallOperandVal) return MVT::Other; 7779 7780 if (isa<BasicBlock>(CallOperandVal)) 7781 return TLI.getProgramPointerTy(DL); 7782 7783 llvm::Type *OpTy = CallOperandVal->getType(); 7784 7785 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7786 // If this is an indirect operand, the operand is a pointer to the 7787 // accessed type. 7788 if (isIndirect) { 7789 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7790 if (!PtrTy) 7791 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7792 OpTy = PtrTy->getElementType(); 7793 } 7794 7795 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7796 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7797 if (STy->getNumElements() == 1) 7798 OpTy = STy->getElementType(0); 7799 7800 // If OpTy is not a single value, it may be a struct/union that we 7801 // can tile with integers. 7802 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7803 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7804 switch (BitSize) { 7805 default: break; 7806 case 1: 7807 case 8: 7808 case 16: 7809 case 32: 7810 case 64: 7811 case 128: 7812 OpTy = IntegerType::get(Context, BitSize); 7813 break; 7814 } 7815 } 7816 7817 return TLI.getValueType(DL, OpTy, true); 7818 } 7819 }; 7820 7821 7822 } // end anonymous namespace 7823 7824 /// Make sure that the output operand \p OpInfo and its corresponding input 7825 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7826 /// out). 7827 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7828 SDISelAsmOperandInfo &MatchingOpInfo, 7829 SelectionDAG &DAG) { 7830 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7831 return; 7832 7833 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7834 const auto &TLI = DAG.getTargetLoweringInfo(); 7835 7836 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7837 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7838 OpInfo.ConstraintVT); 7839 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7840 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7841 MatchingOpInfo.ConstraintVT); 7842 if ((OpInfo.ConstraintVT.isInteger() != 7843 MatchingOpInfo.ConstraintVT.isInteger()) || 7844 (MatchRC.second != InputRC.second)) { 7845 // FIXME: error out in a more elegant fashion 7846 report_fatal_error("Unsupported asm: input constraint" 7847 " with a matching output constraint of" 7848 " incompatible type!"); 7849 } 7850 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7851 } 7852 7853 /// Get a direct memory input to behave well as an indirect operand. 7854 /// This may introduce stores, hence the need for a \p Chain. 7855 /// \return The (possibly updated) chain. 7856 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7857 SDISelAsmOperandInfo &OpInfo, 7858 SelectionDAG &DAG) { 7859 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7860 7861 // If we don't have an indirect input, put it in the constpool if we can, 7862 // otherwise spill it to a stack slot. 7863 // TODO: This isn't quite right. We need to handle these according to 7864 // the addressing mode that the constraint wants. Also, this may take 7865 // an additional register for the computation and we don't want that 7866 // either. 7867 7868 // If the operand is a float, integer, or vector constant, spill to a 7869 // constant pool entry to get its address. 7870 const Value *OpVal = OpInfo.CallOperandVal; 7871 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7872 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7873 OpInfo.CallOperand = DAG.getConstantPool( 7874 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7875 return Chain; 7876 } 7877 7878 // Otherwise, create a stack slot and emit a store to it before the asm. 7879 Type *Ty = OpVal->getType(); 7880 auto &DL = DAG.getDataLayout(); 7881 uint64_t TySize = DL.getTypeAllocSize(Ty); 7882 MachineFunction &MF = DAG.getMachineFunction(); 7883 int SSFI = MF.getFrameInfo().CreateStackObject( 7884 TySize, DL.getPrefTypeAlign(Ty), false); 7885 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7886 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7887 MachinePointerInfo::getFixedStack(MF, SSFI), 7888 TLI.getMemValueType(DL, Ty)); 7889 OpInfo.CallOperand = StackSlot; 7890 7891 return Chain; 7892 } 7893 7894 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7895 /// specified operand. We prefer to assign virtual registers, to allow the 7896 /// register allocator to handle the assignment process. However, if the asm 7897 /// uses features that we can't model on machineinstrs, we have SDISel do the 7898 /// allocation. This produces generally horrible, but correct, code. 7899 /// 7900 /// OpInfo describes the operand 7901 /// RefOpInfo describes the matching operand if any, the operand otherwise 7902 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7903 SDISelAsmOperandInfo &OpInfo, 7904 SDISelAsmOperandInfo &RefOpInfo) { 7905 LLVMContext &Context = *DAG.getContext(); 7906 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7907 7908 MachineFunction &MF = DAG.getMachineFunction(); 7909 SmallVector<unsigned, 4> Regs; 7910 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7911 7912 // No work to do for memory operations. 7913 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7914 return; 7915 7916 // If this is a constraint for a single physreg, or a constraint for a 7917 // register class, find it. 7918 unsigned AssignedReg; 7919 const TargetRegisterClass *RC; 7920 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7921 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7922 // RC is unset only on failure. Return immediately. 7923 if (!RC) 7924 return; 7925 7926 // Get the actual register value type. This is important, because the user 7927 // may have asked for (e.g.) the AX register in i32 type. We need to 7928 // remember that AX is actually i16 to get the right extension. 7929 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7930 7931 if (OpInfo.ConstraintVT != MVT::Other) { 7932 // If this is an FP operand in an integer register (or visa versa), or more 7933 // generally if the operand value disagrees with the register class we plan 7934 // to stick it in, fix the operand type. 7935 // 7936 // If this is an input value, the bitcast to the new type is done now. 7937 // Bitcast for output value is done at the end of visitInlineAsm(). 7938 if ((OpInfo.Type == InlineAsm::isOutput || 7939 OpInfo.Type == InlineAsm::isInput) && 7940 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7941 // Try to convert to the first EVT that the reg class contains. If the 7942 // types are identical size, use a bitcast to convert (e.g. two differing 7943 // vector types). Note: output bitcast is done at the end of 7944 // visitInlineAsm(). 7945 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7946 // Exclude indirect inputs while they are unsupported because the code 7947 // to perform the load is missing and thus OpInfo.CallOperand still 7948 // refers to the input address rather than the pointed-to value. 7949 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7950 OpInfo.CallOperand = 7951 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7952 OpInfo.ConstraintVT = RegVT; 7953 // If the operand is an FP value and we want it in integer registers, 7954 // use the corresponding integer type. This turns an f64 value into 7955 // i64, which can be passed with two i32 values on a 32-bit machine. 7956 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7957 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7958 if (OpInfo.Type == InlineAsm::isInput) 7959 OpInfo.CallOperand = 7960 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7961 OpInfo.ConstraintVT = VT; 7962 } 7963 } 7964 } 7965 7966 // No need to allocate a matching input constraint since the constraint it's 7967 // matching to has already been allocated. 7968 if (OpInfo.isMatchingInputConstraint()) 7969 return; 7970 7971 EVT ValueVT = OpInfo.ConstraintVT; 7972 if (OpInfo.ConstraintVT == MVT::Other) 7973 ValueVT = RegVT; 7974 7975 // Initialize NumRegs. 7976 unsigned NumRegs = 1; 7977 if (OpInfo.ConstraintVT != MVT::Other) 7978 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7979 7980 // If this is a constraint for a specific physical register, like {r17}, 7981 // assign it now. 7982 7983 // If this associated to a specific register, initialize iterator to correct 7984 // place. If virtual, make sure we have enough registers 7985 7986 // Initialize iterator if necessary 7987 TargetRegisterClass::iterator I = RC->begin(); 7988 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7989 7990 // Do not check for single registers. 7991 if (AssignedReg) { 7992 for (; *I != AssignedReg; ++I) 7993 assert(I != RC->end() && "AssignedReg should be member of RC"); 7994 } 7995 7996 for (; NumRegs; --NumRegs, ++I) { 7997 assert(I != RC->end() && "Ran out of registers to allocate!"); 7998 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7999 Regs.push_back(R); 8000 } 8001 8002 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8003 } 8004 8005 static unsigned 8006 findMatchingInlineAsmOperand(unsigned OperandNo, 8007 const std::vector<SDValue> &AsmNodeOperands) { 8008 // Scan until we find the definition we already emitted of this operand. 8009 unsigned CurOp = InlineAsm::Op_FirstOperand; 8010 for (; OperandNo; --OperandNo) { 8011 // Advance to the next operand. 8012 unsigned OpFlag = 8013 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8014 assert((InlineAsm::isRegDefKind(OpFlag) || 8015 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8016 InlineAsm::isMemKind(OpFlag)) && 8017 "Skipped past definitions?"); 8018 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8019 } 8020 return CurOp; 8021 } 8022 8023 namespace { 8024 8025 class ExtraFlags { 8026 unsigned Flags = 0; 8027 8028 public: 8029 explicit ExtraFlags(const CallBase &Call) { 8030 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8031 if (IA->hasSideEffects()) 8032 Flags |= InlineAsm::Extra_HasSideEffects; 8033 if (IA->isAlignStack()) 8034 Flags |= InlineAsm::Extra_IsAlignStack; 8035 if (Call.isConvergent()) 8036 Flags |= InlineAsm::Extra_IsConvergent; 8037 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8038 } 8039 8040 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8041 // Ideally, we would only check against memory constraints. However, the 8042 // meaning of an Other constraint can be target-specific and we can't easily 8043 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8044 // for Other constraints as well. 8045 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8046 OpInfo.ConstraintType == TargetLowering::C_Other) { 8047 if (OpInfo.Type == InlineAsm::isInput) 8048 Flags |= InlineAsm::Extra_MayLoad; 8049 else if (OpInfo.Type == InlineAsm::isOutput) 8050 Flags |= InlineAsm::Extra_MayStore; 8051 else if (OpInfo.Type == InlineAsm::isClobber) 8052 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8053 } 8054 } 8055 8056 unsigned get() const { return Flags; } 8057 }; 8058 8059 } // end anonymous namespace 8060 8061 /// visitInlineAsm - Handle a call to an InlineAsm object. 8062 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8063 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8064 8065 /// ConstraintOperands - Information about all of the constraints. 8066 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8067 8068 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8069 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8070 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8071 8072 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8073 // AsmDialect, MayLoad, MayStore). 8074 bool HasSideEffect = IA->hasSideEffects(); 8075 ExtraFlags ExtraInfo(Call); 8076 8077 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8078 unsigned ResNo = 0; // ResNo - The result number of the next output. 8079 unsigned NumMatchingOps = 0; 8080 for (auto &T : TargetConstraints) { 8081 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8082 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8083 8084 // Compute the value type for each operand. 8085 if (OpInfo.Type == InlineAsm::isInput || 8086 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8087 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8088 8089 // Process the call argument. BasicBlocks are labels, currently appearing 8090 // only in asm's. 8091 if (isa<CallBrInst>(Call) && 8092 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8093 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8094 NumMatchingOps) && 8095 (NumMatchingOps == 0 || 8096 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8097 NumMatchingOps))) { 8098 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8099 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8100 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8101 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8102 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8103 } else { 8104 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8105 } 8106 8107 OpInfo.ConstraintVT = 8108 OpInfo 8109 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8110 .getSimpleVT(); 8111 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8112 // The return value of the call is this value. As such, there is no 8113 // corresponding argument. 8114 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8115 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8116 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8117 DAG.getDataLayout(), STy->getElementType(ResNo)); 8118 } else { 8119 assert(ResNo == 0 && "Asm only has one result!"); 8120 OpInfo.ConstraintVT = 8121 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8122 } 8123 ++ResNo; 8124 } else { 8125 OpInfo.ConstraintVT = MVT::Other; 8126 } 8127 8128 if (OpInfo.hasMatchingInput()) 8129 ++NumMatchingOps; 8130 8131 if (!HasSideEffect) 8132 HasSideEffect = OpInfo.hasMemory(TLI); 8133 8134 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8135 // FIXME: Could we compute this on OpInfo rather than T? 8136 8137 // Compute the constraint code and ConstraintType to use. 8138 TLI.ComputeConstraintToUse(T, SDValue()); 8139 8140 if (T.ConstraintType == TargetLowering::C_Immediate && 8141 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8142 // We've delayed emitting a diagnostic like the "n" constraint because 8143 // inlining could cause an integer showing up. 8144 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8145 "' expects an integer constant " 8146 "expression"); 8147 8148 ExtraInfo.update(T); 8149 } 8150 8151 8152 // We won't need to flush pending loads if this asm doesn't touch 8153 // memory and is nonvolatile. 8154 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8155 8156 bool IsCallBr = isa<CallBrInst>(Call); 8157 if (IsCallBr) { 8158 // If this is a callbr we need to flush pending exports since inlineasm_br 8159 // is a terminator. We need to do this before nodes are glued to 8160 // the inlineasm_br node. 8161 Chain = getControlRoot(); 8162 } 8163 8164 // Second pass over the constraints: compute which constraint option to use. 8165 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8166 // If this is an output operand with a matching input operand, look up the 8167 // matching input. If their types mismatch, e.g. one is an integer, the 8168 // other is floating point, or their sizes are different, flag it as an 8169 // error. 8170 if (OpInfo.hasMatchingInput()) { 8171 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8172 patchMatchingInput(OpInfo, Input, DAG); 8173 } 8174 8175 // Compute the constraint code and ConstraintType to use. 8176 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8177 8178 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8179 OpInfo.Type == InlineAsm::isClobber) 8180 continue; 8181 8182 // If this is a memory input, and if the operand is not indirect, do what we 8183 // need to provide an address for the memory input. 8184 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8185 !OpInfo.isIndirect) { 8186 assert((OpInfo.isMultipleAlternative || 8187 (OpInfo.Type == InlineAsm::isInput)) && 8188 "Can only indirectify direct input operands!"); 8189 8190 // Memory operands really want the address of the value. 8191 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8192 8193 // There is no longer a Value* corresponding to this operand. 8194 OpInfo.CallOperandVal = nullptr; 8195 8196 // It is now an indirect operand. 8197 OpInfo.isIndirect = true; 8198 } 8199 8200 } 8201 8202 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8203 std::vector<SDValue> AsmNodeOperands; 8204 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8205 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8206 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8207 8208 // If we have a !srcloc metadata node associated with it, we want to attach 8209 // this to the ultimately generated inline asm machineinstr. To do this, we 8210 // pass in the third operand as this (potentially null) inline asm MDNode. 8211 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8212 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8213 8214 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8215 // bits as operand 3. 8216 AsmNodeOperands.push_back(DAG.getTargetConstant( 8217 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8218 8219 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8220 // this, assign virtual and physical registers for inputs and otput. 8221 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8222 // Assign Registers. 8223 SDISelAsmOperandInfo &RefOpInfo = 8224 OpInfo.isMatchingInputConstraint() 8225 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8226 : OpInfo; 8227 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8228 8229 auto DetectWriteToReservedRegister = [&]() { 8230 const MachineFunction &MF = DAG.getMachineFunction(); 8231 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8232 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8233 if (Register::isPhysicalRegister(Reg) && 8234 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8235 const char *RegName = TRI.getName(Reg); 8236 emitInlineAsmError(Call, "write to reserved register '" + 8237 Twine(RegName) + "'"); 8238 return true; 8239 } 8240 } 8241 return false; 8242 }; 8243 8244 switch (OpInfo.Type) { 8245 case InlineAsm::isOutput: 8246 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8247 unsigned ConstraintID = 8248 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8249 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8250 "Failed to convert memory constraint code to constraint id."); 8251 8252 // Add information to the INLINEASM node to know about this output. 8253 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8254 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8255 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8256 MVT::i32)); 8257 AsmNodeOperands.push_back(OpInfo.CallOperand); 8258 } else { 8259 // Otherwise, this outputs to a register (directly for C_Register / 8260 // C_RegisterClass, and a target-defined fashion for 8261 // C_Immediate/C_Other). Find a register that we can use. 8262 if (OpInfo.AssignedRegs.Regs.empty()) { 8263 emitInlineAsmError( 8264 Call, "couldn't allocate output register for constraint '" + 8265 Twine(OpInfo.ConstraintCode) + "'"); 8266 return; 8267 } 8268 8269 if (DetectWriteToReservedRegister()) 8270 return; 8271 8272 // Add information to the INLINEASM node to know that this register is 8273 // set. 8274 OpInfo.AssignedRegs.AddInlineAsmOperands( 8275 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8276 : InlineAsm::Kind_RegDef, 8277 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8278 } 8279 break; 8280 8281 case InlineAsm::isInput: { 8282 SDValue InOperandVal = OpInfo.CallOperand; 8283 8284 if (OpInfo.isMatchingInputConstraint()) { 8285 // If this is required to match an output register we have already set, 8286 // just use its register. 8287 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8288 AsmNodeOperands); 8289 unsigned OpFlag = 8290 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8291 if (InlineAsm::isRegDefKind(OpFlag) || 8292 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8293 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8294 if (OpInfo.isIndirect) { 8295 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8296 emitInlineAsmError(Call, "inline asm not supported yet: " 8297 "don't know how to handle tied " 8298 "indirect register inputs"); 8299 return; 8300 } 8301 8302 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8303 SmallVector<unsigned, 4> Regs; 8304 8305 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8306 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8307 MachineRegisterInfo &RegInfo = 8308 DAG.getMachineFunction().getRegInfo(); 8309 for (unsigned i = 0; i != NumRegs; ++i) 8310 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8311 } else { 8312 emitInlineAsmError(Call, 8313 "inline asm error: This value type register " 8314 "class is not natively supported!"); 8315 return; 8316 } 8317 8318 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8319 8320 SDLoc dl = getCurSDLoc(); 8321 // Use the produced MatchedRegs object to 8322 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8323 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8324 true, OpInfo.getMatchedOperand(), dl, 8325 DAG, AsmNodeOperands); 8326 break; 8327 } 8328 8329 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8330 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8331 "Unexpected number of operands"); 8332 // Add information to the INLINEASM node to know about this input. 8333 // See InlineAsm.h isUseOperandTiedToDef. 8334 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8335 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8336 OpInfo.getMatchedOperand()); 8337 AsmNodeOperands.push_back(DAG.getTargetConstant( 8338 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8339 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8340 break; 8341 } 8342 8343 // Treat indirect 'X' constraint as memory. 8344 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8345 OpInfo.isIndirect) 8346 OpInfo.ConstraintType = TargetLowering::C_Memory; 8347 8348 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8349 OpInfo.ConstraintType == TargetLowering::C_Other) { 8350 std::vector<SDValue> Ops; 8351 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8352 Ops, DAG); 8353 if (Ops.empty()) { 8354 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8355 if (isa<ConstantSDNode>(InOperandVal)) { 8356 emitInlineAsmError(Call, "value out of range for constraint '" + 8357 Twine(OpInfo.ConstraintCode) + "'"); 8358 return; 8359 } 8360 8361 emitInlineAsmError(Call, 8362 "invalid operand for inline asm constraint '" + 8363 Twine(OpInfo.ConstraintCode) + "'"); 8364 return; 8365 } 8366 8367 // Add information to the INLINEASM node to know about this input. 8368 unsigned ResOpType = 8369 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8370 AsmNodeOperands.push_back(DAG.getTargetConstant( 8371 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8372 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8373 break; 8374 } 8375 8376 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8377 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8378 assert(InOperandVal.getValueType() == 8379 TLI.getPointerTy(DAG.getDataLayout()) && 8380 "Memory operands expect pointer values"); 8381 8382 unsigned ConstraintID = 8383 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8384 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8385 "Failed to convert memory constraint code to constraint id."); 8386 8387 // Add information to the INLINEASM node to know about this input. 8388 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8389 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8390 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8391 getCurSDLoc(), 8392 MVT::i32)); 8393 AsmNodeOperands.push_back(InOperandVal); 8394 break; 8395 } 8396 8397 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8398 OpInfo.ConstraintType == TargetLowering::C_Register) && 8399 "Unknown constraint type!"); 8400 8401 // TODO: Support this. 8402 if (OpInfo.isIndirect) { 8403 emitInlineAsmError( 8404 Call, "Don't know how to handle indirect register inputs yet " 8405 "for constraint '" + 8406 Twine(OpInfo.ConstraintCode) + "'"); 8407 return; 8408 } 8409 8410 // Copy the input into the appropriate registers. 8411 if (OpInfo.AssignedRegs.Regs.empty()) { 8412 emitInlineAsmError(Call, 8413 "couldn't allocate input reg for constraint '" + 8414 Twine(OpInfo.ConstraintCode) + "'"); 8415 return; 8416 } 8417 8418 if (DetectWriteToReservedRegister()) 8419 return; 8420 8421 SDLoc dl = getCurSDLoc(); 8422 8423 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8424 &Call); 8425 8426 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8427 dl, DAG, AsmNodeOperands); 8428 break; 8429 } 8430 case InlineAsm::isClobber: 8431 // Add the clobbered value to the operand list, so that the register 8432 // allocator is aware that the physreg got clobbered. 8433 if (!OpInfo.AssignedRegs.Regs.empty()) 8434 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8435 false, 0, getCurSDLoc(), DAG, 8436 AsmNodeOperands); 8437 break; 8438 } 8439 } 8440 8441 // Finish up input operands. Set the input chain and add the flag last. 8442 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8443 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8444 8445 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8446 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8447 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8448 Flag = Chain.getValue(1); 8449 8450 // Do additional work to generate outputs. 8451 8452 SmallVector<EVT, 1> ResultVTs; 8453 SmallVector<SDValue, 1> ResultValues; 8454 SmallVector<SDValue, 8> OutChains; 8455 8456 llvm::Type *CallResultType = Call.getType(); 8457 ArrayRef<Type *> ResultTypes; 8458 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8459 ResultTypes = StructResult->elements(); 8460 else if (!CallResultType->isVoidTy()) 8461 ResultTypes = makeArrayRef(CallResultType); 8462 8463 auto CurResultType = ResultTypes.begin(); 8464 auto handleRegAssign = [&](SDValue V) { 8465 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8466 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8467 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8468 ++CurResultType; 8469 // If the type of the inline asm call site return value is different but has 8470 // same size as the type of the asm output bitcast it. One example of this 8471 // is for vectors with different width / number of elements. This can 8472 // happen for register classes that can contain multiple different value 8473 // types. The preg or vreg allocated may not have the same VT as was 8474 // expected. 8475 // 8476 // This can also happen for a return value that disagrees with the register 8477 // class it is put in, eg. a double in a general-purpose register on a 8478 // 32-bit machine. 8479 if (ResultVT != V.getValueType() && 8480 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8481 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8482 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8483 V.getValueType().isInteger()) { 8484 // If a result value was tied to an input value, the computed result 8485 // may have a wider width than the expected result. Extract the 8486 // relevant portion. 8487 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8488 } 8489 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8490 ResultVTs.push_back(ResultVT); 8491 ResultValues.push_back(V); 8492 }; 8493 8494 // Deal with output operands. 8495 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8496 if (OpInfo.Type == InlineAsm::isOutput) { 8497 SDValue Val; 8498 // Skip trivial output operands. 8499 if (OpInfo.AssignedRegs.Regs.empty()) 8500 continue; 8501 8502 switch (OpInfo.ConstraintType) { 8503 case TargetLowering::C_Register: 8504 case TargetLowering::C_RegisterClass: 8505 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8506 Chain, &Flag, &Call); 8507 break; 8508 case TargetLowering::C_Immediate: 8509 case TargetLowering::C_Other: 8510 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8511 OpInfo, DAG); 8512 break; 8513 case TargetLowering::C_Memory: 8514 break; // Already handled. 8515 case TargetLowering::C_Unknown: 8516 assert(false && "Unexpected unknown constraint"); 8517 } 8518 8519 // Indirect output manifest as stores. Record output chains. 8520 if (OpInfo.isIndirect) { 8521 const Value *Ptr = OpInfo.CallOperandVal; 8522 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8523 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8524 MachinePointerInfo(Ptr)); 8525 OutChains.push_back(Store); 8526 } else { 8527 // generate CopyFromRegs to associated registers. 8528 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8529 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8530 for (const SDValue &V : Val->op_values()) 8531 handleRegAssign(V); 8532 } else 8533 handleRegAssign(Val); 8534 } 8535 } 8536 } 8537 8538 // Set results. 8539 if (!ResultValues.empty()) { 8540 assert(CurResultType == ResultTypes.end() && 8541 "Mismatch in number of ResultTypes"); 8542 assert(ResultValues.size() == ResultTypes.size() && 8543 "Mismatch in number of output operands in asm result"); 8544 8545 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8546 DAG.getVTList(ResultVTs), ResultValues); 8547 setValue(&Call, V); 8548 } 8549 8550 // Collect store chains. 8551 if (!OutChains.empty()) 8552 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8553 8554 // Only Update Root if inline assembly has a memory effect. 8555 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8556 DAG.setRoot(Chain); 8557 } 8558 8559 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8560 const Twine &Message) { 8561 LLVMContext &Ctx = *DAG.getContext(); 8562 Ctx.emitError(&Call, Message); 8563 8564 // Make sure we leave the DAG in a valid state 8565 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8566 SmallVector<EVT, 1> ValueVTs; 8567 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8568 8569 if (ValueVTs.empty()) 8570 return; 8571 8572 SmallVector<SDValue, 1> Ops; 8573 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8574 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8575 8576 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8577 } 8578 8579 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8580 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8581 MVT::Other, getRoot(), 8582 getValue(I.getArgOperand(0)), 8583 DAG.getSrcValue(I.getArgOperand(0)))); 8584 } 8585 8586 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8587 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8588 const DataLayout &DL = DAG.getDataLayout(); 8589 SDValue V = DAG.getVAArg( 8590 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8591 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8592 DL.getABITypeAlign(I.getType()).value()); 8593 DAG.setRoot(V.getValue(1)); 8594 8595 if (I.getType()->isPointerTy()) 8596 V = DAG.getPtrExtOrTrunc( 8597 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8598 setValue(&I, V); 8599 } 8600 8601 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8602 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8603 MVT::Other, getRoot(), 8604 getValue(I.getArgOperand(0)), 8605 DAG.getSrcValue(I.getArgOperand(0)))); 8606 } 8607 8608 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8609 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8610 MVT::Other, getRoot(), 8611 getValue(I.getArgOperand(0)), 8612 getValue(I.getArgOperand(1)), 8613 DAG.getSrcValue(I.getArgOperand(0)), 8614 DAG.getSrcValue(I.getArgOperand(1)))); 8615 } 8616 8617 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8618 const Instruction &I, 8619 SDValue Op) { 8620 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8621 if (!Range) 8622 return Op; 8623 8624 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8625 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8626 return Op; 8627 8628 APInt Lo = CR.getUnsignedMin(); 8629 if (!Lo.isMinValue()) 8630 return Op; 8631 8632 APInt Hi = CR.getUnsignedMax(); 8633 unsigned Bits = std::max(Hi.getActiveBits(), 8634 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8635 8636 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8637 8638 SDLoc SL = getCurSDLoc(); 8639 8640 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8641 DAG.getValueType(SmallVT)); 8642 unsigned NumVals = Op.getNode()->getNumValues(); 8643 if (NumVals == 1) 8644 return ZExt; 8645 8646 SmallVector<SDValue, 4> Ops; 8647 8648 Ops.push_back(ZExt); 8649 for (unsigned I = 1; I != NumVals; ++I) 8650 Ops.push_back(Op.getValue(I)); 8651 8652 return DAG.getMergeValues(Ops, SL); 8653 } 8654 8655 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8656 /// the call being lowered. 8657 /// 8658 /// This is a helper for lowering intrinsics that follow a target calling 8659 /// convention or require stack pointer adjustment. Only a subset of the 8660 /// intrinsic's operands need to participate in the calling convention. 8661 void SelectionDAGBuilder::populateCallLoweringInfo( 8662 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8663 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8664 bool IsPatchPoint) { 8665 TargetLowering::ArgListTy Args; 8666 Args.reserve(NumArgs); 8667 8668 // Populate the argument list. 8669 // Attributes for args start at offset 1, after the return attribute. 8670 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8671 ArgI != ArgE; ++ArgI) { 8672 const Value *V = Call->getOperand(ArgI); 8673 8674 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8675 8676 TargetLowering::ArgListEntry Entry; 8677 Entry.Node = getValue(V); 8678 Entry.Ty = V->getType(); 8679 Entry.setAttributes(Call, ArgI); 8680 Args.push_back(Entry); 8681 } 8682 8683 CLI.setDebugLoc(getCurSDLoc()) 8684 .setChain(getRoot()) 8685 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8686 .setDiscardResult(Call->use_empty()) 8687 .setIsPatchPoint(IsPatchPoint) 8688 .setIsPreallocated( 8689 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8690 } 8691 8692 /// Add a stack map intrinsic call's live variable operands to a stackmap 8693 /// or patchpoint target node's operand list. 8694 /// 8695 /// Constants are converted to TargetConstants purely as an optimization to 8696 /// avoid constant materialization and register allocation. 8697 /// 8698 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8699 /// generate addess computation nodes, and so FinalizeISel can convert the 8700 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8701 /// address materialization and register allocation, but may also be required 8702 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8703 /// alloca in the entry block, then the runtime may assume that the alloca's 8704 /// StackMap location can be read immediately after compilation and that the 8705 /// location is valid at any point during execution (this is similar to the 8706 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8707 /// only available in a register, then the runtime would need to trap when 8708 /// execution reaches the StackMap in order to read the alloca's location. 8709 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8710 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8711 SelectionDAGBuilder &Builder) { 8712 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8713 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8714 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8715 Ops.push_back( 8716 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8717 Ops.push_back( 8718 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8719 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8720 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8721 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8722 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8723 } else 8724 Ops.push_back(OpVal); 8725 } 8726 } 8727 8728 /// Lower llvm.experimental.stackmap directly to its target opcode. 8729 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8730 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8731 // [live variables...]) 8732 8733 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8734 8735 SDValue Chain, InFlag, Callee, NullPtr; 8736 SmallVector<SDValue, 32> Ops; 8737 8738 SDLoc DL = getCurSDLoc(); 8739 Callee = getValue(CI.getCalledOperand()); 8740 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8741 8742 // The stackmap intrinsic only records the live variables (the arguments 8743 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8744 // intrinsic, this won't be lowered to a function call. This means we don't 8745 // have to worry about calling conventions and target specific lowering code. 8746 // Instead we perform the call lowering right here. 8747 // 8748 // chain, flag = CALLSEQ_START(chain, 0, 0) 8749 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8750 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8751 // 8752 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8753 InFlag = Chain.getValue(1); 8754 8755 // Add the <id> and <numBytes> constants. 8756 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8757 Ops.push_back(DAG.getTargetConstant( 8758 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8759 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8760 Ops.push_back(DAG.getTargetConstant( 8761 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8762 MVT::i32)); 8763 8764 // Push live variables for the stack map. 8765 addStackMapLiveVars(CI, 2, DL, Ops, *this); 8766 8767 // We are not pushing any register mask info here on the operands list, 8768 // because the stackmap doesn't clobber anything. 8769 8770 // Push the chain and the glue flag. 8771 Ops.push_back(Chain); 8772 Ops.push_back(InFlag); 8773 8774 // Create the STACKMAP node. 8775 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8776 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8777 Chain = SDValue(SM, 0); 8778 InFlag = Chain.getValue(1); 8779 8780 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8781 8782 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8783 8784 // Set the root to the target-lowered call chain. 8785 DAG.setRoot(Chain); 8786 8787 // Inform the Frame Information that we have a stackmap in this function. 8788 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8789 } 8790 8791 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8792 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 8793 const BasicBlock *EHPadBB) { 8794 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8795 // i32 <numBytes>, 8796 // i8* <target>, 8797 // i32 <numArgs>, 8798 // [Args...], 8799 // [live variables...]) 8800 8801 CallingConv::ID CC = CB.getCallingConv(); 8802 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8803 bool HasDef = !CB.getType()->isVoidTy(); 8804 SDLoc dl = getCurSDLoc(); 8805 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 8806 8807 // Handle immediate and symbolic callees. 8808 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8809 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8810 /*isTarget=*/true); 8811 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8812 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8813 SDLoc(SymbolicCallee), 8814 SymbolicCallee->getValueType(0)); 8815 8816 // Get the real number of arguments participating in the call <numArgs> 8817 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 8818 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8819 8820 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8821 // Intrinsics include all meta-operands up to but not including CC. 8822 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8823 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 8824 "Not enough arguments provided to the patchpoint intrinsic"); 8825 8826 // For AnyRegCC the arguments are lowered later on manually. 8827 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8828 Type *ReturnTy = 8829 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 8830 8831 TargetLowering::CallLoweringInfo CLI(DAG); 8832 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 8833 ReturnTy, true); 8834 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8835 8836 SDNode *CallEnd = Result.second.getNode(); 8837 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8838 CallEnd = CallEnd->getOperand(0).getNode(); 8839 8840 /// Get a call instruction from the call sequence chain. 8841 /// Tail calls are not allowed. 8842 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8843 "Expected a callseq node."); 8844 SDNode *Call = CallEnd->getOperand(0).getNode(); 8845 bool HasGlue = Call->getGluedNode(); 8846 8847 // Replace the target specific call node with the patchable intrinsic. 8848 SmallVector<SDValue, 8> Ops; 8849 8850 // Add the <id> and <numBytes> constants. 8851 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 8852 Ops.push_back(DAG.getTargetConstant( 8853 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8854 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 8855 Ops.push_back(DAG.getTargetConstant( 8856 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8857 MVT::i32)); 8858 8859 // Add the callee. 8860 Ops.push_back(Callee); 8861 8862 // Adjust <numArgs> to account for any arguments that have been passed on the 8863 // stack instead. 8864 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8865 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8866 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8867 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8868 8869 // Add the calling convention 8870 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8871 8872 // Add the arguments we omitted previously. The register allocator should 8873 // place these in any free register. 8874 if (IsAnyRegCC) 8875 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8876 Ops.push_back(getValue(CB.getArgOperand(i))); 8877 8878 // Push the arguments from the call instruction up to the register mask. 8879 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8880 Ops.append(Call->op_begin() + 2, e); 8881 8882 // Push live variables for the stack map. 8883 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 8884 8885 // Push the register mask info. 8886 if (HasGlue) 8887 Ops.push_back(*(Call->op_end()-2)); 8888 else 8889 Ops.push_back(*(Call->op_end()-1)); 8890 8891 // Push the chain (this is originally the first operand of the call, but 8892 // becomes now the last or second to last operand). 8893 Ops.push_back(*(Call->op_begin())); 8894 8895 // Push the glue flag (last operand). 8896 if (HasGlue) 8897 Ops.push_back(*(Call->op_end()-1)); 8898 8899 SDVTList NodeTys; 8900 if (IsAnyRegCC && HasDef) { 8901 // Create the return types based on the intrinsic definition 8902 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8903 SmallVector<EVT, 3> ValueVTs; 8904 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 8905 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8906 8907 // There is always a chain and a glue type at the end 8908 ValueVTs.push_back(MVT::Other); 8909 ValueVTs.push_back(MVT::Glue); 8910 NodeTys = DAG.getVTList(ValueVTs); 8911 } else 8912 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8913 8914 // Replace the target specific call node with a PATCHPOINT node. 8915 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8916 dl, NodeTys, Ops); 8917 8918 // Update the NodeMap. 8919 if (HasDef) { 8920 if (IsAnyRegCC) 8921 setValue(&CB, SDValue(MN, 0)); 8922 else 8923 setValue(&CB, Result.first); 8924 } 8925 8926 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8927 // call sequence. Furthermore the location of the chain and glue can change 8928 // when the AnyReg calling convention is used and the intrinsic returns a 8929 // value. 8930 if (IsAnyRegCC && HasDef) { 8931 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8932 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8933 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8934 } else 8935 DAG.ReplaceAllUsesWith(Call, MN); 8936 DAG.DeleteNode(Call); 8937 8938 // Inform the Frame Information that we have a patchpoint in this function. 8939 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8940 } 8941 8942 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8943 unsigned Intrinsic) { 8944 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8945 SDValue Op1 = getValue(I.getArgOperand(0)); 8946 SDValue Op2; 8947 if (I.getNumArgOperands() > 1) 8948 Op2 = getValue(I.getArgOperand(1)); 8949 SDLoc dl = getCurSDLoc(); 8950 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8951 SDValue Res; 8952 FastMathFlags FMF; 8953 if (isa<FPMathOperator>(I)) 8954 FMF = I.getFastMathFlags(); 8955 8956 switch (Intrinsic) { 8957 case Intrinsic::experimental_vector_reduce_v2_fadd: 8958 if (FMF.allowReassoc()) 8959 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8960 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8961 else 8962 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8963 break; 8964 case Intrinsic::experimental_vector_reduce_v2_fmul: 8965 if (FMF.allowReassoc()) 8966 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8967 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8968 else 8969 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8970 break; 8971 case Intrinsic::experimental_vector_reduce_add: 8972 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8973 break; 8974 case Intrinsic::experimental_vector_reduce_mul: 8975 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8976 break; 8977 case Intrinsic::experimental_vector_reduce_and: 8978 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8979 break; 8980 case Intrinsic::experimental_vector_reduce_or: 8981 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8982 break; 8983 case Intrinsic::experimental_vector_reduce_xor: 8984 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8985 break; 8986 case Intrinsic::experimental_vector_reduce_smax: 8987 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8988 break; 8989 case Intrinsic::experimental_vector_reduce_smin: 8990 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8991 break; 8992 case Intrinsic::experimental_vector_reduce_umax: 8993 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8994 break; 8995 case Intrinsic::experimental_vector_reduce_umin: 8996 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8997 break; 8998 case Intrinsic::experimental_vector_reduce_fmax: 8999 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 9000 break; 9001 case Intrinsic::experimental_vector_reduce_fmin: 9002 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 9003 break; 9004 default: 9005 llvm_unreachable("Unhandled vector reduce intrinsic"); 9006 } 9007 setValue(&I, Res); 9008 } 9009 9010 /// Returns an AttributeList representing the attributes applied to the return 9011 /// value of the given call. 9012 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9013 SmallVector<Attribute::AttrKind, 2> Attrs; 9014 if (CLI.RetSExt) 9015 Attrs.push_back(Attribute::SExt); 9016 if (CLI.RetZExt) 9017 Attrs.push_back(Attribute::ZExt); 9018 if (CLI.IsInReg) 9019 Attrs.push_back(Attribute::InReg); 9020 9021 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9022 Attrs); 9023 } 9024 9025 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9026 /// implementation, which just calls LowerCall. 9027 /// FIXME: When all targets are 9028 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9029 std::pair<SDValue, SDValue> 9030 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9031 // Handle the incoming return values from the call. 9032 CLI.Ins.clear(); 9033 Type *OrigRetTy = CLI.RetTy; 9034 SmallVector<EVT, 4> RetTys; 9035 SmallVector<uint64_t, 4> Offsets; 9036 auto &DL = CLI.DAG.getDataLayout(); 9037 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9038 9039 if (CLI.IsPostTypeLegalization) { 9040 // If we are lowering a libcall after legalization, split the return type. 9041 SmallVector<EVT, 4> OldRetTys; 9042 SmallVector<uint64_t, 4> OldOffsets; 9043 RetTys.swap(OldRetTys); 9044 Offsets.swap(OldOffsets); 9045 9046 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9047 EVT RetVT = OldRetTys[i]; 9048 uint64_t Offset = OldOffsets[i]; 9049 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9050 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9051 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9052 RetTys.append(NumRegs, RegisterVT); 9053 for (unsigned j = 0; j != NumRegs; ++j) 9054 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9055 } 9056 } 9057 9058 SmallVector<ISD::OutputArg, 4> Outs; 9059 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9060 9061 bool CanLowerReturn = 9062 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9063 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9064 9065 SDValue DemoteStackSlot; 9066 int DemoteStackIdx = -100; 9067 if (!CanLowerReturn) { 9068 // FIXME: equivalent assert? 9069 // assert(!CS.hasInAllocaArgument() && 9070 // "sret demotion is incompatible with inalloca"); 9071 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9072 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9073 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9074 DemoteStackIdx = 9075 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9076 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9077 DL.getAllocaAddrSpace()); 9078 9079 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9080 ArgListEntry Entry; 9081 Entry.Node = DemoteStackSlot; 9082 Entry.Ty = StackSlotPtrType; 9083 Entry.IsSExt = false; 9084 Entry.IsZExt = false; 9085 Entry.IsInReg = false; 9086 Entry.IsSRet = true; 9087 Entry.IsNest = false; 9088 Entry.IsByVal = false; 9089 Entry.IsByRef = false; 9090 Entry.IsReturned = false; 9091 Entry.IsSwiftSelf = false; 9092 Entry.IsSwiftError = false; 9093 Entry.IsCFGuardTarget = false; 9094 Entry.Alignment = Alignment; 9095 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9096 CLI.NumFixedArgs += 1; 9097 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9098 9099 // sret demotion isn't compatible with tail-calls, since the sret argument 9100 // points into the callers stack frame. 9101 CLI.IsTailCall = false; 9102 } else { 9103 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9104 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9105 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9106 ISD::ArgFlagsTy Flags; 9107 if (NeedsRegBlock) { 9108 Flags.setInConsecutiveRegs(); 9109 if (I == RetTys.size() - 1) 9110 Flags.setInConsecutiveRegsLast(); 9111 } 9112 EVT VT = RetTys[I]; 9113 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9114 CLI.CallConv, VT); 9115 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9116 CLI.CallConv, VT); 9117 for (unsigned i = 0; i != NumRegs; ++i) { 9118 ISD::InputArg MyFlags; 9119 MyFlags.Flags = Flags; 9120 MyFlags.VT = RegisterVT; 9121 MyFlags.ArgVT = VT; 9122 MyFlags.Used = CLI.IsReturnValueUsed; 9123 if (CLI.RetTy->isPointerTy()) { 9124 MyFlags.Flags.setPointer(); 9125 MyFlags.Flags.setPointerAddrSpace( 9126 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9127 } 9128 if (CLI.RetSExt) 9129 MyFlags.Flags.setSExt(); 9130 if (CLI.RetZExt) 9131 MyFlags.Flags.setZExt(); 9132 if (CLI.IsInReg) 9133 MyFlags.Flags.setInReg(); 9134 CLI.Ins.push_back(MyFlags); 9135 } 9136 } 9137 } 9138 9139 // We push in swifterror return as the last element of CLI.Ins. 9140 ArgListTy &Args = CLI.getArgs(); 9141 if (supportSwiftError()) { 9142 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9143 if (Args[i].IsSwiftError) { 9144 ISD::InputArg MyFlags; 9145 MyFlags.VT = getPointerTy(DL); 9146 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9147 MyFlags.Flags.setSwiftError(); 9148 CLI.Ins.push_back(MyFlags); 9149 } 9150 } 9151 } 9152 9153 // Handle all of the outgoing arguments. 9154 CLI.Outs.clear(); 9155 CLI.OutVals.clear(); 9156 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9157 SmallVector<EVT, 4> ValueVTs; 9158 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9159 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9160 Type *FinalType = Args[i].Ty; 9161 if (Args[i].IsByVal) 9162 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9163 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9164 FinalType, CLI.CallConv, CLI.IsVarArg); 9165 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9166 ++Value) { 9167 EVT VT = ValueVTs[Value]; 9168 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9169 SDValue Op = SDValue(Args[i].Node.getNode(), 9170 Args[i].Node.getResNo() + Value); 9171 ISD::ArgFlagsTy Flags; 9172 9173 // Certain targets (such as MIPS), may have a different ABI alignment 9174 // for a type depending on the context. Give the target a chance to 9175 // specify the alignment it wants. 9176 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9177 9178 if (Args[i].Ty->isPointerTy()) { 9179 Flags.setPointer(); 9180 Flags.setPointerAddrSpace( 9181 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9182 } 9183 if (Args[i].IsZExt) 9184 Flags.setZExt(); 9185 if (Args[i].IsSExt) 9186 Flags.setSExt(); 9187 if (Args[i].IsInReg) { 9188 // If we are using vectorcall calling convention, a structure that is 9189 // passed InReg - is surely an HVA 9190 if (CLI.CallConv == CallingConv::X86_VectorCall && 9191 isa<StructType>(FinalType)) { 9192 // The first value of a structure is marked 9193 if (0 == Value) 9194 Flags.setHvaStart(); 9195 Flags.setHva(); 9196 } 9197 // Set InReg Flag 9198 Flags.setInReg(); 9199 } 9200 if (Args[i].IsSRet) 9201 Flags.setSRet(); 9202 if (Args[i].IsSwiftSelf) 9203 Flags.setSwiftSelf(); 9204 if (Args[i].IsSwiftError) 9205 Flags.setSwiftError(); 9206 if (Args[i].IsCFGuardTarget) 9207 Flags.setCFGuardTarget(); 9208 if (Args[i].IsByVal) 9209 Flags.setByVal(); 9210 if (Args[i].IsByRef) 9211 Flags.setByRef(); 9212 if (Args[i].IsPreallocated) { 9213 Flags.setPreallocated(); 9214 // Set the byval flag for CCAssignFn callbacks that don't know about 9215 // preallocated. This way we can know how many bytes we should've 9216 // allocated and how many bytes a callee cleanup function will pop. If 9217 // we port preallocated to more targets, we'll have to add custom 9218 // preallocated handling in the various CC lowering callbacks. 9219 Flags.setByVal(); 9220 } 9221 if (Args[i].IsInAlloca) { 9222 Flags.setInAlloca(); 9223 // Set the byval flag for CCAssignFn callbacks that don't know about 9224 // inalloca. This way we can know how many bytes we should've allocated 9225 // and how many bytes a callee cleanup function will pop. If we port 9226 // inalloca to more targets, we'll have to add custom inalloca handling 9227 // in the various CC lowering callbacks. 9228 Flags.setByVal(); 9229 } 9230 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9231 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9232 Type *ElementTy = Ty->getElementType(); 9233 9234 unsigned FrameSize = DL.getTypeAllocSize( 9235 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9236 Flags.setByValSize(FrameSize); 9237 9238 // info is not there but there are cases it cannot get right. 9239 Align FrameAlign; 9240 if (auto MA = Args[i].Alignment) 9241 FrameAlign = *MA; 9242 else 9243 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9244 Flags.setByValAlign(FrameAlign); 9245 } 9246 if (Args[i].IsNest) 9247 Flags.setNest(); 9248 if (NeedsRegBlock) 9249 Flags.setInConsecutiveRegs(); 9250 Flags.setOrigAlign(OriginalAlignment); 9251 9252 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9253 CLI.CallConv, VT); 9254 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9255 CLI.CallConv, VT); 9256 SmallVector<SDValue, 4> Parts(NumParts); 9257 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9258 9259 if (Args[i].IsSExt) 9260 ExtendKind = ISD::SIGN_EXTEND; 9261 else if (Args[i].IsZExt) 9262 ExtendKind = ISD::ZERO_EXTEND; 9263 9264 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9265 // for now. 9266 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9267 CanLowerReturn) { 9268 assert((CLI.RetTy == Args[i].Ty || 9269 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9270 CLI.RetTy->getPointerAddressSpace() == 9271 Args[i].Ty->getPointerAddressSpace())) && 9272 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9273 // Before passing 'returned' to the target lowering code, ensure that 9274 // either the register MVT and the actual EVT are the same size or that 9275 // the return value and argument are extended in the same way; in these 9276 // cases it's safe to pass the argument register value unchanged as the 9277 // return register value (although it's at the target's option whether 9278 // to do so) 9279 // TODO: allow code generation to take advantage of partially preserved 9280 // registers rather than clobbering the entire register when the 9281 // parameter extension method is not compatible with the return 9282 // extension method 9283 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9284 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9285 CLI.RetZExt == Args[i].IsZExt)) 9286 Flags.setReturned(); 9287 } 9288 9289 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9290 CLI.CallConv, ExtendKind); 9291 9292 for (unsigned j = 0; j != NumParts; ++j) { 9293 // if it isn't first piece, alignment must be 1 9294 // For scalable vectors the scalable part is currently handled 9295 // by individual targets, so we just use the known minimum size here. 9296 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9297 i < CLI.NumFixedArgs, i, 9298 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9299 if (NumParts > 1 && j == 0) 9300 MyFlags.Flags.setSplit(); 9301 else if (j != 0) { 9302 MyFlags.Flags.setOrigAlign(Align(1)); 9303 if (j == NumParts - 1) 9304 MyFlags.Flags.setSplitEnd(); 9305 } 9306 9307 CLI.Outs.push_back(MyFlags); 9308 CLI.OutVals.push_back(Parts[j]); 9309 } 9310 9311 if (NeedsRegBlock && Value == NumValues - 1) 9312 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9313 } 9314 } 9315 9316 SmallVector<SDValue, 4> InVals; 9317 CLI.Chain = LowerCall(CLI, InVals); 9318 9319 // Update CLI.InVals to use outside of this function. 9320 CLI.InVals = InVals; 9321 9322 // Verify that the target's LowerCall behaved as expected. 9323 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9324 "LowerCall didn't return a valid chain!"); 9325 assert((!CLI.IsTailCall || InVals.empty()) && 9326 "LowerCall emitted a return value for a tail call!"); 9327 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9328 "LowerCall didn't emit the correct number of values!"); 9329 9330 // For a tail call, the return value is merely live-out and there aren't 9331 // any nodes in the DAG representing it. Return a special value to 9332 // indicate that a tail call has been emitted and no more Instructions 9333 // should be processed in the current block. 9334 if (CLI.IsTailCall) { 9335 CLI.DAG.setRoot(CLI.Chain); 9336 return std::make_pair(SDValue(), SDValue()); 9337 } 9338 9339 #ifndef NDEBUG 9340 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9341 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9342 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9343 "LowerCall emitted a value with the wrong type!"); 9344 } 9345 #endif 9346 9347 SmallVector<SDValue, 4> ReturnValues; 9348 if (!CanLowerReturn) { 9349 // The instruction result is the result of loading from the 9350 // hidden sret parameter. 9351 SmallVector<EVT, 1> PVTs; 9352 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9353 9354 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9355 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9356 EVT PtrVT = PVTs[0]; 9357 9358 unsigned NumValues = RetTys.size(); 9359 ReturnValues.resize(NumValues); 9360 SmallVector<SDValue, 4> Chains(NumValues); 9361 9362 // An aggregate return value cannot wrap around the address space, so 9363 // offsets to its parts don't wrap either. 9364 SDNodeFlags Flags; 9365 Flags.setNoUnsignedWrap(true); 9366 9367 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9368 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9369 for (unsigned i = 0; i < NumValues; ++i) { 9370 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9371 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9372 PtrVT), Flags); 9373 SDValue L = CLI.DAG.getLoad( 9374 RetTys[i], CLI.DL, CLI.Chain, Add, 9375 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9376 DemoteStackIdx, Offsets[i]), 9377 HiddenSRetAlign); 9378 ReturnValues[i] = L; 9379 Chains[i] = L.getValue(1); 9380 } 9381 9382 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9383 } else { 9384 // Collect the legal value parts into potentially illegal values 9385 // that correspond to the original function's return values. 9386 Optional<ISD::NodeType> AssertOp; 9387 if (CLI.RetSExt) 9388 AssertOp = ISD::AssertSext; 9389 else if (CLI.RetZExt) 9390 AssertOp = ISD::AssertZext; 9391 unsigned CurReg = 0; 9392 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9393 EVT VT = RetTys[I]; 9394 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9395 CLI.CallConv, VT); 9396 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9397 CLI.CallConv, VT); 9398 9399 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9400 NumRegs, RegisterVT, VT, nullptr, 9401 CLI.CallConv, AssertOp)); 9402 CurReg += NumRegs; 9403 } 9404 9405 // For a function returning void, there is no return value. We can't create 9406 // such a node, so we just return a null return value in that case. In 9407 // that case, nothing will actually look at the value. 9408 if (ReturnValues.empty()) 9409 return std::make_pair(SDValue(), CLI.Chain); 9410 } 9411 9412 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9413 CLI.DAG.getVTList(RetTys), ReturnValues); 9414 return std::make_pair(Res, CLI.Chain); 9415 } 9416 9417 void TargetLowering::LowerOperationWrapper(SDNode *N, 9418 SmallVectorImpl<SDValue> &Results, 9419 SelectionDAG &DAG) const { 9420 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9421 Results.push_back(Res); 9422 } 9423 9424 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9425 llvm_unreachable("LowerOperation not implemented for this target!"); 9426 } 9427 9428 void 9429 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9430 SDValue Op = getNonRegisterValue(V); 9431 assert((Op.getOpcode() != ISD::CopyFromReg || 9432 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9433 "Copy from a reg to the same reg!"); 9434 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9435 9436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9437 // If this is an InlineAsm we have to match the registers required, not the 9438 // notional registers required by the type. 9439 9440 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9441 None); // This is not an ABI copy. 9442 SDValue Chain = DAG.getEntryNode(); 9443 9444 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9445 FuncInfo.PreferredExtendType.end()) 9446 ? ISD::ANY_EXTEND 9447 : FuncInfo.PreferredExtendType[V]; 9448 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9449 PendingExports.push_back(Chain); 9450 } 9451 9452 #include "llvm/CodeGen/SelectionDAGISel.h" 9453 9454 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9455 /// entry block, return true. This includes arguments used by switches, since 9456 /// the switch may expand into multiple basic blocks. 9457 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9458 // With FastISel active, we may be splitting blocks, so force creation 9459 // of virtual registers for all non-dead arguments. 9460 if (FastISel) 9461 return A->use_empty(); 9462 9463 const BasicBlock &Entry = A->getParent()->front(); 9464 for (const User *U : A->users()) 9465 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9466 return false; // Use not in entry block. 9467 9468 return true; 9469 } 9470 9471 using ArgCopyElisionMapTy = 9472 DenseMap<const Argument *, 9473 std::pair<const AllocaInst *, const StoreInst *>>; 9474 9475 /// Scan the entry block of the function in FuncInfo for arguments that look 9476 /// like copies into a local alloca. Record any copied arguments in 9477 /// ArgCopyElisionCandidates. 9478 static void 9479 findArgumentCopyElisionCandidates(const DataLayout &DL, 9480 FunctionLoweringInfo *FuncInfo, 9481 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9482 // Record the state of every static alloca used in the entry block. Argument 9483 // allocas are all used in the entry block, so we need approximately as many 9484 // entries as we have arguments. 9485 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9486 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9487 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9488 StaticAllocas.reserve(NumArgs * 2); 9489 9490 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9491 if (!V) 9492 return nullptr; 9493 V = V->stripPointerCasts(); 9494 const auto *AI = dyn_cast<AllocaInst>(V); 9495 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9496 return nullptr; 9497 auto Iter = StaticAllocas.insert({AI, Unknown}); 9498 return &Iter.first->second; 9499 }; 9500 9501 // Look for stores of arguments to static allocas. Look through bitcasts and 9502 // GEPs to handle type coercions, as long as the alloca is fully initialized 9503 // by the store. Any non-store use of an alloca escapes it and any subsequent 9504 // unanalyzed store might write it. 9505 // FIXME: Handle structs initialized with multiple stores. 9506 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9507 // Look for stores, and handle non-store uses conservatively. 9508 const auto *SI = dyn_cast<StoreInst>(&I); 9509 if (!SI) { 9510 // We will look through cast uses, so ignore them completely. 9511 if (I.isCast()) 9512 continue; 9513 // Ignore debug info intrinsics, they don't escape or store to allocas. 9514 if (isa<DbgInfoIntrinsic>(I)) 9515 continue; 9516 // This is an unknown instruction. Assume it escapes or writes to all 9517 // static alloca operands. 9518 for (const Use &U : I.operands()) { 9519 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9520 *Info = StaticAllocaInfo::Clobbered; 9521 } 9522 continue; 9523 } 9524 9525 // If the stored value is a static alloca, mark it as escaped. 9526 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9527 *Info = StaticAllocaInfo::Clobbered; 9528 9529 // Check if the destination is a static alloca. 9530 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9531 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9532 if (!Info) 9533 continue; 9534 const AllocaInst *AI = cast<AllocaInst>(Dst); 9535 9536 // Skip allocas that have been initialized or clobbered. 9537 if (*Info != StaticAllocaInfo::Unknown) 9538 continue; 9539 9540 // Check if the stored value is an argument, and that this store fully 9541 // initializes the alloca. Don't elide copies from the same argument twice. 9542 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9543 const auto *Arg = dyn_cast<Argument>(Val); 9544 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9545 Arg->getType()->isEmptyTy() || 9546 DL.getTypeStoreSize(Arg->getType()) != 9547 DL.getTypeAllocSize(AI->getAllocatedType()) || 9548 ArgCopyElisionCandidates.count(Arg)) { 9549 *Info = StaticAllocaInfo::Clobbered; 9550 continue; 9551 } 9552 9553 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9554 << '\n'); 9555 9556 // Mark this alloca and store for argument copy elision. 9557 *Info = StaticAllocaInfo::Elidable; 9558 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9559 9560 // Stop scanning if we've seen all arguments. This will happen early in -O0 9561 // builds, which is useful, because -O0 builds have large entry blocks and 9562 // many allocas. 9563 if (ArgCopyElisionCandidates.size() == NumArgs) 9564 break; 9565 } 9566 } 9567 9568 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9569 /// ArgVal is a load from a suitable fixed stack object. 9570 static void tryToElideArgumentCopy( 9571 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9572 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9573 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9574 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9575 SDValue ArgVal, bool &ArgHasUses) { 9576 // Check if this is a load from a fixed stack object. 9577 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9578 if (!LNode) 9579 return; 9580 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9581 if (!FINode) 9582 return; 9583 9584 // Check that the fixed stack object is the right size and alignment. 9585 // Look at the alignment that the user wrote on the alloca instead of looking 9586 // at the stack object. 9587 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9588 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9589 const AllocaInst *AI = ArgCopyIter->second.first; 9590 int FixedIndex = FINode->getIndex(); 9591 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9592 int OldIndex = AllocaIndex; 9593 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9594 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9595 LLVM_DEBUG( 9596 dbgs() << " argument copy elision failed due to bad fixed stack " 9597 "object size\n"); 9598 return; 9599 } 9600 Align RequiredAlignment = AI->getAlign(); 9601 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9602 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9603 "greater than stack argument alignment (" 9604 << DebugStr(RequiredAlignment) << " vs " 9605 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9606 return; 9607 } 9608 9609 // Perform the elision. Delete the old stack object and replace its only use 9610 // in the variable info map. Mark the stack object as mutable. 9611 LLVM_DEBUG({ 9612 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9613 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9614 << '\n'; 9615 }); 9616 MFI.RemoveStackObject(OldIndex); 9617 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9618 AllocaIndex = FixedIndex; 9619 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9620 Chains.push_back(ArgVal.getValue(1)); 9621 9622 // Avoid emitting code for the store implementing the copy. 9623 const StoreInst *SI = ArgCopyIter->second.second; 9624 ElidedArgCopyInstrs.insert(SI); 9625 9626 // Check for uses of the argument again so that we can avoid exporting ArgVal 9627 // if it is't used by anything other than the store. 9628 for (const Value *U : Arg.users()) { 9629 if (U != SI) { 9630 ArgHasUses = true; 9631 break; 9632 } 9633 } 9634 } 9635 9636 void SelectionDAGISel::LowerArguments(const Function &F) { 9637 SelectionDAG &DAG = SDB->DAG; 9638 SDLoc dl = SDB->getCurSDLoc(); 9639 const DataLayout &DL = DAG.getDataLayout(); 9640 SmallVector<ISD::InputArg, 16> Ins; 9641 9642 // In Naked functions we aren't going to save any registers. 9643 if (F.hasFnAttribute(Attribute::Naked)) 9644 return; 9645 9646 if (!FuncInfo->CanLowerReturn) { 9647 // Put in an sret pointer parameter before all the other parameters. 9648 SmallVector<EVT, 1> ValueVTs; 9649 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9650 F.getReturnType()->getPointerTo( 9651 DAG.getDataLayout().getAllocaAddrSpace()), 9652 ValueVTs); 9653 9654 // NOTE: Assuming that a pointer will never break down to more than one VT 9655 // or one register. 9656 ISD::ArgFlagsTy Flags; 9657 Flags.setSRet(); 9658 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9659 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9660 ISD::InputArg::NoArgIndex, 0); 9661 Ins.push_back(RetArg); 9662 } 9663 9664 // Look for stores of arguments to static allocas. Mark such arguments with a 9665 // flag to ask the target to give us the memory location of that argument if 9666 // available. 9667 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9668 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9669 ArgCopyElisionCandidates); 9670 9671 // Set up the incoming argument description vector. 9672 for (const Argument &Arg : F.args()) { 9673 unsigned ArgNo = Arg.getArgNo(); 9674 SmallVector<EVT, 4> ValueVTs; 9675 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9676 bool isArgValueUsed = !Arg.use_empty(); 9677 unsigned PartBase = 0; 9678 Type *FinalType = Arg.getType(); 9679 if (Arg.hasAttribute(Attribute::ByVal)) 9680 FinalType = Arg.getParamByValType(); 9681 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9682 FinalType, F.getCallingConv(), F.isVarArg()); 9683 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9684 Value != NumValues; ++Value) { 9685 EVT VT = ValueVTs[Value]; 9686 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9687 ISD::ArgFlagsTy Flags; 9688 9689 // Certain targets (such as MIPS), may have a different ABI alignment 9690 // for a type depending on the context. Give the target a chance to 9691 // specify the alignment it wants. 9692 const Align OriginalAlignment( 9693 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9694 9695 if (Arg.getType()->isPointerTy()) { 9696 Flags.setPointer(); 9697 Flags.setPointerAddrSpace( 9698 cast<PointerType>(Arg.getType())->getAddressSpace()); 9699 } 9700 if (Arg.hasAttribute(Attribute::ZExt)) 9701 Flags.setZExt(); 9702 if (Arg.hasAttribute(Attribute::SExt)) 9703 Flags.setSExt(); 9704 if (Arg.hasAttribute(Attribute::InReg)) { 9705 // If we are using vectorcall calling convention, a structure that is 9706 // passed InReg - is surely an HVA 9707 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9708 isa<StructType>(Arg.getType())) { 9709 // The first value of a structure is marked 9710 if (0 == Value) 9711 Flags.setHvaStart(); 9712 Flags.setHva(); 9713 } 9714 // Set InReg Flag 9715 Flags.setInReg(); 9716 } 9717 if (Arg.hasAttribute(Attribute::StructRet)) 9718 Flags.setSRet(); 9719 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9720 Flags.setSwiftSelf(); 9721 if (Arg.hasAttribute(Attribute::SwiftError)) 9722 Flags.setSwiftError(); 9723 if (Arg.hasAttribute(Attribute::ByVal)) 9724 Flags.setByVal(); 9725 if (Arg.hasAttribute(Attribute::ByRef)) 9726 Flags.setByRef(); 9727 if (Arg.hasAttribute(Attribute::InAlloca)) { 9728 Flags.setInAlloca(); 9729 // Set the byval flag for CCAssignFn callbacks that don't know about 9730 // inalloca. This way we can know how many bytes we should've allocated 9731 // and how many bytes a callee cleanup function will pop. If we port 9732 // inalloca to more targets, we'll have to add custom inalloca handling 9733 // in the various CC lowering callbacks. 9734 Flags.setByVal(); 9735 } 9736 if (Arg.hasAttribute(Attribute::Preallocated)) { 9737 Flags.setPreallocated(); 9738 // Set the byval flag for CCAssignFn callbacks that don't know about 9739 // preallocated. This way we can know how many bytes we should've 9740 // allocated and how many bytes a callee cleanup function will pop. If 9741 // we port preallocated to more targets, we'll have to add custom 9742 // preallocated handling in the various CC lowering callbacks. 9743 Flags.setByVal(); 9744 } 9745 9746 Type *ArgMemTy = nullptr; 9747 if (F.getCallingConv() == CallingConv::X86_INTR) { 9748 // IA Interrupt passes frame (1st parameter) by value in the stack. 9749 if (ArgNo == 0) { 9750 Flags.setByVal(); 9751 // FIXME: Dependence on pointee element type. See bug 46672. 9752 ArgMemTy = Arg.getType()->getPointerElementType(); 9753 } 9754 } 9755 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 9756 Flags.isByRef()) { 9757 if (!ArgMemTy) 9758 ArgMemTy = Arg.getPointeeInMemoryValueType(); 9759 9760 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 9761 9762 // For in-memory arguments, size and alignment should be passed from FE. 9763 // BE will guess if this info is not there but there are cases it cannot 9764 // get right. 9765 MaybeAlign MemAlign = Arg.getParamAlign(); 9766 if (!MemAlign) 9767 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 9768 9769 if (Flags.isByRef()) { 9770 Flags.setByRefSize(MemSize); 9771 Flags.setByRefAlign(*MemAlign); 9772 } else { 9773 Flags.setByValSize(MemSize); 9774 Flags.setByValAlign(*MemAlign); 9775 } 9776 } 9777 9778 if (Arg.hasAttribute(Attribute::Nest)) 9779 Flags.setNest(); 9780 if (NeedsRegBlock) 9781 Flags.setInConsecutiveRegs(); 9782 Flags.setOrigAlign(OriginalAlignment); 9783 if (ArgCopyElisionCandidates.count(&Arg)) 9784 Flags.setCopyElisionCandidate(); 9785 if (Arg.hasAttribute(Attribute::Returned)) 9786 Flags.setReturned(); 9787 9788 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9789 *CurDAG->getContext(), F.getCallingConv(), VT); 9790 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9791 *CurDAG->getContext(), F.getCallingConv(), VT); 9792 for (unsigned i = 0; i != NumRegs; ++i) { 9793 // For scalable vectors, use the minimum size; individual targets 9794 // are responsible for handling scalable vector arguments and 9795 // return values. 9796 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9797 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9798 if (NumRegs > 1 && i == 0) 9799 MyFlags.Flags.setSplit(); 9800 // if it isn't first piece, alignment must be 1 9801 else if (i > 0) { 9802 MyFlags.Flags.setOrigAlign(Align(1)); 9803 if (i == NumRegs - 1) 9804 MyFlags.Flags.setSplitEnd(); 9805 } 9806 Ins.push_back(MyFlags); 9807 } 9808 if (NeedsRegBlock && Value == NumValues - 1) 9809 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9810 PartBase += VT.getStoreSize().getKnownMinSize(); 9811 } 9812 } 9813 9814 // Call the target to set up the argument values. 9815 SmallVector<SDValue, 8> InVals; 9816 SDValue NewRoot = TLI->LowerFormalArguments( 9817 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9818 9819 // Verify that the target's LowerFormalArguments behaved as expected. 9820 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9821 "LowerFormalArguments didn't return a valid chain!"); 9822 assert(InVals.size() == Ins.size() && 9823 "LowerFormalArguments didn't emit the correct number of values!"); 9824 LLVM_DEBUG({ 9825 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9826 assert(InVals[i].getNode() && 9827 "LowerFormalArguments emitted a null value!"); 9828 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9829 "LowerFormalArguments emitted a value with the wrong type!"); 9830 } 9831 }); 9832 9833 // Update the DAG with the new chain value resulting from argument lowering. 9834 DAG.setRoot(NewRoot); 9835 9836 // Set up the argument values. 9837 unsigned i = 0; 9838 if (!FuncInfo->CanLowerReturn) { 9839 // Create a virtual register for the sret pointer, and put in a copy 9840 // from the sret argument into it. 9841 SmallVector<EVT, 1> ValueVTs; 9842 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9843 F.getReturnType()->getPointerTo( 9844 DAG.getDataLayout().getAllocaAddrSpace()), 9845 ValueVTs); 9846 MVT VT = ValueVTs[0].getSimpleVT(); 9847 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9848 Optional<ISD::NodeType> AssertOp = None; 9849 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9850 nullptr, F.getCallingConv(), AssertOp); 9851 9852 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9853 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9854 Register SRetReg = 9855 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9856 FuncInfo->DemoteRegister = SRetReg; 9857 NewRoot = 9858 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9859 DAG.setRoot(NewRoot); 9860 9861 // i indexes lowered arguments. Bump it past the hidden sret argument. 9862 ++i; 9863 } 9864 9865 SmallVector<SDValue, 4> Chains; 9866 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9867 for (const Argument &Arg : F.args()) { 9868 SmallVector<SDValue, 4> ArgValues; 9869 SmallVector<EVT, 4> ValueVTs; 9870 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9871 unsigned NumValues = ValueVTs.size(); 9872 if (NumValues == 0) 9873 continue; 9874 9875 bool ArgHasUses = !Arg.use_empty(); 9876 9877 // Elide the copying store if the target loaded this argument from a 9878 // suitable fixed stack object. 9879 if (Ins[i].Flags.isCopyElisionCandidate()) { 9880 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9881 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9882 InVals[i], ArgHasUses); 9883 } 9884 9885 // If this argument is unused then remember its value. It is used to generate 9886 // debugging information. 9887 bool isSwiftErrorArg = 9888 TLI->supportSwiftError() && 9889 Arg.hasAttribute(Attribute::SwiftError); 9890 if (!ArgHasUses && !isSwiftErrorArg) { 9891 SDB->setUnusedArgValue(&Arg, InVals[i]); 9892 9893 // Also remember any frame index for use in FastISel. 9894 if (FrameIndexSDNode *FI = 9895 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9896 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9897 } 9898 9899 for (unsigned Val = 0; Val != NumValues; ++Val) { 9900 EVT VT = ValueVTs[Val]; 9901 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9902 F.getCallingConv(), VT); 9903 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9904 *CurDAG->getContext(), F.getCallingConv(), VT); 9905 9906 // Even an apparent 'unused' swifterror argument needs to be returned. So 9907 // we do generate a copy for it that can be used on return from the 9908 // function. 9909 if (ArgHasUses || isSwiftErrorArg) { 9910 Optional<ISD::NodeType> AssertOp; 9911 if (Arg.hasAttribute(Attribute::SExt)) 9912 AssertOp = ISD::AssertSext; 9913 else if (Arg.hasAttribute(Attribute::ZExt)) 9914 AssertOp = ISD::AssertZext; 9915 9916 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9917 PartVT, VT, nullptr, 9918 F.getCallingConv(), AssertOp)); 9919 } 9920 9921 i += NumParts; 9922 } 9923 9924 // We don't need to do anything else for unused arguments. 9925 if (ArgValues.empty()) 9926 continue; 9927 9928 // Note down frame index. 9929 if (FrameIndexSDNode *FI = 9930 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9931 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9932 9933 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9934 SDB->getCurSDLoc()); 9935 9936 SDB->setValue(&Arg, Res); 9937 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9938 // We want to associate the argument with the frame index, among 9939 // involved operands, that correspond to the lowest address. The 9940 // getCopyFromParts function, called earlier, is swapping the order of 9941 // the operands to BUILD_PAIR depending on endianness. The result of 9942 // that swapping is that the least significant bits of the argument will 9943 // be in the first operand of the BUILD_PAIR node, and the most 9944 // significant bits will be in the second operand. 9945 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9946 if (LoadSDNode *LNode = 9947 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9948 if (FrameIndexSDNode *FI = 9949 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9950 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9951 } 9952 9953 // Analyses past this point are naive and don't expect an assertion. 9954 if (Res.getOpcode() == ISD::AssertZext) 9955 Res = Res.getOperand(0); 9956 9957 // Update the SwiftErrorVRegDefMap. 9958 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9959 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9960 if (Register::isVirtualRegister(Reg)) 9961 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9962 Reg); 9963 } 9964 9965 // If this argument is live outside of the entry block, insert a copy from 9966 // wherever we got it to the vreg that other BB's will reference it as. 9967 if (Res.getOpcode() == ISD::CopyFromReg) { 9968 // If we can, though, try to skip creating an unnecessary vreg. 9969 // FIXME: This isn't very clean... it would be nice to make this more 9970 // general. 9971 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9972 if (Register::isVirtualRegister(Reg)) { 9973 FuncInfo->ValueMap[&Arg] = Reg; 9974 continue; 9975 } 9976 } 9977 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9978 FuncInfo->InitializeRegForValue(&Arg); 9979 SDB->CopyToExportRegsIfNeeded(&Arg); 9980 } 9981 } 9982 9983 if (!Chains.empty()) { 9984 Chains.push_back(NewRoot); 9985 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9986 } 9987 9988 DAG.setRoot(NewRoot); 9989 9990 assert(i == InVals.size() && "Argument register count mismatch!"); 9991 9992 // If any argument copy elisions occurred and we have debug info, update the 9993 // stale frame indices used in the dbg.declare variable info table. 9994 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9995 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9996 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9997 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9998 if (I != ArgCopyElisionFrameIndexMap.end()) 9999 VI.Slot = I->second; 10000 } 10001 } 10002 10003 // Finally, if the target has anything special to do, allow it to do so. 10004 emitFunctionEntryCode(); 10005 } 10006 10007 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10008 /// ensure constants are generated when needed. Remember the virtual registers 10009 /// that need to be added to the Machine PHI nodes as input. We cannot just 10010 /// directly add them, because expansion might result in multiple MBB's for one 10011 /// BB. As such, the start of the BB might correspond to a different MBB than 10012 /// the end. 10013 void 10014 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10015 const Instruction *TI = LLVMBB->getTerminator(); 10016 10017 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10018 10019 // Check PHI nodes in successors that expect a value to be available from this 10020 // block. 10021 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10022 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10023 if (!isa<PHINode>(SuccBB->begin())) continue; 10024 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10025 10026 // If this terminator has multiple identical successors (common for 10027 // switches), only handle each succ once. 10028 if (!SuccsHandled.insert(SuccMBB).second) 10029 continue; 10030 10031 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10032 10033 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10034 // nodes and Machine PHI nodes, but the incoming operands have not been 10035 // emitted yet. 10036 for (const PHINode &PN : SuccBB->phis()) { 10037 // Ignore dead phi's. 10038 if (PN.use_empty()) 10039 continue; 10040 10041 // Skip empty types 10042 if (PN.getType()->isEmptyTy()) 10043 continue; 10044 10045 unsigned Reg; 10046 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10047 10048 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10049 unsigned &RegOut = ConstantsOut[C]; 10050 if (RegOut == 0) { 10051 RegOut = FuncInfo.CreateRegs(C); 10052 CopyValueToVirtualRegister(C, RegOut); 10053 } 10054 Reg = RegOut; 10055 } else { 10056 DenseMap<const Value *, Register>::iterator I = 10057 FuncInfo.ValueMap.find(PHIOp); 10058 if (I != FuncInfo.ValueMap.end()) 10059 Reg = I->second; 10060 else { 10061 assert(isa<AllocaInst>(PHIOp) && 10062 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10063 "Didn't codegen value into a register!??"); 10064 Reg = FuncInfo.CreateRegs(PHIOp); 10065 CopyValueToVirtualRegister(PHIOp, Reg); 10066 } 10067 } 10068 10069 // Remember that this register needs to added to the machine PHI node as 10070 // the input for this MBB. 10071 SmallVector<EVT, 4> ValueVTs; 10072 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10073 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10074 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10075 EVT VT = ValueVTs[vti]; 10076 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10077 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10078 FuncInfo.PHINodesToUpdate.push_back( 10079 std::make_pair(&*MBBI++, Reg + i)); 10080 Reg += NumRegisters; 10081 } 10082 } 10083 } 10084 10085 ConstantsOut.clear(); 10086 } 10087 10088 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10089 /// is 0. 10090 MachineBasicBlock * 10091 SelectionDAGBuilder::StackProtectorDescriptor:: 10092 AddSuccessorMBB(const BasicBlock *BB, 10093 MachineBasicBlock *ParentMBB, 10094 bool IsLikely, 10095 MachineBasicBlock *SuccMBB) { 10096 // If SuccBB has not been created yet, create it. 10097 if (!SuccMBB) { 10098 MachineFunction *MF = ParentMBB->getParent(); 10099 MachineFunction::iterator BBI(ParentMBB); 10100 SuccMBB = MF->CreateMachineBasicBlock(BB); 10101 MF->insert(++BBI, SuccMBB); 10102 } 10103 // Add it as a successor of ParentMBB. 10104 ParentMBB->addSuccessor( 10105 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10106 return SuccMBB; 10107 } 10108 10109 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10110 MachineFunction::iterator I(MBB); 10111 if (++I == FuncInfo.MF->end()) 10112 return nullptr; 10113 return &*I; 10114 } 10115 10116 /// During lowering new call nodes can be created (such as memset, etc.). 10117 /// Those will become new roots of the current DAG, but complications arise 10118 /// when they are tail calls. In such cases, the call lowering will update 10119 /// the root, but the builder still needs to know that a tail call has been 10120 /// lowered in order to avoid generating an additional return. 10121 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10122 // If the node is null, we do have a tail call. 10123 if (MaybeTC.getNode() != nullptr) 10124 DAG.setRoot(MaybeTC); 10125 else 10126 HasTailCall = true; 10127 } 10128 10129 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10130 MachineBasicBlock *SwitchMBB, 10131 MachineBasicBlock *DefaultMBB) { 10132 MachineFunction *CurMF = FuncInfo.MF; 10133 MachineBasicBlock *NextMBB = nullptr; 10134 MachineFunction::iterator BBI(W.MBB); 10135 if (++BBI != FuncInfo.MF->end()) 10136 NextMBB = &*BBI; 10137 10138 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10139 10140 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10141 10142 if (Size == 2 && W.MBB == SwitchMBB) { 10143 // If any two of the cases has the same destination, and if one value 10144 // is the same as the other, but has one bit unset that the other has set, 10145 // use bit manipulation to do two compares at once. For example: 10146 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10147 // TODO: This could be extended to merge any 2 cases in switches with 3 10148 // cases. 10149 // TODO: Handle cases where W.CaseBB != SwitchBB. 10150 CaseCluster &Small = *W.FirstCluster; 10151 CaseCluster &Big = *W.LastCluster; 10152 10153 if (Small.Low == Small.High && Big.Low == Big.High && 10154 Small.MBB == Big.MBB) { 10155 const APInt &SmallValue = Small.Low->getValue(); 10156 const APInt &BigValue = Big.Low->getValue(); 10157 10158 // Check that there is only one bit different. 10159 APInt CommonBit = BigValue ^ SmallValue; 10160 if (CommonBit.isPowerOf2()) { 10161 SDValue CondLHS = getValue(Cond); 10162 EVT VT = CondLHS.getValueType(); 10163 SDLoc DL = getCurSDLoc(); 10164 10165 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10166 DAG.getConstant(CommonBit, DL, VT)); 10167 SDValue Cond = DAG.getSetCC( 10168 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10169 ISD::SETEQ); 10170 10171 // Update successor info. 10172 // Both Small and Big will jump to Small.BB, so we sum up the 10173 // probabilities. 10174 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10175 if (BPI) 10176 addSuccessorWithProb( 10177 SwitchMBB, DefaultMBB, 10178 // The default destination is the first successor in IR. 10179 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10180 else 10181 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10182 10183 // Insert the true branch. 10184 SDValue BrCond = 10185 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10186 DAG.getBasicBlock(Small.MBB)); 10187 // Insert the false branch. 10188 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10189 DAG.getBasicBlock(DefaultMBB)); 10190 10191 DAG.setRoot(BrCond); 10192 return; 10193 } 10194 } 10195 } 10196 10197 if (TM.getOptLevel() != CodeGenOpt::None) { 10198 // Here, we order cases by probability so the most likely case will be 10199 // checked first. However, two clusters can have the same probability in 10200 // which case their relative ordering is non-deterministic. So we use Low 10201 // as a tie-breaker as clusters are guaranteed to never overlap. 10202 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10203 [](const CaseCluster &a, const CaseCluster &b) { 10204 return a.Prob != b.Prob ? 10205 a.Prob > b.Prob : 10206 a.Low->getValue().slt(b.Low->getValue()); 10207 }); 10208 10209 // Rearrange the case blocks so that the last one falls through if possible 10210 // without changing the order of probabilities. 10211 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10212 --I; 10213 if (I->Prob > W.LastCluster->Prob) 10214 break; 10215 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10216 std::swap(*I, *W.LastCluster); 10217 break; 10218 } 10219 } 10220 } 10221 10222 // Compute total probability. 10223 BranchProbability DefaultProb = W.DefaultProb; 10224 BranchProbability UnhandledProbs = DefaultProb; 10225 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10226 UnhandledProbs += I->Prob; 10227 10228 MachineBasicBlock *CurMBB = W.MBB; 10229 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10230 bool FallthroughUnreachable = false; 10231 MachineBasicBlock *Fallthrough; 10232 if (I == W.LastCluster) { 10233 // For the last cluster, fall through to the default destination. 10234 Fallthrough = DefaultMBB; 10235 FallthroughUnreachable = isa<UnreachableInst>( 10236 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10237 } else { 10238 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10239 CurMF->insert(BBI, Fallthrough); 10240 // Put Cond in a virtual register to make it available from the new blocks. 10241 ExportFromCurrentBlock(Cond); 10242 } 10243 UnhandledProbs -= I->Prob; 10244 10245 switch (I->Kind) { 10246 case CC_JumpTable: { 10247 // FIXME: Optimize away range check based on pivot comparisons. 10248 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10249 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10250 10251 // The jump block hasn't been inserted yet; insert it here. 10252 MachineBasicBlock *JumpMBB = JT->MBB; 10253 CurMF->insert(BBI, JumpMBB); 10254 10255 auto JumpProb = I->Prob; 10256 auto FallthroughProb = UnhandledProbs; 10257 10258 // If the default statement is a target of the jump table, we evenly 10259 // distribute the default probability to successors of CurMBB. Also 10260 // update the probability on the edge from JumpMBB to Fallthrough. 10261 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10262 SE = JumpMBB->succ_end(); 10263 SI != SE; ++SI) { 10264 if (*SI == DefaultMBB) { 10265 JumpProb += DefaultProb / 2; 10266 FallthroughProb -= DefaultProb / 2; 10267 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10268 JumpMBB->normalizeSuccProbs(); 10269 break; 10270 } 10271 } 10272 10273 if (FallthroughUnreachable) { 10274 // Skip the range check if the fallthrough block is unreachable. 10275 JTH->OmitRangeCheck = true; 10276 } 10277 10278 if (!JTH->OmitRangeCheck) 10279 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10280 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10281 CurMBB->normalizeSuccProbs(); 10282 10283 // The jump table header will be inserted in our current block, do the 10284 // range check, and fall through to our fallthrough block. 10285 JTH->HeaderBB = CurMBB; 10286 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10287 10288 // If we're in the right place, emit the jump table header right now. 10289 if (CurMBB == SwitchMBB) { 10290 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10291 JTH->Emitted = true; 10292 } 10293 break; 10294 } 10295 case CC_BitTests: { 10296 // FIXME: Optimize away range check based on pivot comparisons. 10297 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10298 10299 // The bit test blocks haven't been inserted yet; insert them here. 10300 for (BitTestCase &BTC : BTB->Cases) 10301 CurMF->insert(BBI, BTC.ThisBB); 10302 10303 // Fill in fields of the BitTestBlock. 10304 BTB->Parent = CurMBB; 10305 BTB->Default = Fallthrough; 10306 10307 BTB->DefaultProb = UnhandledProbs; 10308 // If the cases in bit test don't form a contiguous range, we evenly 10309 // distribute the probability on the edge to Fallthrough to two 10310 // successors of CurMBB. 10311 if (!BTB->ContiguousRange) { 10312 BTB->Prob += DefaultProb / 2; 10313 BTB->DefaultProb -= DefaultProb / 2; 10314 } 10315 10316 if (FallthroughUnreachable) { 10317 // Skip the range check if the fallthrough block is unreachable. 10318 BTB->OmitRangeCheck = true; 10319 } 10320 10321 // If we're in the right place, emit the bit test header right now. 10322 if (CurMBB == SwitchMBB) { 10323 visitBitTestHeader(*BTB, SwitchMBB); 10324 BTB->Emitted = true; 10325 } 10326 break; 10327 } 10328 case CC_Range: { 10329 const Value *RHS, *LHS, *MHS; 10330 ISD::CondCode CC; 10331 if (I->Low == I->High) { 10332 // Check Cond == I->Low. 10333 CC = ISD::SETEQ; 10334 LHS = Cond; 10335 RHS=I->Low; 10336 MHS = nullptr; 10337 } else { 10338 // Check I->Low <= Cond <= I->High. 10339 CC = ISD::SETLE; 10340 LHS = I->Low; 10341 MHS = Cond; 10342 RHS = I->High; 10343 } 10344 10345 // If Fallthrough is unreachable, fold away the comparison. 10346 if (FallthroughUnreachable) 10347 CC = ISD::SETTRUE; 10348 10349 // The false probability is the sum of all unhandled cases. 10350 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10351 getCurSDLoc(), I->Prob, UnhandledProbs); 10352 10353 if (CurMBB == SwitchMBB) 10354 visitSwitchCase(CB, SwitchMBB); 10355 else 10356 SL->SwitchCases.push_back(CB); 10357 10358 break; 10359 } 10360 } 10361 CurMBB = Fallthrough; 10362 } 10363 } 10364 10365 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10366 CaseClusterIt First, 10367 CaseClusterIt Last) { 10368 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10369 if (X.Prob != CC.Prob) 10370 return X.Prob > CC.Prob; 10371 10372 // Ties are broken by comparing the case value. 10373 return X.Low->getValue().slt(CC.Low->getValue()); 10374 }); 10375 } 10376 10377 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10378 const SwitchWorkListItem &W, 10379 Value *Cond, 10380 MachineBasicBlock *SwitchMBB) { 10381 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10382 "Clusters not sorted?"); 10383 10384 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10385 10386 // Balance the tree based on branch probabilities to create a near-optimal (in 10387 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10388 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10389 CaseClusterIt LastLeft = W.FirstCluster; 10390 CaseClusterIt FirstRight = W.LastCluster; 10391 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10392 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10393 10394 // Move LastLeft and FirstRight towards each other from opposite directions to 10395 // find a partitioning of the clusters which balances the probability on both 10396 // sides. If LeftProb and RightProb are equal, alternate which side is 10397 // taken to ensure 0-probability nodes are distributed evenly. 10398 unsigned I = 0; 10399 while (LastLeft + 1 < FirstRight) { 10400 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10401 LeftProb += (++LastLeft)->Prob; 10402 else 10403 RightProb += (--FirstRight)->Prob; 10404 I++; 10405 } 10406 10407 while (true) { 10408 // Our binary search tree differs from a typical BST in that ours can have up 10409 // to three values in each leaf. The pivot selection above doesn't take that 10410 // into account, which means the tree might require more nodes and be less 10411 // efficient. We compensate for this here. 10412 10413 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10414 unsigned NumRight = W.LastCluster - FirstRight + 1; 10415 10416 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10417 // If one side has less than 3 clusters, and the other has more than 3, 10418 // consider taking a cluster from the other side. 10419 10420 if (NumLeft < NumRight) { 10421 // Consider moving the first cluster on the right to the left side. 10422 CaseCluster &CC = *FirstRight; 10423 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10424 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10425 if (LeftSideRank <= RightSideRank) { 10426 // Moving the cluster to the left does not demote it. 10427 ++LastLeft; 10428 ++FirstRight; 10429 continue; 10430 } 10431 } else { 10432 assert(NumRight < NumLeft); 10433 // Consider moving the last element on the left to the right side. 10434 CaseCluster &CC = *LastLeft; 10435 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10436 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10437 if (RightSideRank <= LeftSideRank) { 10438 // Moving the cluster to the right does not demot it. 10439 --LastLeft; 10440 --FirstRight; 10441 continue; 10442 } 10443 } 10444 } 10445 break; 10446 } 10447 10448 assert(LastLeft + 1 == FirstRight); 10449 assert(LastLeft >= W.FirstCluster); 10450 assert(FirstRight <= W.LastCluster); 10451 10452 // Use the first element on the right as pivot since we will make less-than 10453 // comparisons against it. 10454 CaseClusterIt PivotCluster = FirstRight; 10455 assert(PivotCluster > W.FirstCluster); 10456 assert(PivotCluster <= W.LastCluster); 10457 10458 CaseClusterIt FirstLeft = W.FirstCluster; 10459 CaseClusterIt LastRight = W.LastCluster; 10460 10461 const ConstantInt *Pivot = PivotCluster->Low; 10462 10463 // New blocks will be inserted immediately after the current one. 10464 MachineFunction::iterator BBI(W.MBB); 10465 ++BBI; 10466 10467 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10468 // we can branch to its destination directly if it's squeezed exactly in 10469 // between the known lower bound and Pivot - 1. 10470 MachineBasicBlock *LeftMBB; 10471 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10472 FirstLeft->Low == W.GE && 10473 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10474 LeftMBB = FirstLeft->MBB; 10475 } else { 10476 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10477 FuncInfo.MF->insert(BBI, LeftMBB); 10478 WorkList.push_back( 10479 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10480 // Put Cond in a virtual register to make it available from the new blocks. 10481 ExportFromCurrentBlock(Cond); 10482 } 10483 10484 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10485 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10486 // directly if RHS.High equals the current upper bound. 10487 MachineBasicBlock *RightMBB; 10488 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10489 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10490 RightMBB = FirstRight->MBB; 10491 } else { 10492 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10493 FuncInfo.MF->insert(BBI, RightMBB); 10494 WorkList.push_back( 10495 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10496 // Put Cond in a virtual register to make it available from the new blocks. 10497 ExportFromCurrentBlock(Cond); 10498 } 10499 10500 // Create the CaseBlock record that will be used to lower the branch. 10501 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10502 getCurSDLoc(), LeftProb, RightProb); 10503 10504 if (W.MBB == SwitchMBB) 10505 visitSwitchCase(CB, SwitchMBB); 10506 else 10507 SL->SwitchCases.push_back(CB); 10508 } 10509 10510 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10511 // from the swith statement. 10512 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10513 BranchProbability PeeledCaseProb) { 10514 if (PeeledCaseProb == BranchProbability::getOne()) 10515 return BranchProbability::getZero(); 10516 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10517 10518 uint32_t Numerator = CaseProb.getNumerator(); 10519 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10520 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10521 } 10522 10523 // Try to peel the top probability case if it exceeds the threshold. 10524 // Return current MachineBasicBlock for the switch statement if the peeling 10525 // does not occur. 10526 // If the peeling is performed, return the newly created MachineBasicBlock 10527 // for the peeled switch statement. Also update Clusters to remove the peeled 10528 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10529 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10530 const SwitchInst &SI, CaseClusterVector &Clusters, 10531 BranchProbability &PeeledCaseProb) { 10532 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10533 // Don't perform if there is only one cluster or optimizing for size. 10534 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10535 TM.getOptLevel() == CodeGenOpt::None || 10536 SwitchMBB->getParent()->getFunction().hasMinSize()) 10537 return SwitchMBB; 10538 10539 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10540 unsigned PeeledCaseIndex = 0; 10541 bool SwitchPeeled = false; 10542 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10543 CaseCluster &CC = Clusters[Index]; 10544 if (CC.Prob < TopCaseProb) 10545 continue; 10546 TopCaseProb = CC.Prob; 10547 PeeledCaseIndex = Index; 10548 SwitchPeeled = true; 10549 } 10550 if (!SwitchPeeled) 10551 return SwitchMBB; 10552 10553 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10554 << TopCaseProb << "\n"); 10555 10556 // Record the MBB for the peeled switch statement. 10557 MachineFunction::iterator BBI(SwitchMBB); 10558 ++BBI; 10559 MachineBasicBlock *PeeledSwitchMBB = 10560 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10561 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10562 10563 ExportFromCurrentBlock(SI.getCondition()); 10564 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10565 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10566 nullptr, nullptr, TopCaseProb.getCompl()}; 10567 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10568 10569 Clusters.erase(PeeledCaseIt); 10570 for (CaseCluster &CC : Clusters) { 10571 LLVM_DEBUG( 10572 dbgs() << "Scale the probablity for one cluster, before scaling: " 10573 << CC.Prob << "\n"); 10574 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10575 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10576 } 10577 PeeledCaseProb = TopCaseProb; 10578 return PeeledSwitchMBB; 10579 } 10580 10581 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10582 // Extract cases from the switch. 10583 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10584 CaseClusterVector Clusters; 10585 Clusters.reserve(SI.getNumCases()); 10586 for (auto I : SI.cases()) { 10587 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10588 const ConstantInt *CaseVal = I.getCaseValue(); 10589 BranchProbability Prob = 10590 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10591 : BranchProbability(1, SI.getNumCases() + 1); 10592 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10593 } 10594 10595 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10596 10597 // Cluster adjacent cases with the same destination. We do this at all 10598 // optimization levels because it's cheap to do and will make codegen faster 10599 // if there are many clusters. 10600 sortAndRangeify(Clusters); 10601 10602 // The branch probablity of the peeled case. 10603 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10604 MachineBasicBlock *PeeledSwitchMBB = 10605 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10606 10607 // If there is only the default destination, jump there directly. 10608 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10609 if (Clusters.empty()) { 10610 assert(PeeledSwitchMBB == SwitchMBB); 10611 SwitchMBB->addSuccessor(DefaultMBB); 10612 if (DefaultMBB != NextBlock(SwitchMBB)) { 10613 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10614 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10615 } 10616 return; 10617 } 10618 10619 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10620 SL->findBitTestClusters(Clusters, &SI); 10621 10622 LLVM_DEBUG({ 10623 dbgs() << "Case clusters: "; 10624 for (const CaseCluster &C : Clusters) { 10625 if (C.Kind == CC_JumpTable) 10626 dbgs() << "JT:"; 10627 if (C.Kind == CC_BitTests) 10628 dbgs() << "BT:"; 10629 10630 C.Low->getValue().print(dbgs(), true); 10631 if (C.Low != C.High) { 10632 dbgs() << '-'; 10633 C.High->getValue().print(dbgs(), true); 10634 } 10635 dbgs() << ' '; 10636 } 10637 dbgs() << '\n'; 10638 }); 10639 10640 assert(!Clusters.empty()); 10641 SwitchWorkList WorkList; 10642 CaseClusterIt First = Clusters.begin(); 10643 CaseClusterIt Last = Clusters.end() - 1; 10644 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10645 // Scale the branchprobability for DefaultMBB if the peel occurs and 10646 // DefaultMBB is not replaced. 10647 if (PeeledCaseProb != BranchProbability::getZero() && 10648 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10649 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10650 WorkList.push_back( 10651 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10652 10653 while (!WorkList.empty()) { 10654 SwitchWorkListItem W = WorkList.back(); 10655 WorkList.pop_back(); 10656 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10657 10658 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10659 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10660 // For optimized builds, lower large range as a balanced binary tree. 10661 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10662 continue; 10663 } 10664 10665 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10666 } 10667 } 10668 10669 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10670 SmallVector<EVT, 4> ValueVTs; 10671 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10672 ValueVTs); 10673 unsigned NumValues = ValueVTs.size(); 10674 if (NumValues == 0) return; 10675 10676 SmallVector<SDValue, 4> Values(NumValues); 10677 SDValue Op = getValue(I.getOperand(0)); 10678 10679 for (unsigned i = 0; i != NumValues; ++i) 10680 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10681 SDValue(Op.getNode(), Op.getResNo() + i)); 10682 10683 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10684 DAG.getVTList(ValueVTs), Values)); 10685 } 10686