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