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/AliasAnalysis.h" 27 #include "llvm/Analysis/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/EHPersonalities.h" 31 #include "llvm/Analysis/Loads.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/ProfileSummaryInfo.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/Analysis/VectorUtils.h" 37 #include "llvm/CodeGen/Analysis.h" 38 #include "llvm/CodeGen/FunctionLoweringInfo.h" 39 #include "llvm/CodeGen/GCMetadata.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 53 #include "llvm/CodeGen/StackMaps.h" 54 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 55 #include "llvm/CodeGen/TargetFrameLowering.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetOpcodes.h" 58 #include "llvm/CodeGen/TargetRegisterInfo.h" 59 #include "llvm/CodeGen/TargetSubtargetInfo.h" 60 #include "llvm/CodeGen/WinEHFuncInfo.h" 61 #include "llvm/IR/Argument.h" 62 #include "llvm/IR/Attributes.h" 63 #include "llvm/IR/BasicBlock.h" 64 #include "llvm/IR/CFG.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/ConstantRange.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugInfoMetadata.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/DiagnosticInfo.h" 73 #include "llvm/IR/Function.h" 74 #include "llvm/IR/GetElementPtrTypeIterator.h" 75 #include "llvm/IR/InlineAsm.h" 76 #include "llvm/IR/InstrTypes.h" 77 #include "llvm/IR/Instructions.h" 78 #include "llvm/IR/IntrinsicInst.h" 79 #include "llvm/IR/Intrinsics.h" 80 #include "llvm/IR/IntrinsicsAArch64.h" 81 #include "llvm/IR/IntrinsicsWebAssembly.h" 82 #include "llvm/IR/LLVMContext.h" 83 #include "llvm/IR/Metadata.h" 84 #include "llvm/IR/Module.h" 85 #include "llvm/IR/Operator.h" 86 #include "llvm/IR/PatternMatch.h" 87 #include "llvm/IR/Statepoint.h" 88 #include "llvm/IR/Type.h" 89 #include "llvm/IR/User.h" 90 #include "llvm/IR/Value.h" 91 #include "llvm/MC/MCContext.h" 92 #include "llvm/MC/MCSymbol.h" 93 #include "llvm/Support/AtomicOrdering.h" 94 #include "llvm/Support/Casting.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/MathExtras.h" 99 #include "llvm/Support/raw_ostream.h" 100 #include "llvm/Target/TargetIntrinsicInfo.h" 101 #include "llvm/Target/TargetMachine.h" 102 #include "llvm/Target/TargetOptions.h" 103 #include "llvm/Transforms/Utils/Local.h" 104 #include <cstddef> 105 #include <cstring> 106 #include <iterator> 107 #include <limits> 108 #include <numeric> 109 #include <tuple> 110 111 using namespace llvm; 112 using namespace PatternMatch; 113 using namespace SwitchCG; 114 115 #define DEBUG_TYPE "isel" 116 117 /// LimitFloatPrecision - Generate low-precision inline sequences for 118 /// some float libcalls (6, 8 or 12 bits). 119 static unsigned LimitFloatPrecision; 120 121 static cl::opt<bool> 122 InsertAssertAlign("insert-assert-align", cl::init(true), 123 cl::desc("Insert the experimental `assertalign` node."), 124 cl::ReallyHidden); 125 126 static cl::opt<unsigned, true> 127 LimitFPPrecision("limit-float-precision", 128 cl::desc("Generate low-precision inline sequences " 129 "for some float libcalls"), 130 cl::location(LimitFloatPrecision), cl::Hidden, 131 cl::init(0)); 132 133 static cl::opt<unsigned> SwitchPeelThreshold( 134 "switch-peel-threshold", cl::Hidden, cl::init(66), 135 cl::desc("Set the case probability threshold for peeling the case from a " 136 "switch statement. A value greater than 100 will void this " 137 "optimization")); 138 139 // Limit the width of DAG chains. This is important in general to prevent 140 // DAG-based analysis from blowing up. For example, alias analysis and 141 // load clustering may not complete in reasonable time. It is difficult to 142 // recognize and avoid this situation within each individual analysis, and 143 // future analyses are likely to have the same behavior. Limiting DAG width is 144 // the safe approach and will be especially important with global DAGs. 145 // 146 // MaxParallelChains default is arbitrarily high to avoid affecting 147 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 148 // sequence over this should have been converted to llvm.memcpy by the 149 // frontend. It is easy to induce this behavior with .ll code such as: 150 // %buffer = alloca [4096 x i8] 151 // %data = load [4096 x i8]* %argPtr 152 // store [4096 x i8] %data, [4096 x i8]* %buffer 153 static const unsigned MaxParallelChains = 64; 154 155 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 156 const SDValue *Parts, unsigned NumParts, 157 MVT PartVT, EVT ValueVT, const Value *V, 158 Optional<CallingConv::ID> CC); 159 160 /// getCopyFromParts - Create a value that contains the specified legal parts 161 /// combined into the value they represent. If the parts combine to a type 162 /// larger than ValueVT then AssertOp can be used to specify whether the extra 163 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 164 /// (ISD::AssertSext). 165 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 166 const SDValue *Parts, unsigned NumParts, 167 MVT PartVT, EVT ValueVT, const Value *V, 168 Optional<CallingConv::ID> CC = None, 169 Optional<ISD::NodeType> AssertOp = None) { 170 // Let the target assemble the parts if it wants to 171 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 172 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 173 PartVT, ValueVT, CC)) 174 return Val; 175 176 if (ValueVT.isVector()) 177 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 178 CC); 179 180 assert(NumParts > 0 && "No parts to assemble!"); 181 SDValue Val = Parts[0]; 182 183 if (NumParts > 1) { 184 // Assemble the value from multiple parts. 185 if (ValueVT.isInteger()) { 186 unsigned PartBits = PartVT.getSizeInBits(); 187 unsigned ValueBits = ValueVT.getSizeInBits(); 188 189 // Assemble the power of 2 part. 190 unsigned RoundParts = 191 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 192 unsigned RoundBits = PartBits * RoundParts; 193 EVT RoundVT = RoundBits == ValueBits ? 194 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 195 SDValue Lo, Hi; 196 197 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 198 199 if (RoundParts > 2) { 200 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 201 PartVT, HalfVT, V); 202 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 203 RoundParts / 2, PartVT, HalfVT, V); 204 } else { 205 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 206 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 207 } 208 209 if (DAG.getDataLayout().isBigEndian()) 210 std::swap(Lo, Hi); 211 212 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 213 214 if (RoundParts < NumParts) { 215 // Assemble the trailing non-power-of-2 part. 216 unsigned OddParts = NumParts - RoundParts; 217 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 218 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 219 OddVT, V, CC); 220 221 // Combine the round and odd parts. 222 Lo = Val; 223 if (DAG.getDataLayout().isBigEndian()) 224 std::swap(Lo, Hi); 225 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 226 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 227 Hi = 228 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 229 DAG.getConstant(Lo.getValueSizeInBits(), DL, 230 TLI.getPointerTy(DAG.getDataLayout()))); 231 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 232 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 233 } 234 } else if (PartVT.isFloatingPoint()) { 235 // FP split into multiple FP parts (for ppcf128) 236 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 237 "Unexpected split"); 238 SDValue Lo, Hi; 239 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 240 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 241 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 242 std::swap(Lo, Hi); 243 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 244 } else { 245 // FP split into integer parts (soft fp) 246 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 247 !PartVT.isVector() && "Unexpected split"); 248 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 249 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 250 } 251 } 252 253 // There is now one part, held in Val. Correct it to match ValueVT. 254 // PartEVT is the type of the register class that holds the value. 255 // ValueVT is the type of the inline asm operation. 256 EVT PartEVT = Val.getValueType(); 257 258 if (PartEVT == ValueVT) 259 return Val; 260 261 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 262 ValueVT.bitsLT(PartEVT)) { 263 // For an FP value in an integer part, we need to truncate to the right 264 // width first. 265 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 266 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 267 } 268 269 // Handle types that have the same size. 270 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 271 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 272 273 // Handle types with different sizes. 274 if (PartEVT.isInteger() && ValueVT.isInteger()) { 275 if (ValueVT.bitsLT(PartEVT)) { 276 // For a truncate, see if we have any information to 277 // indicate whether the truncated bits will always be 278 // zero or sign-extension. 279 if (AssertOp.hasValue()) 280 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 281 DAG.getValueType(ValueVT)); 282 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 283 } 284 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 285 } 286 287 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 288 // FP_ROUND's are always exact here. 289 if (ValueVT.bitsLT(Val.getValueType())) 290 return DAG.getNode( 291 ISD::FP_ROUND, DL, ValueVT, Val, 292 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 293 294 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 295 } 296 297 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 298 // then truncating. 299 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 300 ValueVT.bitsLT(PartEVT)) { 301 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 302 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 303 } 304 305 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 306 } 307 308 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 309 const Twine &ErrMsg) { 310 const Instruction *I = dyn_cast_or_null<Instruction>(V); 311 if (!V) 312 return Ctx.emitError(ErrMsg); 313 314 const char *AsmError = ", possible invalid constraint for vector type"; 315 if (const CallInst *CI = dyn_cast<CallInst>(I)) 316 if (CI->isInlineAsm()) 317 return Ctx.emitError(I, ErrMsg + AsmError); 318 319 return Ctx.emitError(I, ErrMsg); 320 } 321 322 /// getCopyFromPartsVector - Create a value that contains the specified legal 323 /// parts combined into the value they represent. If the parts combine to a 324 /// type larger than ValueVT then AssertOp can be used to specify whether the 325 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 326 /// ValueVT (ISD::AssertSext). 327 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 328 const SDValue *Parts, unsigned NumParts, 329 MVT PartVT, EVT ValueVT, const Value *V, 330 Optional<CallingConv::ID> CallConv) { 331 assert(ValueVT.isVector() && "Not a vector value"); 332 assert(NumParts > 0 && "No parts to assemble!"); 333 const bool IsABIRegCopy = CallConv.hasValue(); 334 335 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 336 SDValue Val = Parts[0]; 337 338 // Handle a multi-element vector. 339 if (NumParts > 1) { 340 EVT IntermediateVT; 341 MVT RegisterVT; 342 unsigned NumIntermediates; 343 unsigned NumRegs; 344 345 if (IsABIRegCopy) { 346 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 347 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 348 NumIntermediates, RegisterVT); 349 } else { 350 NumRegs = 351 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 352 NumIntermediates, RegisterVT); 353 } 354 355 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 356 NumParts = NumRegs; // Silence a compiler warning. 357 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 358 assert(RegisterVT.getSizeInBits() == 359 Parts[0].getSimpleValueType().getSizeInBits() && 360 "Part type sizes don't match!"); 361 362 // Assemble the parts into intermediate operands. 363 SmallVector<SDValue, 8> Ops(NumIntermediates); 364 if (NumIntermediates == NumParts) { 365 // If the register was not expanded, truncate or copy the value, 366 // as appropriate. 367 for (unsigned i = 0; i != NumParts; ++i) 368 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 369 PartVT, IntermediateVT, V, CallConv); 370 } else if (NumParts > 0) { 371 // If the intermediate type was expanded, build the intermediate 372 // operands from the parts. 373 assert(NumParts % NumIntermediates == 0 && 374 "Must expand into a divisible number of parts!"); 375 unsigned Factor = NumParts / NumIntermediates; 376 for (unsigned i = 0; i != NumIntermediates; ++i) 377 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 378 PartVT, IntermediateVT, V, CallConv); 379 } 380 381 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 382 // intermediate operands. 383 EVT BuiltVectorTy = 384 IntermediateVT.isVector() 385 ? EVT::getVectorVT( 386 *DAG.getContext(), IntermediateVT.getScalarType(), 387 IntermediateVT.getVectorElementCount() * NumParts) 388 : EVT::getVectorVT(*DAG.getContext(), 389 IntermediateVT.getScalarType(), 390 NumIntermediates); 391 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 392 : ISD::BUILD_VECTOR, 393 DL, BuiltVectorTy, Ops); 394 } 395 396 // There is now one part, held in Val. Correct it to match ValueVT. 397 EVT PartEVT = Val.getValueType(); 398 399 if (PartEVT == ValueVT) 400 return Val; 401 402 if (PartEVT.isVector()) { 403 // Vector/Vector bitcast. 404 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 405 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 406 407 // If the element type of the source/dest vectors are the same, but the 408 // parts vector has more elements than the value vector, then we have a 409 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 410 // elements we want. 411 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 412 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 413 ValueVT.getVectorElementCount().getKnownMinValue()) && 414 (PartEVT.getVectorElementCount().isScalable() == 415 ValueVT.getVectorElementCount().isScalable()) && 416 "Cannot narrow, it would be a lossy transformation"); 417 PartEVT = 418 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 419 ValueVT.getVectorElementCount()); 420 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 421 DAG.getVectorIdxConstant(0, DL)); 422 if (PartEVT == ValueVT) 423 return Val; 424 } 425 426 // Promoted vector extract 427 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 428 } 429 430 // Trivial bitcast if the types are the same size and the destination 431 // vector type is legal. 432 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 433 TLI.isTypeLegal(ValueVT)) 434 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 435 436 if (ValueVT.getVectorNumElements() != 1) { 437 // Certain ABIs require that vectors are passed as integers. For vectors 438 // are the same size, this is an obvious bitcast. 439 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 440 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 441 } else if (ValueVT.bitsLT(PartEVT)) { 442 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 443 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 444 // Drop the extra bits. 445 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 446 return DAG.getBitcast(ValueVT, Val); 447 } 448 449 diagnosePossiblyInvalidConstraint( 450 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 451 return DAG.getUNDEF(ValueVT); 452 } 453 454 // Handle cases such as i8 -> <1 x i1> 455 EVT ValueSVT = ValueVT.getVectorElementType(); 456 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 457 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 458 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 459 else 460 Val = ValueVT.isFloatingPoint() 461 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 462 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 463 } 464 465 return DAG.getBuildVector(ValueVT, DL, Val); 466 } 467 468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 469 SDValue Val, SDValue *Parts, unsigned NumParts, 470 MVT PartVT, const Value *V, 471 Optional<CallingConv::ID> CallConv); 472 473 /// getCopyToParts - Create a series of nodes that contain the specified value 474 /// split into legal parts. If the parts contain more bits than Val, then, for 475 /// integers, ExtendKind can be used to specify how to generate the extra bits. 476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 477 SDValue *Parts, unsigned NumParts, MVT PartVT, 478 const Value *V, 479 Optional<CallingConv::ID> CallConv = None, 480 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 481 // Let the target split the parts if it wants to 482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 483 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 484 CallConv)) 485 return; 486 EVT ValueVT = Val.getValueType(); 487 488 // Handle the vector case separately. 489 if (ValueVT.isVector()) 490 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 491 CallConv); 492 493 unsigned PartBits = PartVT.getSizeInBits(); 494 unsigned OrigNumParts = NumParts; 495 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 496 "Copying to an illegal type!"); 497 498 if (NumParts == 0) 499 return; 500 501 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 502 EVT PartEVT = PartVT; 503 if (PartEVT == ValueVT) { 504 assert(NumParts == 1 && "No-op copy with multiple parts!"); 505 Parts[0] = Val; 506 return; 507 } 508 509 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 510 // If the parts cover more bits than the value has, promote the value. 511 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 512 assert(NumParts == 1 && "Do not know what to promote to!"); 513 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 514 } else { 515 if (ValueVT.isFloatingPoint()) { 516 // FP values need to be bitcast, then extended if they are being put 517 // into a larger container. 518 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 519 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 520 } 521 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 522 ValueVT.isInteger() && 523 "Unknown mismatch!"); 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 525 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 526 if (PartVT == MVT::x86mmx) 527 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 528 } 529 } else if (PartBits == ValueVT.getSizeInBits()) { 530 // Different types of the same size. 531 assert(NumParts == 1 && PartEVT != ValueVT); 532 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 533 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 534 // If the parts cover less bits than value has, truncate the value. 535 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 536 ValueVT.isInteger() && 537 "Unknown mismatch!"); 538 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 539 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 540 if (PartVT == MVT::x86mmx) 541 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 542 } 543 544 // The value may have changed - recompute ValueVT. 545 ValueVT = Val.getValueType(); 546 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 547 "Failed to tile the value with PartVT!"); 548 549 if (NumParts == 1) { 550 if (PartEVT != ValueVT) { 551 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 552 "scalar-to-vector conversion failed"); 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 556 Parts[0] = Val; 557 return; 558 } 559 560 // Expand the value into multiple parts. 561 if (NumParts & (NumParts - 1)) { 562 // The number of parts is not a power of 2. Split off and copy the tail. 563 assert(PartVT.isInteger() && ValueVT.isInteger() && 564 "Do not know what to expand to!"); 565 unsigned RoundParts = 1 << Log2_32(NumParts); 566 unsigned RoundBits = RoundParts * PartBits; 567 unsigned OddParts = NumParts - RoundParts; 568 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 569 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 570 571 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 572 CallConv); 573 574 if (DAG.getDataLayout().isBigEndian()) 575 // The odd parts were reversed by getCopyToParts - unreverse them. 576 std::reverse(Parts + RoundParts, Parts + NumParts); 577 578 NumParts = RoundParts; 579 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 580 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 581 } 582 583 // The number of parts is a power of 2. Repeatedly bisect the value using 584 // EXTRACT_ELEMENT. 585 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 586 EVT::getIntegerVT(*DAG.getContext(), 587 ValueVT.getSizeInBits()), 588 Val); 589 590 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 591 for (unsigned i = 0; i < NumParts; i += StepSize) { 592 unsigned ThisBits = StepSize * PartBits / 2; 593 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 594 SDValue &Part0 = Parts[i]; 595 SDValue &Part1 = Parts[i+StepSize/2]; 596 597 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 598 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 599 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 600 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 601 602 if (ThisBits == PartBits && ThisVT != PartVT) { 603 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 604 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 605 } 606 } 607 } 608 609 if (DAG.getDataLayout().isBigEndian()) 610 std::reverse(Parts, Parts + OrigNumParts); 611 } 612 613 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 614 const SDLoc &DL, EVT PartVT) { 615 if (!PartVT.isVector()) 616 return SDValue(); 617 618 EVT ValueVT = Val.getValueType(); 619 ElementCount PartNumElts = PartVT.getVectorElementCount(); 620 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 621 622 // We only support widening vectors with equivalent element types and 623 // fixed/scalable properties. If a target needs to widen a fixed-length type 624 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 625 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 626 PartNumElts.isScalable() != ValueNumElts.isScalable() || 627 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 628 return SDValue(); 629 630 // Widening a scalable vector to another scalable vector is done by inserting 631 // the vector into a larger undef one. 632 if (PartNumElts.isScalable()) 633 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 634 Val, DAG.getVectorIdxConstant(0, DL)); 635 636 EVT ElementVT = PartVT.getVectorElementType(); 637 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 638 // undef elements. 639 SmallVector<SDValue, 16> Ops; 640 DAG.ExtractVectorElements(Val, Ops); 641 SDValue EltUndef = DAG.getUNDEF(ElementVT); 642 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 643 644 // FIXME: Use CONCAT for 2x -> 4x. 645 return DAG.getBuildVector(PartVT, DL, Ops); 646 } 647 648 /// getCopyToPartsVector - Create a series of nodes that contain the specified 649 /// value split into legal parts. 650 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 651 SDValue Val, SDValue *Parts, unsigned NumParts, 652 MVT PartVT, const Value *V, 653 Optional<CallingConv::ID> CallConv) { 654 EVT ValueVT = Val.getValueType(); 655 assert(ValueVT.isVector() && "Not a vector"); 656 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 657 const bool IsABIRegCopy = CallConv.hasValue(); 658 659 if (NumParts == 1) { 660 EVT PartEVT = PartVT; 661 if (PartEVT == ValueVT) { 662 // Nothing to do. 663 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 664 // Bitconvert vector->vector case. 665 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 666 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 667 Val = Widened; 668 } else if (PartVT.isVector() && 669 PartEVT.getVectorElementType().bitsGE( 670 ValueVT.getVectorElementType()) && 671 PartEVT.getVectorElementCount() == 672 ValueVT.getVectorElementCount()) { 673 674 // Promoted vector extract 675 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 676 } else if (PartEVT.isVector() && 677 PartEVT.getVectorElementType() != 678 ValueVT.getVectorElementType() && 679 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 680 TargetLowering::TypeWidenVector) { 681 // Combination of widening and promotion. 682 EVT WidenVT = 683 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 684 PartVT.getVectorElementCount()); 685 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 686 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 687 } else { 688 if (ValueVT.getVectorElementCount().isScalar()) { 689 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 690 DAG.getVectorIdxConstant(0, DL)); 691 } else { 692 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 693 assert(PartVT.getFixedSizeInBits() > ValueSize && 694 "lossy conversion of vector to scalar type"); 695 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 696 Val = DAG.getBitcast(IntermediateType, Val); 697 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 698 } 699 } 700 701 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 702 Parts[0] = Val; 703 return; 704 } 705 706 // Handle a multi-element vector. 707 EVT IntermediateVT; 708 MVT RegisterVT; 709 unsigned NumIntermediates; 710 unsigned NumRegs; 711 if (IsABIRegCopy) { 712 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 713 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 714 NumIntermediates, RegisterVT); 715 } else { 716 NumRegs = 717 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 718 NumIntermediates, RegisterVT); 719 } 720 721 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 722 NumParts = NumRegs; // Silence a compiler warning. 723 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 724 725 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 726 "Mixing scalable and fixed vectors when copying in parts"); 727 728 Optional<ElementCount> DestEltCnt; 729 730 if (IntermediateVT.isVector()) 731 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 732 else 733 DestEltCnt = ElementCount::getFixed(NumIntermediates); 734 735 EVT BuiltVectorTy = EVT::getVectorVT( 736 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 737 738 if (ValueVT == BuiltVectorTy) { 739 // Nothing to do. 740 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 741 // Bitconvert vector->vector case. 742 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 743 } else { 744 if (BuiltVectorTy.getVectorElementType().bitsGT( 745 ValueVT.getVectorElementType())) { 746 // Integer promotion. 747 ValueVT = EVT::getVectorVT(*DAG.getContext(), 748 BuiltVectorTy.getVectorElementType(), 749 ValueVT.getVectorElementCount()); 750 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 751 } 752 753 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 754 Val = Widened; 755 } 756 } 757 758 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 759 760 // Split the vector into intermediate operands. 761 SmallVector<SDValue, 8> Ops(NumIntermediates); 762 for (unsigned i = 0; i != NumIntermediates; ++i) { 763 if (IntermediateVT.isVector()) { 764 // This does something sensible for scalable vectors - see the 765 // definition of EXTRACT_SUBVECTOR for further details. 766 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 767 Ops[i] = 768 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 769 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 770 } else { 771 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 772 DAG.getVectorIdxConstant(i, DL)); 773 } 774 } 775 776 // Split the intermediate operands into legal parts. 777 if (NumParts == NumIntermediates) { 778 // If the register was not expanded, promote or copy the value, 779 // as appropriate. 780 for (unsigned i = 0; i != NumParts; ++i) 781 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 782 } else if (NumParts > 0) { 783 // If the intermediate type was expanded, split each the value into 784 // legal parts. 785 assert(NumIntermediates != 0 && "division by zero"); 786 assert(NumParts % NumIntermediates == 0 && 787 "Must expand into a divisible number of parts!"); 788 unsigned Factor = NumParts / NumIntermediates; 789 for (unsigned i = 0; i != NumIntermediates; ++i) 790 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 791 CallConv); 792 } 793 } 794 795 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 796 EVT valuevt, Optional<CallingConv::ID> CC) 797 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 798 RegCount(1, regs.size()), CallConv(CC) {} 799 800 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 801 const DataLayout &DL, unsigned Reg, Type *Ty, 802 Optional<CallingConv::ID> CC) { 803 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 804 805 CallConv = CC; 806 807 for (EVT ValueVT : ValueVTs) { 808 unsigned NumRegs = 809 isABIMangled() 810 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 811 : TLI.getNumRegisters(Context, ValueVT); 812 MVT RegisterVT = 813 isABIMangled() 814 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 815 : TLI.getRegisterType(Context, ValueVT); 816 for (unsigned i = 0; i != NumRegs; ++i) 817 Regs.push_back(Reg + i); 818 RegVTs.push_back(RegisterVT); 819 RegCount.push_back(NumRegs); 820 Reg += NumRegs; 821 } 822 } 823 824 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 825 FunctionLoweringInfo &FuncInfo, 826 const SDLoc &dl, SDValue &Chain, 827 SDValue *Flag, const Value *V) const { 828 // A Value with type {} or [0 x %t] needs no registers. 829 if (ValueVTs.empty()) 830 return SDValue(); 831 832 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 833 834 // Assemble the legal parts into the final values. 835 SmallVector<SDValue, 4> Values(ValueVTs.size()); 836 SmallVector<SDValue, 8> Parts; 837 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 838 // Copy the legal parts from the registers. 839 EVT ValueVT = ValueVTs[Value]; 840 unsigned NumRegs = RegCount[Value]; 841 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 842 *DAG.getContext(), 843 CallConv.getValue(), RegVTs[Value]) 844 : RegVTs[Value]; 845 846 Parts.resize(NumRegs); 847 for (unsigned i = 0; i != NumRegs; ++i) { 848 SDValue P; 849 if (!Flag) { 850 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 851 } else { 852 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 853 *Flag = P.getValue(2); 854 } 855 856 Chain = P.getValue(1); 857 Parts[i] = P; 858 859 // If the source register was virtual and if we know something about it, 860 // add an assert node. 861 if (!Register::isVirtualRegister(Regs[Part + i]) || 862 !RegisterVT.isInteger()) 863 continue; 864 865 const FunctionLoweringInfo::LiveOutInfo *LOI = 866 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 867 if (!LOI) 868 continue; 869 870 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 871 unsigned NumSignBits = LOI->NumSignBits; 872 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 873 874 if (NumZeroBits == RegSize) { 875 // The current value is a zero. 876 // Explicitly express that as it would be easier for 877 // optimizations to kick in. 878 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 879 continue; 880 } 881 882 // FIXME: We capture more information than the dag can represent. For 883 // now, just use the tightest assertzext/assertsext possible. 884 bool isSExt; 885 EVT FromVT(MVT::Other); 886 if (NumZeroBits) { 887 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 888 isSExt = false; 889 } else if (NumSignBits > 1) { 890 FromVT = 891 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 892 isSExt = true; 893 } else { 894 continue; 895 } 896 // Add an assertion node. 897 assert(FromVT != MVT::Other); 898 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 899 RegisterVT, P, DAG.getValueType(FromVT)); 900 } 901 902 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 903 RegisterVT, ValueVT, V, CallConv); 904 Part += NumRegs; 905 Parts.clear(); 906 } 907 908 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 909 } 910 911 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 912 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 913 const Value *V, 914 ISD::NodeType PreferredExtendType) const { 915 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 916 ISD::NodeType ExtendKind = PreferredExtendType; 917 918 // Get the list of the values's legal parts. 919 unsigned NumRegs = Regs.size(); 920 SmallVector<SDValue, 8> Parts(NumRegs); 921 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 922 unsigned NumParts = RegCount[Value]; 923 924 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 925 *DAG.getContext(), 926 CallConv.getValue(), RegVTs[Value]) 927 : RegVTs[Value]; 928 929 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 930 ExtendKind = ISD::ZERO_EXTEND; 931 932 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 933 NumParts, RegisterVT, V, CallConv, ExtendKind); 934 Part += NumParts; 935 } 936 937 // Copy the parts into the registers. 938 SmallVector<SDValue, 8> Chains(NumRegs); 939 for (unsigned i = 0; i != NumRegs; ++i) { 940 SDValue Part; 941 if (!Flag) { 942 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 943 } else { 944 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 945 *Flag = Part.getValue(1); 946 } 947 948 Chains[i] = Part.getValue(0); 949 } 950 951 if (NumRegs == 1 || Flag) 952 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 953 // flagged to it. That is the CopyToReg nodes and the user are considered 954 // a single scheduling unit. If we create a TokenFactor and return it as 955 // chain, then the TokenFactor is both a predecessor (operand) of the 956 // user as well as a successor (the TF operands are flagged to the user). 957 // c1, f1 = CopyToReg 958 // c2, f2 = CopyToReg 959 // c3 = TokenFactor c1, c2 960 // ... 961 // = op c3, ..., f2 962 Chain = Chains[NumRegs-1]; 963 else 964 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 965 } 966 967 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 968 unsigned MatchingIdx, const SDLoc &dl, 969 SelectionDAG &DAG, 970 std::vector<SDValue> &Ops) const { 971 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 972 973 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 974 if (HasMatching) 975 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 976 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 977 // Put the register class of the virtual registers in the flag word. That 978 // way, later passes can recompute register class constraints for inline 979 // assembly as well as normal instructions. 980 // Don't do this for tied operands that can use the regclass information 981 // from the def. 982 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 983 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 984 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 985 } 986 987 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 988 Ops.push_back(Res); 989 990 if (Code == InlineAsm::Kind_Clobber) { 991 // Clobbers should always have a 1:1 mapping with registers, and may 992 // reference registers that have illegal (e.g. vector) types. Hence, we 993 // shouldn't try to apply any sort of splitting logic to them. 994 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 995 "No 1:1 mapping from clobbers to regs?"); 996 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 997 (void)SP; 998 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 999 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1000 assert( 1001 (Regs[I] != SP || 1002 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1003 "If we clobbered the stack pointer, MFI should know about it."); 1004 } 1005 return; 1006 } 1007 1008 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1009 MVT RegisterVT = RegVTs[Value]; 1010 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1011 RegisterVT); 1012 for (unsigned i = 0; i != NumRegs; ++i) { 1013 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1014 unsigned TheReg = Regs[Reg++]; 1015 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1016 } 1017 } 1018 } 1019 1020 SmallVector<std::pair<unsigned, TypeSize>, 4> 1021 RegsForValue::getRegsAndSizes() const { 1022 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1023 unsigned I = 0; 1024 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1025 unsigned RegCount = std::get<0>(CountAndVT); 1026 MVT RegisterVT = std::get<1>(CountAndVT); 1027 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1028 for (unsigned E = I + RegCount; I != E; ++I) 1029 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1030 } 1031 return OutVec; 1032 } 1033 1034 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1035 const TargetLibraryInfo *li) { 1036 AA = aa; 1037 GFI = gfi; 1038 LibInfo = li; 1039 Context = DAG.getContext(); 1040 LPadToCallSiteMap.clear(); 1041 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1042 } 1043 1044 void SelectionDAGBuilder::clear() { 1045 NodeMap.clear(); 1046 UnusedArgNodeMap.clear(); 1047 PendingLoads.clear(); 1048 PendingExports.clear(); 1049 PendingConstrainedFP.clear(); 1050 PendingConstrainedFPStrict.clear(); 1051 CurInst = nullptr; 1052 HasTailCall = false; 1053 SDNodeOrder = LowestSDNodeOrder; 1054 StatepointLowering.clear(); 1055 } 1056 1057 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1058 DanglingDebugInfoMap.clear(); 1059 } 1060 1061 // Update DAG root to include dependencies on Pending chains. 1062 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1063 SDValue Root = DAG.getRoot(); 1064 1065 if (Pending.empty()) 1066 return Root; 1067 1068 // Add current root to PendingChains, unless we already indirectly 1069 // depend on it. 1070 if (Root.getOpcode() != ISD::EntryToken) { 1071 unsigned i = 0, e = Pending.size(); 1072 for (; i != e; ++i) { 1073 assert(Pending[i].getNode()->getNumOperands() > 1); 1074 if (Pending[i].getNode()->getOperand(0) == Root) 1075 break; // Don't add the root if we already indirectly depend on it. 1076 } 1077 1078 if (i == e) 1079 Pending.push_back(Root); 1080 } 1081 1082 if (Pending.size() == 1) 1083 Root = Pending[0]; 1084 else 1085 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1086 1087 DAG.setRoot(Root); 1088 Pending.clear(); 1089 return Root; 1090 } 1091 1092 SDValue SelectionDAGBuilder::getMemoryRoot() { 1093 return updateRoot(PendingLoads); 1094 } 1095 1096 SDValue SelectionDAGBuilder::getRoot() { 1097 // Chain up all pending constrained intrinsics together with all 1098 // pending loads, by simply appending them to PendingLoads and 1099 // then calling getMemoryRoot(). 1100 PendingLoads.reserve(PendingLoads.size() + 1101 PendingConstrainedFP.size() + 1102 PendingConstrainedFPStrict.size()); 1103 PendingLoads.append(PendingConstrainedFP.begin(), 1104 PendingConstrainedFP.end()); 1105 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1106 PendingConstrainedFPStrict.end()); 1107 PendingConstrainedFP.clear(); 1108 PendingConstrainedFPStrict.clear(); 1109 return getMemoryRoot(); 1110 } 1111 1112 SDValue SelectionDAGBuilder::getControlRoot() { 1113 // We need to emit pending fpexcept.strict constrained intrinsics, 1114 // so append them to the PendingExports list. 1115 PendingExports.append(PendingConstrainedFPStrict.begin(), 1116 PendingConstrainedFPStrict.end()); 1117 PendingConstrainedFPStrict.clear(); 1118 return updateRoot(PendingExports); 1119 } 1120 1121 void SelectionDAGBuilder::visit(const Instruction &I) { 1122 // Set up outgoing PHI node register values before emitting the terminator. 1123 if (I.isTerminator()) { 1124 HandlePHINodesInSuccessorBlocks(I.getParent()); 1125 } 1126 1127 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1128 if (!isa<DbgInfoIntrinsic>(I)) 1129 ++SDNodeOrder; 1130 1131 CurInst = &I; 1132 1133 visit(I.getOpcode(), I); 1134 1135 if (!I.isTerminator() && !HasTailCall && 1136 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1137 CopyToExportRegsIfNeeded(&I); 1138 1139 CurInst = nullptr; 1140 } 1141 1142 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1143 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1144 } 1145 1146 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1147 // Note: this doesn't use InstVisitor, because it has to work with 1148 // ConstantExpr's in addition to instructions. 1149 switch (Opcode) { 1150 default: llvm_unreachable("Unknown instruction type encountered!"); 1151 // Build the switch statement using the Instruction.def file. 1152 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1153 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1154 #include "llvm/IR/Instruction.def" 1155 } 1156 } 1157 1158 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1159 DebugLoc DL, unsigned Order) { 1160 // We treat variadic dbg_values differently at this stage. 1161 if (DI->hasArgList()) { 1162 // For variadic dbg_values we will now insert an undef. 1163 // FIXME: We can potentially recover these! 1164 SmallVector<SDDbgOperand, 2> Locs; 1165 for (const Value *V : DI->getValues()) { 1166 auto Undef = UndefValue::get(V->getType()); 1167 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1168 } 1169 SDDbgValue *SDV = DAG.getDbgValueList( 1170 DI->getVariable(), DI->getExpression(), Locs, {}, 1171 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1172 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1173 } else { 1174 // TODO: Dangling debug info will eventually either be resolved or produce 1175 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1176 // between the original dbg.value location and its resolved DBG_VALUE, 1177 // which we should ideally fill with an extra Undef DBG_VALUE. 1178 assert(DI->getNumVariableLocationOps() == 1 && 1179 "DbgValueInst without an ArgList should have a single location " 1180 "operand."); 1181 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1182 } 1183 } 1184 1185 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1186 const DIExpression *Expr) { 1187 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1188 const DbgValueInst *DI = DDI.getDI(); 1189 DIVariable *DanglingVariable = DI->getVariable(); 1190 DIExpression *DanglingExpr = DI->getExpression(); 1191 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1192 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1193 return true; 1194 } 1195 return false; 1196 }; 1197 1198 for (auto &DDIMI : DanglingDebugInfoMap) { 1199 DanglingDebugInfoVector &DDIV = DDIMI.second; 1200 1201 // If debug info is to be dropped, run it through final checks to see 1202 // whether it can be salvaged. 1203 for (auto &DDI : DDIV) 1204 if (isMatchingDbgValue(DDI)) 1205 salvageUnresolvedDbgValue(DDI); 1206 1207 erase_if(DDIV, isMatchingDbgValue); 1208 } 1209 } 1210 1211 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1212 // generate the debug data structures now that we've seen its definition. 1213 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1214 SDValue Val) { 1215 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1216 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1217 return; 1218 1219 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1220 for (auto &DDI : DDIV) { 1221 const DbgValueInst *DI = DDI.getDI(); 1222 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1223 assert(DI && "Ill-formed DanglingDebugInfo"); 1224 DebugLoc dl = DDI.getdl(); 1225 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1226 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1227 DILocalVariable *Variable = DI->getVariable(); 1228 DIExpression *Expr = DI->getExpression(); 1229 assert(Variable->isValidLocationForIntrinsic(dl) && 1230 "Expected inlined-at fields to agree"); 1231 SDDbgValue *SDV; 1232 if (Val.getNode()) { 1233 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1234 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1235 // we couldn't resolve it directly when examining the DbgValue intrinsic 1236 // in the first place we should not be more successful here). Unless we 1237 // have some test case that prove this to be correct we should avoid 1238 // calling EmitFuncArgumentDbgValue here. 1239 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1240 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1241 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1242 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1243 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1244 // inserted after the definition of Val when emitting the instructions 1245 // after ISel. An alternative could be to teach 1246 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1247 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1248 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1249 << ValSDNodeOrder << "\n"); 1250 SDV = getDbgValue(Val, Variable, Expr, dl, 1251 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1252 DAG.AddDbgValue(SDV, false); 1253 } else 1254 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1255 << "in EmitFuncArgumentDbgValue\n"); 1256 } else { 1257 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1258 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1259 auto SDV = 1260 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1261 DAG.AddDbgValue(SDV, false); 1262 } 1263 } 1264 DDIV.clear(); 1265 } 1266 1267 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1268 // TODO: For the variadic implementation, instead of only checking the fail 1269 // state of `handleDebugValue`, we need know specifically which values were 1270 // invalid, so that we attempt to salvage only those values when processing 1271 // a DIArgList. 1272 assert(!DDI.getDI()->hasArgList() && 1273 "Not implemented for variadic dbg_values"); 1274 Value *V = DDI.getDI()->getValue(0); 1275 DILocalVariable *Var = DDI.getDI()->getVariable(); 1276 DIExpression *Expr = DDI.getDI()->getExpression(); 1277 DebugLoc DL = DDI.getdl(); 1278 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1279 unsigned SDOrder = DDI.getSDNodeOrder(); 1280 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1281 // that DW_OP_stack_value is desired. 1282 assert(isa<DbgValueInst>(DDI.getDI())); 1283 bool StackValue = true; 1284 1285 // Can this Value can be encoded without any further work? 1286 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1287 return; 1288 1289 // Attempt to salvage back through as many instructions as possible. Bail if 1290 // a non-instruction is seen, such as a constant expression or global 1291 // variable. FIXME: Further work could recover those too. 1292 while (isa<Instruction>(V)) { 1293 Instruction &VAsInst = *cast<Instruction>(V); 1294 // Temporary "0", awaiting real implementation. 1295 SmallVector<uint64_t, 16> Ops; 1296 SmallVector<Value *, 4> AdditionalValues; 1297 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1298 AdditionalValues); 1299 // If we cannot salvage any further, and haven't yet found a suitable debug 1300 // expression, bail out. 1301 if (!V) 1302 break; 1303 1304 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1305 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1306 // here for variadic dbg_values, remove that condition. 1307 if (!AdditionalValues.empty()) 1308 break; 1309 1310 // New value and expr now represent this debuginfo. 1311 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1312 1313 // Some kind of simplification occurred: check whether the operand of the 1314 // salvaged debug expression can be encoded in this DAG. 1315 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1316 /*IsVariadic=*/false)) { 1317 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1318 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1319 return; 1320 } 1321 } 1322 1323 // This was the final opportunity to salvage this debug information, and it 1324 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1325 // any earlier variable location. 1326 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1327 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1328 DAG.AddDbgValue(SDV, false); 1329 1330 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1331 << "\n"); 1332 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1333 << "\n"); 1334 } 1335 1336 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1337 DILocalVariable *Var, 1338 DIExpression *Expr, DebugLoc dl, 1339 DebugLoc InstDL, unsigned Order, 1340 bool IsVariadic) { 1341 if (Values.empty()) 1342 return true; 1343 SmallVector<SDDbgOperand> LocationOps; 1344 SmallVector<SDNode *> Dependencies; 1345 for (const Value *V : Values) { 1346 // Constant value. 1347 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1348 isa<ConstantPointerNull>(V)) { 1349 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1350 continue; 1351 } 1352 1353 // If the Value is a frame index, we can create a FrameIndex debug value 1354 // without relying on the DAG at all. 1355 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1356 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1357 if (SI != FuncInfo.StaticAllocaMap.end()) { 1358 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1359 continue; 1360 } 1361 } 1362 1363 // Do not use getValue() in here; we don't want to generate code at 1364 // this point if it hasn't been done yet. 1365 SDValue N = NodeMap[V]; 1366 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1367 N = UnusedArgNodeMap[V]; 1368 if (N.getNode()) { 1369 // Only emit func arg dbg value for non-variadic dbg.values for now. 1370 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1371 return true; 1372 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1373 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1374 // describe stack slot locations. 1375 // 1376 // Consider "int x = 0; int *px = &x;". There are two kinds of 1377 // interesting debug values here after optimization: 1378 // 1379 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1380 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1381 // 1382 // Both describe the direct values of their associated variables. 1383 Dependencies.push_back(N.getNode()); 1384 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1385 continue; 1386 } 1387 LocationOps.emplace_back( 1388 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1389 continue; 1390 } 1391 1392 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1393 // Special rules apply for the first dbg.values of parameter variables in a 1394 // function. Identify them by the fact they reference Argument Values, that 1395 // they're parameters, and they are parameters of the current function. We 1396 // need to let them dangle until they get an SDNode. 1397 bool IsParamOfFunc = 1398 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1399 if (IsParamOfFunc) 1400 return false; 1401 1402 // The value is not used in this block yet (or it would have an SDNode). 1403 // We still want the value to appear for the user if possible -- if it has 1404 // an associated VReg, we can refer to that instead. 1405 auto VMI = FuncInfo.ValueMap.find(V); 1406 if (VMI != FuncInfo.ValueMap.end()) { 1407 unsigned Reg = VMI->second; 1408 // If this is a PHI node, it may be split up into several MI PHI nodes 1409 // (in FunctionLoweringInfo::set). 1410 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1411 V->getType(), None); 1412 if (RFV.occupiesMultipleRegs()) { 1413 // FIXME: We could potentially support variadic dbg_values here. 1414 if (IsVariadic) 1415 return false; 1416 unsigned Offset = 0; 1417 unsigned BitsToDescribe = 0; 1418 if (auto VarSize = Var->getSizeInBits()) 1419 BitsToDescribe = *VarSize; 1420 if (auto Fragment = Expr->getFragmentInfo()) 1421 BitsToDescribe = Fragment->SizeInBits; 1422 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1423 // Bail out if all bits are described already. 1424 if (Offset >= BitsToDescribe) 1425 break; 1426 // TODO: handle scalable vectors. 1427 unsigned RegisterSize = RegAndSize.second; 1428 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1429 ? BitsToDescribe - Offset 1430 : RegisterSize; 1431 auto FragmentExpr = DIExpression::createFragmentExpression( 1432 Expr, Offset, FragmentSize); 1433 if (!FragmentExpr) 1434 continue; 1435 SDDbgValue *SDV = DAG.getVRegDbgValue( 1436 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1437 DAG.AddDbgValue(SDV, false); 1438 Offset += RegisterSize; 1439 } 1440 return true; 1441 } 1442 // We can use simple vreg locations for variadic dbg_values as well. 1443 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1444 continue; 1445 } 1446 // We failed to create a SDDbgOperand for V. 1447 return false; 1448 } 1449 1450 // We have created a SDDbgOperand for each Value in Values. 1451 // Should use Order instead of SDNodeOrder? 1452 assert(!LocationOps.empty()); 1453 SDDbgValue *SDV = 1454 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1455 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1456 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1457 return true; 1458 } 1459 1460 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1461 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1462 for (auto &Pair : DanglingDebugInfoMap) 1463 for (auto &DDI : Pair.second) 1464 salvageUnresolvedDbgValue(DDI); 1465 clearDanglingDebugInfo(); 1466 } 1467 1468 /// getCopyFromRegs - If there was virtual register allocated for the value V 1469 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1470 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1471 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1472 SDValue Result; 1473 1474 if (It != FuncInfo.ValueMap.end()) { 1475 Register InReg = It->second; 1476 1477 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1478 DAG.getDataLayout(), InReg, Ty, 1479 None); // This is not an ABI copy. 1480 SDValue Chain = DAG.getEntryNode(); 1481 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1482 V); 1483 resolveDanglingDebugInfo(V, Result); 1484 } 1485 1486 return Result; 1487 } 1488 1489 /// getValue - Return an SDValue for the given Value. 1490 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1491 // If we already have an SDValue for this value, use it. It's important 1492 // to do this first, so that we don't create a CopyFromReg if we already 1493 // have a regular SDValue. 1494 SDValue &N = NodeMap[V]; 1495 if (N.getNode()) return N; 1496 1497 // If there's a virtual register allocated and initialized for this 1498 // value, use it. 1499 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1500 return copyFromReg; 1501 1502 // Otherwise create a new SDValue and remember it. 1503 SDValue Val = getValueImpl(V); 1504 NodeMap[V] = Val; 1505 resolveDanglingDebugInfo(V, Val); 1506 return Val; 1507 } 1508 1509 /// getNonRegisterValue - Return an SDValue for the given Value, but 1510 /// don't look in FuncInfo.ValueMap for a virtual register. 1511 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1512 // If we already have an SDValue for this value, use it. 1513 SDValue &N = NodeMap[V]; 1514 if (N.getNode()) { 1515 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1516 // Remove the debug location from the node as the node is about to be used 1517 // in a location which may differ from the original debug location. This 1518 // is relevant to Constant and ConstantFP nodes because they can appear 1519 // as constant expressions inside PHI nodes. 1520 N->setDebugLoc(DebugLoc()); 1521 } 1522 return N; 1523 } 1524 1525 // Otherwise create a new SDValue and remember it. 1526 SDValue Val = getValueImpl(V); 1527 NodeMap[V] = Val; 1528 resolveDanglingDebugInfo(V, Val); 1529 return Val; 1530 } 1531 1532 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1533 /// Create an SDValue for the given value. 1534 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1535 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1536 1537 if (const Constant *C = dyn_cast<Constant>(V)) { 1538 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1539 1540 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1541 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1542 1543 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1544 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1545 1546 if (isa<ConstantPointerNull>(C)) { 1547 unsigned AS = V->getType()->getPointerAddressSpace(); 1548 return DAG.getConstant(0, getCurSDLoc(), 1549 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1550 } 1551 1552 if (match(C, m_VScale(DAG.getDataLayout()))) 1553 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1554 1555 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1556 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1557 1558 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1559 return DAG.getUNDEF(VT); 1560 1561 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1562 visit(CE->getOpcode(), *CE); 1563 SDValue N1 = NodeMap[V]; 1564 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1565 return N1; 1566 } 1567 1568 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1569 SmallVector<SDValue, 4> Constants; 1570 for (const Use &U : C->operands()) { 1571 SDNode *Val = getValue(U).getNode(); 1572 // If the operand is an empty aggregate, there are no values. 1573 if (!Val) continue; 1574 // Add each leaf value from the operand to the Constants list 1575 // to form a flattened list of all the values. 1576 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1577 Constants.push_back(SDValue(Val, i)); 1578 } 1579 1580 return DAG.getMergeValues(Constants, getCurSDLoc()); 1581 } 1582 1583 if (const ConstantDataSequential *CDS = 1584 dyn_cast<ConstantDataSequential>(C)) { 1585 SmallVector<SDValue, 4> Ops; 1586 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1587 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1588 // Add each leaf value from the operand to the Constants list 1589 // to form a flattened list of all the values. 1590 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1591 Ops.push_back(SDValue(Val, i)); 1592 } 1593 1594 if (isa<ArrayType>(CDS->getType())) 1595 return DAG.getMergeValues(Ops, getCurSDLoc()); 1596 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1597 } 1598 1599 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1600 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1601 "Unknown struct or array constant!"); 1602 1603 SmallVector<EVT, 4> ValueVTs; 1604 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1605 unsigned NumElts = ValueVTs.size(); 1606 if (NumElts == 0) 1607 return SDValue(); // empty struct 1608 SmallVector<SDValue, 4> Constants(NumElts); 1609 for (unsigned i = 0; i != NumElts; ++i) { 1610 EVT EltVT = ValueVTs[i]; 1611 if (isa<UndefValue>(C)) 1612 Constants[i] = DAG.getUNDEF(EltVT); 1613 else if (EltVT.isFloatingPoint()) 1614 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1615 else 1616 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1617 } 1618 1619 return DAG.getMergeValues(Constants, getCurSDLoc()); 1620 } 1621 1622 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1623 return DAG.getBlockAddress(BA, VT); 1624 1625 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1626 return getValue(Equiv->getGlobalValue()); 1627 1628 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1629 return getValue(NC->getGlobalValue()); 1630 1631 VectorType *VecTy = cast<VectorType>(V->getType()); 1632 1633 // Now that we know the number and type of the elements, get that number of 1634 // elements into the Ops array based on what kind of constant it is. 1635 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1636 SmallVector<SDValue, 16> Ops; 1637 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1638 for (unsigned i = 0; i != NumElements; ++i) 1639 Ops.push_back(getValue(CV->getOperand(i))); 1640 1641 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1642 } 1643 1644 if (isa<ConstantAggregateZero>(C)) { 1645 EVT EltVT = 1646 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1647 1648 SDValue Op; 1649 if (EltVT.isFloatingPoint()) 1650 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1651 else 1652 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1653 1654 if (isa<ScalableVectorType>(VecTy)) 1655 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1656 1657 SmallVector<SDValue, 16> Ops; 1658 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1659 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1660 } 1661 1662 llvm_unreachable("Unknown vector constant"); 1663 } 1664 1665 // If this is a static alloca, generate it as the frameindex instead of 1666 // computation. 1667 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1668 DenseMap<const AllocaInst*, int>::iterator SI = 1669 FuncInfo.StaticAllocaMap.find(AI); 1670 if (SI != FuncInfo.StaticAllocaMap.end()) 1671 return DAG.getFrameIndex(SI->second, 1672 TLI.getFrameIndexTy(DAG.getDataLayout())); 1673 } 1674 1675 // If this is an instruction which fast-isel has deferred, select it now. 1676 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1677 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1678 1679 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1680 Inst->getType(), None); 1681 SDValue Chain = DAG.getEntryNode(); 1682 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1683 } 1684 1685 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1686 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1687 1688 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1689 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1690 1691 llvm_unreachable("Can't get register for value!"); 1692 } 1693 1694 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1695 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1696 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1697 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1698 bool IsSEH = isAsynchronousEHPersonality(Pers); 1699 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1700 if (!IsSEH) 1701 CatchPadMBB->setIsEHScopeEntry(); 1702 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1703 if (IsMSVCCXX || IsCoreCLR) 1704 CatchPadMBB->setIsEHFuncletEntry(); 1705 } 1706 1707 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1708 // Update machine-CFG edge. 1709 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1710 FuncInfo.MBB->addSuccessor(TargetMBB); 1711 TargetMBB->setIsEHCatchretTarget(true); 1712 DAG.getMachineFunction().setHasEHCatchret(true); 1713 1714 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1715 bool IsSEH = isAsynchronousEHPersonality(Pers); 1716 if (IsSEH) { 1717 // If this is not a fall-through branch or optimizations are switched off, 1718 // emit the branch. 1719 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1720 TM.getOptLevel() == CodeGenOpt::None) 1721 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1722 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1723 return; 1724 } 1725 1726 // Figure out the funclet membership for the catchret's successor. 1727 // This will be used by the FuncletLayout pass to determine how to order the 1728 // BB's. 1729 // A 'catchret' returns to the outer scope's color. 1730 Value *ParentPad = I.getCatchSwitchParentPad(); 1731 const BasicBlock *SuccessorColor; 1732 if (isa<ConstantTokenNone>(ParentPad)) 1733 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1734 else 1735 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1736 assert(SuccessorColor && "No parent funclet for catchret!"); 1737 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1738 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1739 1740 // Create the terminator node. 1741 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1742 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1743 DAG.getBasicBlock(SuccessorColorMBB)); 1744 DAG.setRoot(Ret); 1745 } 1746 1747 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1748 // Don't emit any special code for the cleanuppad instruction. It just marks 1749 // the start of an EH scope/funclet. 1750 FuncInfo.MBB->setIsEHScopeEntry(); 1751 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1752 if (Pers != EHPersonality::Wasm_CXX) { 1753 FuncInfo.MBB->setIsEHFuncletEntry(); 1754 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1755 } 1756 } 1757 1758 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1759 // not match, it is OK to add only the first unwind destination catchpad to the 1760 // successors, because there will be at least one invoke instruction within the 1761 // catch scope that points to the next unwind destination, if one exists, so 1762 // CFGSort cannot mess up with BB sorting order. 1763 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1764 // call within them, and catchpads only consisting of 'catch (...)' have a 1765 // '__cxa_end_catch' call within them, both of which generate invokes in case 1766 // the next unwind destination exists, i.e., the next unwind destination is not 1767 // the caller.) 1768 // 1769 // Having at most one EH pad successor is also simpler and helps later 1770 // transformations. 1771 // 1772 // For example, 1773 // current: 1774 // invoke void @foo to ... unwind label %catch.dispatch 1775 // catch.dispatch: 1776 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1777 // catch.start: 1778 // ... 1779 // ... in this BB or some other child BB dominated by this BB there will be an 1780 // invoke that points to 'next' BB as an unwind destination 1781 // 1782 // next: ; We don't need to add this to 'current' BB's successor 1783 // ... 1784 static void findWasmUnwindDestinations( 1785 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1786 BranchProbability Prob, 1787 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1788 &UnwindDests) { 1789 while (EHPadBB) { 1790 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1791 if (isa<CleanupPadInst>(Pad)) { 1792 // Stop on cleanup pads. 1793 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1794 UnwindDests.back().first->setIsEHScopeEntry(); 1795 break; 1796 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1797 // Add the catchpad handlers to the possible destinations. We don't 1798 // continue to the unwind destination of the catchswitch for wasm. 1799 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1800 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1801 UnwindDests.back().first->setIsEHScopeEntry(); 1802 } 1803 break; 1804 } else { 1805 continue; 1806 } 1807 } 1808 } 1809 1810 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1811 /// many places it could ultimately go. In the IR, we have a single unwind 1812 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1813 /// This function skips over imaginary basic blocks that hold catchswitch 1814 /// instructions, and finds all the "real" machine 1815 /// basic block destinations. As those destinations may not be successors of 1816 /// EHPadBB, here we also calculate the edge probability to those destinations. 1817 /// The passed-in Prob is the edge probability to EHPadBB. 1818 static void findUnwindDestinations( 1819 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1820 BranchProbability Prob, 1821 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1822 &UnwindDests) { 1823 EHPersonality Personality = 1824 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1825 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1826 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1827 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1828 bool IsSEH = isAsynchronousEHPersonality(Personality); 1829 1830 if (IsWasmCXX) { 1831 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1832 assert(UnwindDests.size() <= 1 && 1833 "There should be at most one unwind destination for wasm"); 1834 return; 1835 } 1836 1837 while (EHPadBB) { 1838 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1839 BasicBlock *NewEHPadBB = nullptr; 1840 if (isa<LandingPadInst>(Pad)) { 1841 // Stop on landingpads. They are not funclets. 1842 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1843 break; 1844 } else if (isa<CleanupPadInst>(Pad)) { 1845 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1846 // personalities. 1847 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1848 UnwindDests.back().first->setIsEHScopeEntry(); 1849 UnwindDests.back().first->setIsEHFuncletEntry(); 1850 break; 1851 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1852 // Add the catchpad handlers to the possible destinations. 1853 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1854 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1855 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1856 if (IsMSVCCXX || IsCoreCLR) 1857 UnwindDests.back().first->setIsEHFuncletEntry(); 1858 if (!IsSEH) 1859 UnwindDests.back().first->setIsEHScopeEntry(); 1860 } 1861 NewEHPadBB = CatchSwitch->getUnwindDest(); 1862 } else { 1863 continue; 1864 } 1865 1866 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1867 if (BPI && NewEHPadBB) 1868 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1869 EHPadBB = NewEHPadBB; 1870 } 1871 } 1872 1873 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1874 // Update successor info. 1875 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1876 auto UnwindDest = I.getUnwindDest(); 1877 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1878 BranchProbability UnwindDestProb = 1879 (BPI && UnwindDest) 1880 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1881 : BranchProbability::getZero(); 1882 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1883 for (auto &UnwindDest : UnwindDests) { 1884 UnwindDest.first->setIsEHPad(); 1885 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1886 } 1887 FuncInfo.MBB->normalizeSuccProbs(); 1888 1889 // Create the terminator node. 1890 SDValue Ret = 1891 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1892 DAG.setRoot(Ret); 1893 } 1894 1895 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1896 report_fatal_error("visitCatchSwitch not yet implemented!"); 1897 } 1898 1899 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1900 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1901 auto &DL = DAG.getDataLayout(); 1902 SDValue Chain = getControlRoot(); 1903 SmallVector<ISD::OutputArg, 8> Outs; 1904 SmallVector<SDValue, 8> OutVals; 1905 1906 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1907 // lower 1908 // 1909 // %val = call <ty> @llvm.experimental.deoptimize() 1910 // ret <ty> %val 1911 // 1912 // differently. 1913 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1914 LowerDeoptimizingReturn(); 1915 return; 1916 } 1917 1918 if (!FuncInfo.CanLowerReturn) { 1919 unsigned DemoteReg = FuncInfo.DemoteRegister; 1920 const Function *F = I.getParent()->getParent(); 1921 1922 // Emit a store of the return value through the virtual register. 1923 // Leave Outs empty so that LowerReturn won't try to load return 1924 // registers the usual way. 1925 SmallVector<EVT, 1> PtrValueVTs; 1926 ComputeValueVTs(TLI, DL, 1927 F->getReturnType()->getPointerTo( 1928 DAG.getDataLayout().getAllocaAddrSpace()), 1929 PtrValueVTs); 1930 1931 SDValue RetPtr = 1932 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 1933 SDValue RetOp = getValue(I.getOperand(0)); 1934 1935 SmallVector<EVT, 4> ValueVTs, MemVTs; 1936 SmallVector<uint64_t, 4> Offsets; 1937 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1938 &Offsets); 1939 unsigned NumValues = ValueVTs.size(); 1940 1941 SmallVector<SDValue, 4> Chains(NumValues); 1942 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1943 for (unsigned i = 0; i != NumValues; ++i) { 1944 // An aggregate return value cannot wrap around the address space, so 1945 // offsets to its parts don't wrap either. 1946 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1947 TypeSize::Fixed(Offsets[i])); 1948 1949 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1950 if (MemVTs[i] != ValueVTs[i]) 1951 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1952 Chains[i] = DAG.getStore( 1953 Chain, getCurSDLoc(), Val, 1954 // FIXME: better loc info would be nice. 1955 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1956 commonAlignment(BaseAlign, Offsets[i])); 1957 } 1958 1959 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1960 MVT::Other, Chains); 1961 } else if (I.getNumOperands() != 0) { 1962 SmallVector<EVT, 4> ValueVTs; 1963 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1964 unsigned NumValues = ValueVTs.size(); 1965 if (NumValues) { 1966 SDValue RetOp = getValue(I.getOperand(0)); 1967 1968 const Function *F = I.getParent()->getParent(); 1969 1970 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1971 I.getOperand(0)->getType(), F->getCallingConv(), 1972 /*IsVarArg*/ false, DL); 1973 1974 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1975 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 1976 ExtendKind = ISD::SIGN_EXTEND; 1977 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 1978 ExtendKind = ISD::ZERO_EXTEND; 1979 1980 LLVMContext &Context = F->getContext(); 1981 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 1982 1983 for (unsigned j = 0; j != NumValues; ++j) { 1984 EVT VT = ValueVTs[j]; 1985 1986 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1987 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1988 1989 CallingConv::ID CC = F->getCallingConv(); 1990 1991 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1992 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1993 SmallVector<SDValue, 4> Parts(NumParts); 1994 getCopyToParts(DAG, getCurSDLoc(), 1995 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1996 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1997 1998 // 'inreg' on function refers to return value 1999 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2000 if (RetInReg) 2001 Flags.setInReg(); 2002 2003 if (I.getOperand(0)->getType()->isPointerTy()) { 2004 Flags.setPointer(); 2005 Flags.setPointerAddrSpace( 2006 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2007 } 2008 2009 if (NeedsRegBlock) { 2010 Flags.setInConsecutiveRegs(); 2011 if (j == NumValues - 1) 2012 Flags.setInConsecutiveRegsLast(); 2013 } 2014 2015 // Propagate extension type if any 2016 if (ExtendKind == ISD::SIGN_EXTEND) 2017 Flags.setSExt(); 2018 else if (ExtendKind == ISD::ZERO_EXTEND) 2019 Flags.setZExt(); 2020 2021 for (unsigned i = 0; i < NumParts; ++i) { 2022 Outs.push_back(ISD::OutputArg(Flags, 2023 Parts[i].getValueType().getSimpleVT(), 2024 VT, /*isfixed=*/true, 0, 0)); 2025 OutVals.push_back(Parts[i]); 2026 } 2027 } 2028 } 2029 } 2030 2031 // Push in swifterror virtual register as the last element of Outs. This makes 2032 // sure swifterror virtual register will be returned in the swifterror 2033 // physical register. 2034 const Function *F = I.getParent()->getParent(); 2035 if (TLI.supportSwiftError() && 2036 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2037 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2038 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2039 Flags.setSwiftError(); 2040 Outs.push_back(ISD::OutputArg( 2041 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2042 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2043 // Create SDNode for the swifterror virtual register. 2044 OutVals.push_back( 2045 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2046 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2047 EVT(TLI.getPointerTy(DL)))); 2048 } 2049 2050 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2051 CallingConv::ID CallConv = 2052 DAG.getMachineFunction().getFunction().getCallingConv(); 2053 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2054 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2055 2056 // Verify that the target's LowerReturn behaved as expected. 2057 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2058 "LowerReturn didn't return a valid chain!"); 2059 2060 // Update the DAG with the new chain value resulting from return lowering. 2061 DAG.setRoot(Chain); 2062 } 2063 2064 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2065 /// created for it, emit nodes to copy the value into the virtual 2066 /// registers. 2067 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2068 // Skip empty types 2069 if (V->getType()->isEmptyTy()) 2070 return; 2071 2072 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2073 if (VMI != FuncInfo.ValueMap.end()) { 2074 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2075 CopyValueToVirtualRegister(V, VMI->second); 2076 } 2077 } 2078 2079 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2080 /// the current basic block, add it to ValueMap now so that we'll get a 2081 /// CopyTo/FromReg. 2082 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2083 // No need to export constants. 2084 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2085 2086 // Already exported? 2087 if (FuncInfo.isExportedInst(V)) return; 2088 2089 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2090 CopyValueToVirtualRegister(V, Reg); 2091 } 2092 2093 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2094 const BasicBlock *FromBB) { 2095 // The operands of the setcc have to be in this block. We don't know 2096 // how to export them from some other block. 2097 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2098 // Can export from current BB. 2099 if (VI->getParent() == FromBB) 2100 return true; 2101 2102 // Is already exported, noop. 2103 return FuncInfo.isExportedInst(V); 2104 } 2105 2106 // If this is an argument, we can export it if the BB is the entry block or 2107 // if it is already exported. 2108 if (isa<Argument>(V)) { 2109 if (FromBB->isEntryBlock()) 2110 return true; 2111 2112 // Otherwise, can only export this if it is already exported. 2113 return FuncInfo.isExportedInst(V); 2114 } 2115 2116 // Otherwise, constants can always be exported. 2117 return true; 2118 } 2119 2120 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2121 BranchProbability 2122 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2123 const MachineBasicBlock *Dst) const { 2124 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2125 const BasicBlock *SrcBB = Src->getBasicBlock(); 2126 const BasicBlock *DstBB = Dst->getBasicBlock(); 2127 if (!BPI) { 2128 // If BPI is not available, set the default probability as 1 / N, where N is 2129 // the number of successors. 2130 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2131 return BranchProbability(1, SuccSize); 2132 } 2133 return BPI->getEdgeProbability(SrcBB, DstBB); 2134 } 2135 2136 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2137 MachineBasicBlock *Dst, 2138 BranchProbability Prob) { 2139 if (!FuncInfo.BPI) 2140 Src->addSuccessorWithoutProb(Dst); 2141 else { 2142 if (Prob.isUnknown()) 2143 Prob = getEdgeProbability(Src, Dst); 2144 Src->addSuccessor(Dst, Prob); 2145 } 2146 } 2147 2148 static bool InBlock(const Value *V, const BasicBlock *BB) { 2149 if (const Instruction *I = dyn_cast<Instruction>(V)) 2150 return I->getParent() == BB; 2151 return true; 2152 } 2153 2154 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2155 /// This function emits a branch and is used at the leaves of an OR or an 2156 /// AND operator tree. 2157 void 2158 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2159 MachineBasicBlock *TBB, 2160 MachineBasicBlock *FBB, 2161 MachineBasicBlock *CurBB, 2162 MachineBasicBlock *SwitchBB, 2163 BranchProbability TProb, 2164 BranchProbability FProb, 2165 bool InvertCond) { 2166 const BasicBlock *BB = CurBB->getBasicBlock(); 2167 2168 // If the leaf of the tree is a comparison, merge the condition into 2169 // the caseblock. 2170 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2171 // The operands of the cmp have to be in this block. We don't know 2172 // how to export them from some other block. If this is the first block 2173 // of the sequence, no exporting is needed. 2174 if (CurBB == SwitchBB || 2175 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2176 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2177 ISD::CondCode Condition; 2178 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2179 ICmpInst::Predicate Pred = 2180 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2181 Condition = getICmpCondCode(Pred); 2182 } else { 2183 const FCmpInst *FC = cast<FCmpInst>(Cond); 2184 FCmpInst::Predicate Pred = 2185 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2186 Condition = getFCmpCondCode(Pred); 2187 if (TM.Options.NoNaNsFPMath) 2188 Condition = getFCmpCodeWithoutNaN(Condition); 2189 } 2190 2191 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2192 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2193 SL->SwitchCases.push_back(CB); 2194 return; 2195 } 2196 } 2197 2198 // Create a CaseBlock record representing this branch. 2199 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2200 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2201 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2202 SL->SwitchCases.push_back(CB); 2203 } 2204 2205 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2206 MachineBasicBlock *TBB, 2207 MachineBasicBlock *FBB, 2208 MachineBasicBlock *CurBB, 2209 MachineBasicBlock *SwitchBB, 2210 Instruction::BinaryOps Opc, 2211 BranchProbability TProb, 2212 BranchProbability FProb, 2213 bool InvertCond) { 2214 // Skip over not part of the tree and remember to invert op and operands at 2215 // next level. 2216 Value *NotCond; 2217 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2218 InBlock(NotCond, CurBB->getBasicBlock())) { 2219 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2220 !InvertCond); 2221 return; 2222 } 2223 2224 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2225 const Value *BOpOp0, *BOpOp1; 2226 // Compute the effective opcode for Cond, taking into account whether it needs 2227 // to be inverted, e.g. 2228 // and (not (or A, B)), C 2229 // gets lowered as 2230 // and (and (not A, not B), C) 2231 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2232 if (BOp) { 2233 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2234 ? Instruction::And 2235 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2236 ? Instruction::Or 2237 : (Instruction::BinaryOps)0); 2238 if (InvertCond) { 2239 if (BOpc == Instruction::And) 2240 BOpc = Instruction::Or; 2241 else if (BOpc == Instruction::Or) 2242 BOpc = Instruction::And; 2243 } 2244 } 2245 2246 // If this node is not part of the or/and tree, emit it as a branch. 2247 // Note that all nodes in the tree should have same opcode. 2248 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2249 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2250 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2251 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2252 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2253 TProb, FProb, InvertCond); 2254 return; 2255 } 2256 2257 // Create TmpBB after CurBB. 2258 MachineFunction::iterator BBI(CurBB); 2259 MachineFunction &MF = DAG.getMachineFunction(); 2260 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2261 CurBB->getParent()->insert(++BBI, TmpBB); 2262 2263 if (Opc == Instruction::Or) { 2264 // Codegen X | Y as: 2265 // BB1: 2266 // jmp_if_X TBB 2267 // jmp TmpBB 2268 // TmpBB: 2269 // jmp_if_Y TBB 2270 // jmp FBB 2271 // 2272 2273 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2274 // The requirement is that 2275 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2276 // = TrueProb for original BB. 2277 // Assuming the original probabilities are A and B, one choice is to set 2278 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2279 // A/(1+B) and 2B/(1+B). This choice assumes that 2280 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2281 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2282 // TmpBB, but the math is more complicated. 2283 2284 auto NewTrueProb = TProb / 2; 2285 auto NewFalseProb = TProb / 2 + FProb; 2286 // Emit the LHS condition. 2287 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2288 NewFalseProb, InvertCond); 2289 2290 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2291 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2292 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2293 // Emit the RHS condition into TmpBB. 2294 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2295 Probs[1], InvertCond); 2296 } else { 2297 assert(Opc == Instruction::And && "Unknown merge op!"); 2298 // Codegen X & Y as: 2299 // BB1: 2300 // jmp_if_X TmpBB 2301 // jmp FBB 2302 // TmpBB: 2303 // jmp_if_Y TBB 2304 // jmp FBB 2305 // 2306 // This requires creation of TmpBB after CurBB. 2307 2308 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2309 // The requirement is that 2310 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2311 // = FalseProb for original BB. 2312 // Assuming the original probabilities are A and B, one choice is to set 2313 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2314 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2315 // TrueProb for BB1 * FalseProb for TmpBB. 2316 2317 auto NewTrueProb = TProb + FProb / 2; 2318 auto NewFalseProb = FProb / 2; 2319 // Emit the LHS condition. 2320 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2321 NewFalseProb, InvertCond); 2322 2323 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2324 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2325 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2326 // Emit the RHS condition into TmpBB. 2327 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2328 Probs[1], InvertCond); 2329 } 2330 } 2331 2332 /// If the set of cases should be emitted as a series of branches, return true. 2333 /// If we should emit this as a bunch of and/or'd together conditions, return 2334 /// false. 2335 bool 2336 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2337 if (Cases.size() != 2) return true; 2338 2339 // If this is two comparisons of the same values or'd or and'd together, they 2340 // will get folded into a single comparison, so don't emit two blocks. 2341 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2342 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2343 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2344 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2345 return false; 2346 } 2347 2348 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2349 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2350 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2351 Cases[0].CC == Cases[1].CC && 2352 isa<Constant>(Cases[0].CmpRHS) && 2353 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2354 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2355 return false; 2356 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2357 return false; 2358 } 2359 2360 return true; 2361 } 2362 2363 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2364 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2365 2366 // Update machine-CFG edges. 2367 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2368 2369 if (I.isUnconditional()) { 2370 // Update machine-CFG edges. 2371 BrMBB->addSuccessor(Succ0MBB); 2372 2373 // If this is not a fall-through branch or optimizations are switched off, 2374 // emit the branch. 2375 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2376 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2377 MVT::Other, getControlRoot(), 2378 DAG.getBasicBlock(Succ0MBB))); 2379 2380 return; 2381 } 2382 2383 // If this condition is one of the special cases we handle, do special stuff 2384 // now. 2385 const Value *CondVal = I.getCondition(); 2386 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2387 2388 // If this is a series of conditions that are or'd or and'd together, emit 2389 // this as a sequence of branches instead of setcc's with and/or operations. 2390 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2391 // unpredictable branches, and vector extracts because those jumps are likely 2392 // expensive for any target), this should improve performance. 2393 // For example, instead of something like: 2394 // cmp A, B 2395 // C = seteq 2396 // cmp D, E 2397 // F = setle 2398 // or C, F 2399 // jnz foo 2400 // Emit: 2401 // cmp A, B 2402 // je foo 2403 // cmp D, E 2404 // jle foo 2405 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2406 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2407 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2408 Value *Vec; 2409 const Value *BOp0, *BOp1; 2410 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2411 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2412 Opcode = Instruction::And; 2413 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2414 Opcode = Instruction::Or; 2415 2416 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2417 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2418 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2419 getEdgeProbability(BrMBB, Succ0MBB), 2420 getEdgeProbability(BrMBB, Succ1MBB), 2421 /*InvertCond=*/false); 2422 // If the compares in later blocks need to use values not currently 2423 // exported from this block, export them now. This block should always 2424 // be the first entry. 2425 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2426 2427 // Allow some cases to be rejected. 2428 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2429 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2430 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2431 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2432 } 2433 2434 // Emit the branch for this block. 2435 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2436 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2437 return; 2438 } 2439 2440 // Okay, we decided not to do this, remove any inserted MBB's and clear 2441 // SwitchCases. 2442 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2443 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2444 2445 SL->SwitchCases.clear(); 2446 } 2447 } 2448 2449 // Create a CaseBlock record representing this branch. 2450 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2451 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2452 2453 // Use visitSwitchCase to actually insert the fast branch sequence for this 2454 // cond branch. 2455 visitSwitchCase(CB, BrMBB); 2456 } 2457 2458 /// visitSwitchCase - Emits the necessary code to represent a single node in 2459 /// the binary search tree resulting from lowering a switch instruction. 2460 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2461 MachineBasicBlock *SwitchBB) { 2462 SDValue Cond; 2463 SDValue CondLHS = getValue(CB.CmpLHS); 2464 SDLoc dl = CB.DL; 2465 2466 if (CB.CC == ISD::SETTRUE) { 2467 // Branch or fall through to TrueBB. 2468 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2469 SwitchBB->normalizeSuccProbs(); 2470 if (CB.TrueBB != NextBlock(SwitchBB)) { 2471 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2472 DAG.getBasicBlock(CB.TrueBB))); 2473 } 2474 return; 2475 } 2476 2477 auto &TLI = DAG.getTargetLoweringInfo(); 2478 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2479 2480 // Build the setcc now. 2481 if (!CB.CmpMHS) { 2482 // Fold "(X == true)" to X and "(X == false)" to !X to 2483 // handle common cases produced by branch lowering. 2484 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2485 CB.CC == ISD::SETEQ) 2486 Cond = CondLHS; 2487 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2488 CB.CC == ISD::SETEQ) { 2489 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2490 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2491 } else { 2492 SDValue CondRHS = getValue(CB.CmpRHS); 2493 2494 // If a pointer's DAG type is larger than its memory type then the DAG 2495 // values are zero-extended. This breaks signed comparisons so truncate 2496 // back to the underlying type before doing the compare. 2497 if (CondLHS.getValueType() != MemVT) { 2498 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2499 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2500 } 2501 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2502 } 2503 } else { 2504 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2505 2506 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2507 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2508 2509 SDValue CmpOp = getValue(CB.CmpMHS); 2510 EVT VT = CmpOp.getValueType(); 2511 2512 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2513 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2514 ISD::SETLE); 2515 } else { 2516 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2517 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2518 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2519 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2520 } 2521 } 2522 2523 // Update successor info 2524 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2525 // TrueBB and FalseBB are always different unless the incoming IR is 2526 // degenerate. This only happens when running llc on weird IR. 2527 if (CB.TrueBB != CB.FalseBB) 2528 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2529 SwitchBB->normalizeSuccProbs(); 2530 2531 // If the lhs block is the next block, invert the condition so that we can 2532 // fall through to the lhs instead of the rhs block. 2533 if (CB.TrueBB == NextBlock(SwitchBB)) { 2534 std::swap(CB.TrueBB, CB.FalseBB); 2535 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2536 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2537 } 2538 2539 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2540 MVT::Other, getControlRoot(), Cond, 2541 DAG.getBasicBlock(CB.TrueBB)); 2542 2543 // Insert the false branch. Do this even if it's a fall through branch, 2544 // this makes it easier to do DAG optimizations which require inverting 2545 // the branch condition. 2546 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2547 DAG.getBasicBlock(CB.FalseBB)); 2548 2549 DAG.setRoot(BrCond); 2550 } 2551 2552 /// visitJumpTable - Emit JumpTable node in the current MBB 2553 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2554 // Emit the code for the jump table 2555 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2556 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2557 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2558 JT.Reg, PTy); 2559 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2560 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2561 MVT::Other, Index.getValue(1), 2562 Table, Index); 2563 DAG.setRoot(BrJumpTable); 2564 } 2565 2566 /// visitJumpTableHeader - This function emits necessary code to produce index 2567 /// in the JumpTable from switch case. 2568 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2569 JumpTableHeader &JTH, 2570 MachineBasicBlock *SwitchBB) { 2571 SDLoc dl = getCurSDLoc(); 2572 2573 // Subtract the lowest switch case value from the value being switched on. 2574 SDValue SwitchOp = getValue(JTH.SValue); 2575 EVT VT = SwitchOp.getValueType(); 2576 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2577 DAG.getConstant(JTH.First, dl, VT)); 2578 2579 // The SDNode we just created, which holds the value being switched on minus 2580 // the smallest case value, needs to be copied to a virtual register so it 2581 // can be used as an index into the jump table in a subsequent basic block. 2582 // This value may be smaller or larger than the target's pointer type, and 2583 // therefore require extension or truncating. 2584 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2585 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2586 2587 unsigned JumpTableReg = 2588 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2589 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2590 JumpTableReg, SwitchOp); 2591 JT.Reg = JumpTableReg; 2592 2593 if (!JTH.FallthroughUnreachable) { 2594 // Emit the range check for the jump table, and branch to the default block 2595 // for the switch statement if the value being switched on exceeds the 2596 // largest case in the switch. 2597 SDValue CMP = DAG.getSetCC( 2598 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2599 Sub.getValueType()), 2600 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2601 2602 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2603 MVT::Other, CopyTo, CMP, 2604 DAG.getBasicBlock(JT.Default)); 2605 2606 // Avoid emitting unnecessary branches to the next block. 2607 if (JT.MBB != NextBlock(SwitchBB)) 2608 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2609 DAG.getBasicBlock(JT.MBB)); 2610 2611 DAG.setRoot(BrCond); 2612 } else { 2613 // Avoid emitting unnecessary branches to the next block. 2614 if (JT.MBB != NextBlock(SwitchBB)) 2615 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2616 DAG.getBasicBlock(JT.MBB))); 2617 else 2618 DAG.setRoot(CopyTo); 2619 } 2620 } 2621 2622 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2623 /// variable if there exists one. 2624 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2625 SDValue &Chain) { 2626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2627 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2628 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2629 MachineFunction &MF = DAG.getMachineFunction(); 2630 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2631 MachineSDNode *Node = 2632 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2633 if (Global) { 2634 MachinePointerInfo MPInfo(Global); 2635 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2636 MachineMemOperand::MODereferenceable; 2637 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2638 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2639 DAG.setNodeMemRefs(Node, {MemRef}); 2640 } 2641 if (PtrTy != PtrMemTy) 2642 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2643 return SDValue(Node, 0); 2644 } 2645 2646 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2647 /// tail spliced into a stack protector check success bb. 2648 /// 2649 /// For a high level explanation of how this fits into the stack protector 2650 /// generation see the comment on the declaration of class 2651 /// StackProtectorDescriptor. 2652 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2653 MachineBasicBlock *ParentBB) { 2654 2655 // First create the loads to the guard/stack slot for the comparison. 2656 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2657 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2658 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2659 2660 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2661 int FI = MFI.getStackProtectorIndex(); 2662 2663 SDValue Guard; 2664 SDLoc dl = getCurSDLoc(); 2665 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2666 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2667 Align Align = 2668 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2669 2670 // Generate code to load the content of the guard slot. 2671 SDValue GuardVal = DAG.getLoad( 2672 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2673 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2674 MachineMemOperand::MOVolatile); 2675 2676 if (TLI.useStackGuardXorFP()) 2677 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2678 2679 // Retrieve guard check function, nullptr if instrumentation is inlined. 2680 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2681 // The target provides a guard check function to validate the guard value. 2682 // Generate a call to that function with the content of the guard slot as 2683 // argument. 2684 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2685 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2686 2687 TargetLowering::ArgListTy Args; 2688 TargetLowering::ArgListEntry Entry; 2689 Entry.Node = GuardVal; 2690 Entry.Ty = FnTy->getParamType(0); 2691 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2692 Entry.IsInReg = true; 2693 Args.push_back(Entry); 2694 2695 TargetLowering::CallLoweringInfo CLI(DAG); 2696 CLI.setDebugLoc(getCurSDLoc()) 2697 .setChain(DAG.getEntryNode()) 2698 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2699 getValue(GuardCheckFn), std::move(Args)); 2700 2701 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2702 DAG.setRoot(Result.second); 2703 return; 2704 } 2705 2706 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2707 // Otherwise, emit a volatile load to retrieve the stack guard value. 2708 SDValue Chain = DAG.getEntryNode(); 2709 if (TLI.useLoadStackGuardNode()) { 2710 Guard = getLoadStackGuard(DAG, dl, Chain); 2711 } else { 2712 const Value *IRGuard = TLI.getSDagStackGuard(M); 2713 SDValue GuardPtr = getValue(IRGuard); 2714 2715 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2716 MachinePointerInfo(IRGuard, 0), Align, 2717 MachineMemOperand::MOVolatile); 2718 } 2719 2720 // Perform the comparison via a getsetcc. 2721 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2722 *DAG.getContext(), 2723 Guard.getValueType()), 2724 Guard, GuardVal, ISD::SETNE); 2725 2726 // If the guard/stackslot do not equal, branch to failure MBB. 2727 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2728 MVT::Other, GuardVal.getOperand(0), 2729 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2730 // Otherwise branch to success MBB. 2731 SDValue Br = DAG.getNode(ISD::BR, dl, 2732 MVT::Other, BrCond, 2733 DAG.getBasicBlock(SPD.getSuccessMBB())); 2734 2735 DAG.setRoot(Br); 2736 } 2737 2738 /// Codegen the failure basic block for a stack protector check. 2739 /// 2740 /// A failure stack protector machine basic block consists simply of a call to 2741 /// __stack_chk_fail(). 2742 /// 2743 /// For a high level explanation of how this fits into the stack protector 2744 /// generation see the comment on the declaration of class 2745 /// StackProtectorDescriptor. 2746 void 2747 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2748 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2749 TargetLowering::MakeLibCallOptions CallOptions; 2750 CallOptions.setDiscardResult(true); 2751 SDValue Chain = 2752 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2753 None, CallOptions, getCurSDLoc()).second; 2754 // On PS4, the "return address" must still be within the calling function, 2755 // even if it's at the very end, so emit an explicit TRAP here. 2756 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2757 if (TM.getTargetTriple().isPS4()) 2758 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2759 // WebAssembly needs an unreachable instruction after a non-returning call, 2760 // because the function return type can be different from __stack_chk_fail's 2761 // return type (void). 2762 if (TM.getTargetTriple().isWasm()) 2763 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2764 2765 DAG.setRoot(Chain); 2766 } 2767 2768 /// visitBitTestHeader - This function emits necessary code to produce value 2769 /// suitable for "bit tests" 2770 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2771 MachineBasicBlock *SwitchBB) { 2772 SDLoc dl = getCurSDLoc(); 2773 2774 // Subtract the minimum value. 2775 SDValue SwitchOp = getValue(B.SValue); 2776 EVT VT = SwitchOp.getValueType(); 2777 SDValue RangeSub = 2778 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2779 2780 // Determine the type of the test operands. 2781 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2782 bool UsePtrType = false; 2783 if (!TLI.isTypeLegal(VT)) { 2784 UsePtrType = true; 2785 } else { 2786 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2787 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2788 // Switch table case range are encoded into series of masks. 2789 // Just use pointer type, it's guaranteed to fit. 2790 UsePtrType = true; 2791 break; 2792 } 2793 } 2794 SDValue Sub = RangeSub; 2795 if (UsePtrType) { 2796 VT = TLI.getPointerTy(DAG.getDataLayout()); 2797 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2798 } 2799 2800 B.RegVT = VT.getSimpleVT(); 2801 B.Reg = FuncInfo.CreateReg(B.RegVT); 2802 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2803 2804 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2805 2806 if (!B.FallthroughUnreachable) 2807 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2808 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2809 SwitchBB->normalizeSuccProbs(); 2810 2811 SDValue Root = CopyTo; 2812 if (!B.FallthroughUnreachable) { 2813 // Conditional branch to the default block. 2814 SDValue RangeCmp = DAG.getSetCC(dl, 2815 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2816 RangeSub.getValueType()), 2817 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2818 ISD::SETUGT); 2819 2820 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2821 DAG.getBasicBlock(B.Default)); 2822 } 2823 2824 // Avoid emitting unnecessary branches to the next block. 2825 if (MBB != NextBlock(SwitchBB)) 2826 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2827 2828 DAG.setRoot(Root); 2829 } 2830 2831 /// visitBitTestCase - this function produces one "bit test" 2832 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2833 MachineBasicBlock* NextMBB, 2834 BranchProbability BranchProbToNext, 2835 unsigned Reg, 2836 BitTestCase &B, 2837 MachineBasicBlock *SwitchBB) { 2838 SDLoc dl = getCurSDLoc(); 2839 MVT VT = BB.RegVT; 2840 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2841 SDValue Cmp; 2842 unsigned PopCount = countPopulation(B.Mask); 2843 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2844 if (PopCount == 1) { 2845 // Testing for a single bit; just compare the shift count with what it 2846 // would need to be to shift a 1 bit in that position. 2847 Cmp = DAG.getSetCC( 2848 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2849 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2850 ISD::SETEQ); 2851 } else if (PopCount == BB.Range) { 2852 // There is only one zero bit in the range, test for it directly. 2853 Cmp = DAG.getSetCC( 2854 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2855 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2856 ISD::SETNE); 2857 } else { 2858 // Make desired shift 2859 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2860 DAG.getConstant(1, dl, VT), ShiftOp); 2861 2862 // Emit bit tests and jumps 2863 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2864 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2865 Cmp = DAG.getSetCC( 2866 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2867 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2868 } 2869 2870 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2871 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2872 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2873 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2874 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2875 // one as they are relative probabilities (and thus work more like weights), 2876 // and hence we need to normalize them to let the sum of them become one. 2877 SwitchBB->normalizeSuccProbs(); 2878 2879 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2880 MVT::Other, getControlRoot(), 2881 Cmp, DAG.getBasicBlock(B.TargetBB)); 2882 2883 // Avoid emitting unnecessary branches to the next block. 2884 if (NextMBB != NextBlock(SwitchBB)) 2885 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2886 DAG.getBasicBlock(NextMBB)); 2887 2888 DAG.setRoot(BrAnd); 2889 } 2890 2891 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2892 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2893 2894 // Retrieve successors. Look through artificial IR level blocks like 2895 // catchswitch for successors. 2896 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2897 const BasicBlock *EHPadBB = I.getSuccessor(1); 2898 2899 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2900 // have to do anything here to lower funclet bundles. 2901 assert(!I.hasOperandBundlesOtherThan( 2902 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2903 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2904 LLVMContext::OB_cfguardtarget, 2905 LLVMContext::OB_clang_arc_attachedcall}) && 2906 "Cannot lower invokes with arbitrary operand bundles yet!"); 2907 2908 const Value *Callee(I.getCalledOperand()); 2909 const Function *Fn = dyn_cast<Function>(Callee); 2910 if (isa<InlineAsm>(Callee)) 2911 visitInlineAsm(I, EHPadBB); 2912 else if (Fn && Fn->isIntrinsic()) { 2913 switch (Fn->getIntrinsicID()) { 2914 default: 2915 llvm_unreachable("Cannot invoke this intrinsic"); 2916 case Intrinsic::donothing: 2917 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2918 case Intrinsic::seh_try_begin: 2919 case Intrinsic::seh_scope_begin: 2920 case Intrinsic::seh_try_end: 2921 case Intrinsic::seh_scope_end: 2922 break; 2923 case Intrinsic::experimental_patchpoint_void: 2924 case Intrinsic::experimental_patchpoint_i64: 2925 visitPatchpoint(I, EHPadBB); 2926 break; 2927 case Intrinsic::experimental_gc_statepoint: 2928 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2929 break; 2930 case Intrinsic::wasm_rethrow: { 2931 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2932 // special because it can be invoked, so we manually lower it to a DAG 2933 // node here. 2934 SmallVector<SDValue, 8> Ops; 2935 Ops.push_back(getRoot()); // inchain 2936 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2937 Ops.push_back( 2938 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2939 TLI.getPointerTy(DAG.getDataLayout()))); 2940 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2941 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2942 break; 2943 } 2944 } 2945 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2946 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2947 // Eventually we will support lowering the @llvm.experimental.deoptimize 2948 // intrinsic, and right now there are no plans to support other intrinsics 2949 // with deopt state. 2950 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2951 } else { 2952 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2953 } 2954 2955 // If the value of the invoke is used outside of its defining block, make it 2956 // available as a virtual register. 2957 // We already took care of the exported value for the statepoint instruction 2958 // during call to the LowerStatepoint. 2959 if (!isa<GCStatepointInst>(I)) { 2960 CopyToExportRegsIfNeeded(&I); 2961 } 2962 2963 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2964 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2965 BranchProbability EHPadBBProb = 2966 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2967 : BranchProbability::getZero(); 2968 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2969 2970 // Update successor info. 2971 addSuccessorWithProb(InvokeMBB, Return); 2972 for (auto &UnwindDest : UnwindDests) { 2973 UnwindDest.first->setIsEHPad(); 2974 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2975 } 2976 InvokeMBB->normalizeSuccProbs(); 2977 2978 // Drop into normal successor. 2979 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2980 DAG.getBasicBlock(Return))); 2981 } 2982 2983 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2984 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2985 2986 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2987 // have to do anything here to lower funclet bundles. 2988 assert(!I.hasOperandBundlesOtherThan( 2989 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2990 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2991 2992 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2993 visitInlineAsm(I); 2994 CopyToExportRegsIfNeeded(&I); 2995 2996 // Retrieve successors. 2997 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2998 2999 // Update successor info. 3000 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3001 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3002 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 3003 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3004 Target->setIsInlineAsmBrIndirectTarget(); 3005 } 3006 CallBrMBB->normalizeSuccProbs(); 3007 3008 // Drop into default successor. 3009 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3010 MVT::Other, getControlRoot(), 3011 DAG.getBasicBlock(Return))); 3012 } 3013 3014 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3015 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3016 } 3017 3018 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3019 assert(FuncInfo.MBB->isEHPad() && 3020 "Call to landingpad not in landing pad!"); 3021 3022 // If there aren't registers to copy the values into (e.g., during SjLj 3023 // exceptions), then don't bother to create these DAG nodes. 3024 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3025 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3026 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3027 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3028 return; 3029 3030 // If landingpad's return type is token type, we don't create DAG nodes 3031 // for its exception pointer and selector value. The extraction of exception 3032 // pointer or selector value from token type landingpads is not currently 3033 // supported. 3034 if (LP.getType()->isTokenTy()) 3035 return; 3036 3037 SmallVector<EVT, 2> ValueVTs; 3038 SDLoc dl = getCurSDLoc(); 3039 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3040 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3041 3042 // Get the two live-in registers as SDValues. The physregs have already been 3043 // copied into virtual registers. 3044 SDValue Ops[2]; 3045 if (FuncInfo.ExceptionPointerVirtReg) { 3046 Ops[0] = DAG.getZExtOrTrunc( 3047 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3048 FuncInfo.ExceptionPointerVirtReg, 3049 TLI.getPointerTy(DAG.getDataLayout())), 3050 dl, ValueVTs[0]); 3051 } else { 3052 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3053 } 3054 Ops[1] = DAG.getZExtOrTrunc( 3055 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3056 FuncInfo.ExceptionSelectorVirtReg, 3057 TLI.getPointerTy(DAG.getDataLayout())), 3058 dl, ValueVTs[1]); 3059 3060 // Merge into one. 3061 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3062 DAG.getVTList(ValueVTs), Ops); 3063 setValue(&LP, Res); 3064 } 3065 3066 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3067 MachineBasicBlock *Last) { 3068 // Update JTCases. 3069 for (JumpTableBlock &JTB : SL->JTCases) 3070 if (JTB.first.HeaderBB == First) 3071 JTB.first.HeaderBB = Last; 3072 3073 // Update BitTestCases. 3074 for (BitTestBlock &BTB : SL->BitTestCases) 3075 if (BTB.Parent == First) 3076 BTB.Parent = Last; 3077 } 3078 3079 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3080 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3081 3082 // Update machine-CFG edges with unique successors. 3083 SmallSet<BasicBlock*, 32> Done; 3084 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3085 BasicBlock *BB = I.getSuccessor(i); 3086 bool Inserted = Done.insert(BB).second; 3087 if (!Inserted) 3088 continue; 3089 3090 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3091 addSuccessorWithProb(IndirectBrMBB, Succ); 3092 } 3093 IndirectBrMBB->normalizeSuccProbs(); 3094 3095 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3096 MVT::Other, getControlRoot(), 3097 getValue(I.getAddress()))); 3098 } 3099 3100 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3101 if (!DAG.getTarget().Options.TrapUnreachable) 3102 return; 3103 3104 // We may be able to ignore unreachable behind a noreturn call. 3105 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3106 const BasicBlock &BB = *I.getParent(); 3107 if (&I != &BB.front()) { 3108 BasicBlock::const_iterator PredI = 3109 std::prev(BasicBlock::const_iterator(&I)); 3110 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3111 if (Call->doesNotReturn()) 3112 return; 3113 } 3114 } 3115 } 3116 3117 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3118 } 3119 3120 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3121 SDNodeFlags Flags; 3122 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3123 Flags.copyFMF(*FPOp); 3124 3125 SDValue Op = getValue(I.getOperand(0)); 3126 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3127 Op, Flags); 3128 setValue(&I, UnNodeValue); 3129 } 3130 3131 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3132 SDNodeFlags Flags; 3133 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3134 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3135 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3136 } 3137 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3138 Flags.setExact(ExactOp->isExact()); 3139 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3140 Flags.copyFMF(*FPOp); 3141 3142 SDValue Op1 = getValue(I.getOperand(0)); 3143 SDValue Op2 = getValue(I.getOperand(1)); 3144 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3145 Op1, Op2, Flags); 3146 setValue(&I, BinNodeValue); 3147 } 3148 3149 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3150 SDValue Op1 = getValue(I.getOperand(0)); 3151 SDValue Op2 = getValue(I.getOperand(1)); 3152 3153 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3154 Op1.getValueType(), DAG.getDataLayout()); 3155 3156 // Coerce the shift amount to the right type if we can. This exposes the 3157 // truncate or zext to optimization early. 3158 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3159 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3160 "Unexpected shift type"); 3161 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3162 } 3163 3164 bool nuw = false; 3165 bool nsw = false; 3166 bool exact = false; 3167 3168 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3169 3170 if (const OverflowingBinaryOperator *OFBinOp = 3171 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3172 nuw = OFBinOp->hasNoUnsignedWrap(); 3173 nsw = OFBinOp->hasNoSignedWrap(); 3174 } 3175 if (const PossiblyExactOperator *ExactOp = 3176 dyn_cast<const PossiblyExactOperator>(&I)) 3177 exact = ExactOp->isExact(); 3178 } 3179 SDNodeFlags Flags; 3180 Flags.setExact(exact); 3181 Flags.setNoSignedWrap(nsw); 3182 Flags.setNoUnsignedWrap(nuw); 3183 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3184 Flags); 3185 setValue(&I, Res); 3186 } 3187 3188 void SelectionDAGBuilder::visitSDiv(const User &I) { 3189 SDValue Op1 = getValue(I.getOperand(0)); 3190 SDValue Op2 = getValue(I.getOperand(1)); 3191 3192 SDNodeFlags Flags; 3193 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3194 cast<PossiblyExactOperator>(&I)->isExact()); 3195 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3196 Op2, Flags)); 3197 } 3198 3199 void SelectionDAGBuilder::visitICmp(const User &I) { 3200 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3201 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3202 predicate = IC->getPredicate(); 3203 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3204 predicate = ICmpInst::Predicate(IC->getPredicate()); 3205 SDValue Op1 = getValue(I.getOperand(0)); 3206 SDValue Op2 = getValue(I.getOperand(1)); 3207 ISD::CondCode Opcode = getICmpCondCode(predicate); 3208 3209 auto &TLI = DAG.getTargetLoweringInfo(); 3210 EVT MemVT = 3211 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3212 3213 // If a pointer's DAG type is larger than its memory type then the DAG values 3214 // are zero-extended. This breaks signed comparisons so truncate back to the 3215 // underlying type before doing the compare. 3216 if (Op1.getValueType() != MemVT) { 3217 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3218 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3219 } 3220 3221 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3222 I.getType()); 3223 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3224 } 3225 3226 void SelectionDAGBuilder::visitFCmp(const User &I) { 3227 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3228 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3229 predicate = FC->getPredicate(); 3230 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3231 predicate = FCmpInst::Predicate(FC->getPredicate()); 3232 SDValue Op1 = getValue(I.getOperand(0)); 3233 SDValue Op2 = getValue(I.getOperand(1)); 3234 3235 ISD::CondCode Condition = getFCmpCondCode(predicate); 3236 auto *FPMO = cast<FPMathOperator>(&I); 3237 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3238 Condition = getFCmpCodeWithoutNaN(Condition); 3239 3240 SDNodeFlags Flags; 3241 Flags.copyFMF(*FPMO); 3242 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3243 3244 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3245 I.getType()); 3246 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3247 } 3248 3249 // Check if the condition of the select has one use or two users that are both 3250 // selects with the same condition. 3251 static bool hasOnlySelectUsers(const Value *Cond) { 3252 return llvm::all_of(Cond->users(), [](const Value *V) { 3253 return isa<SelectInst>(V); 3254 }); 3255 } 3256 3257 void SelectionDAGBuilder::visitSelect(const User &I) { 3258 SmallVector<EVT, 4> ValueVTs; 3259 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3260 ValueVTs); 3261 unsigned NumValues = ValueVTs.size(); 3262 if (NumValues == 0) return; 3263 3264 SmallVector<SDValue, 4> Values(NumValues); 3265 SDValue Cond = getValue(I.getOperand(0)); 3266 SDValue LHSVal = getValue(I.getOperand(1)); 3267 SDValue RHSVal = getValue(I.getOperand(2)); 3268 SmallVector<SDValue, 1> BaseOps(1, Cond); 3269 ISD::NodeType OpCode = 3270 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3271 3272 bool IsUnaryAbs = false; 3273 bool Negate = false; 3274 3275 SDNodeFlags Flags; 3276 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3277 Flags.copyFMF(*FPOp); 3278 3279 // Min/max matching is only viable if all output VTs are the same. 3280 if (is_splat(ValueVTs)) { 3281 EVT VT = ValueVTs[0]; 3282 LLVMContext &Ctx = *DAG.getContext(); 3283 auto &TLI = DAG.getTargetLoweringInfo(); 3284 3285 // We care about the legality of the operation after it has been type 3286 // legalized. 3287 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3288 VT = TLI.getTypeToTransformTo(Ctx, VT); 3289 3290 // If the vselect is legal, assume we want to leave this as a vector setcc + 3291 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3292 // min/max is legal on the scalar type. 3293 bool UseScalarMinMax = VT.isVector() && 3294 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3295 3296 Value *LHS, *RHS; 3297 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3298 ISD::NodeType Opc = ISD::DELETED_NODE; 3299 switch (SPR.Flavor) { 3300 case SPF_UMAX: Opc = ISD::UMAX; break; 3301 case SPF_UMIN: Opc = ISD::UMIN; break; 3302 case SPF_SMAX: Opc = ISD::SMAX; break; 3303 case SPF_SMIN: Opc = ISD::SMIN; break; 3304 case SPF_FMINNUM: 3305 switch (SPR.NaNBehavior) { 3306 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3307 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3308 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3309 case SPNB_RETURNS_ANY: { 3310 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3311 Opc = ISD::FMINNUM; 3312 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3313 Opc = ISD::FMINIMUM; 3314 else if (UseScalarMinMax) 3315 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3316 ISD::FMINNUM : ISD::FMINIMUM; 3317 break; 3318 } 3319 } 3320 break; 3321 case SPF_FMAXNUM: 3322 switch (SPR.NaNBehavior) { 3323 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3324 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3325 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3326 case SPNB_RETURNS_ANY: 3327 3328 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3329 Opc = ISD::FMAXNUM; 3330 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3331 Opc = ISD::FMAXIMUM; 3332 else if (UseScalarMinMax) 3333 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3334 ISD::FMAXNUM : ISD::FMAXIMUM; 3335 break; 3336 } 3337 break; 3338 case SPF_NABS: 3339 Negate = true; 3340 LLVM_FALLTHROUGH; 3341 case SPF_ABS: 3342 IsUnaryAbs = true; 3343 Opc = ISD::ABS; 3344 break; 3345 default: break; 3346 } 3347 3348 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3349 (TLI.isOperationLegalOrCustom(Opc, VT) || 3350 (UseScalarMinMax && 3351 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3352 // If the underlying comparison instruction is used by any other 3353 // instruction, the consumed instructions won't be destroyed, so it is 3354 // not profitable to convert to a min/max. 3355 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3356 OpCode = Opc; 3357 LHSVal = getValue(LHS); 3358 RHSVal = getValue(RHS); 3359 BaseOps.clear(); 3360 } 3361 3362 if (IsUnaryAbs) { 3363 OpCode = Opc; 3364 LHSVal = getValue(LHS); 3365 BaseOps.clear(); 3366 } 3367 } 3368 3369 if (IsUnaryAbs) { 3370 for (unsigned i = 0; i != NumValues; ++i) { 3371 SDLoc dl = getCurSDLoc(); 3372 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3373 Values[i] = 3374 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3375 if (Negate) 3376 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3377 Values[i]); 3378 } 3379 } else { 3380 for (unsigned i = 0; i != NumValues; ++i) { 3381 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3382 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3383 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3384 Values[i] = DAG.getNode( 3385 OpCode, getCurSDLoc(), 3386 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3387 } 3388 } 3389 3390 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3391 DAG.getVTList(ValueVTs), Values)); 3392 } 3393 3394 void SelectionDAGBuilder::visitTrunc(const User &I) { 3395 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3396 SDValue N = getValue(I.getOperand(0)); 3397 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3398 I.getType()); 3399 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3400 } 3401 3402 void SelectionDAGBuilder::visitZExt(const User &I) { 3403 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3404 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3405 SDValue N = getValue(I.getOperand(0)); 3406 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3407 I.getType()); 3408 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3409 } 3410 3411 void SelectionDAGBuilder::visitSExt(const User &I) { 3412 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3413 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3414 SDValue N = getValue(I.getOperand(0)); 3415 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3416 I.getType()); 3417 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3418 } 3419 3420 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3421 // FPTrunc is never a no-op cast, no need to check 3422 SDValue N = getValue(I.getOperand(0)); 3423 SDLoc dl = getCurSDLoc(); 3424 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3425 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3426 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3427 DAG.getTargetConstant( 3428 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3429 } 3430 3431 void SelectionDAGBuilder::visitFPExt(const User &I) { 3432 // FPExt is never a no-op cast, no need to check 3433 SDValue N = getValue(I.getOperand(0)); 3434 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3435 I.getType()); 3436 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3437 } 3438 3439 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3440 // FPToUI is never a no-op cast, no need to check 3441 SDValue N = getValue(I.getOperand(0)); 3442 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3443 I.getType()); 3444 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3445 } 3446 3447 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3448 // FPToSI is never a no-op cast, no need to check 3449 SDValue N = getValue(I.getOperand(0)); 3450 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3451 I.getType()); 3452 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3453 } 3454 3455 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3456 // UIToFP is never a no-op cast, no need to check 3457 SDValue N = getValue(I.getOperand(0)); 3458 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3459 I.getType()); 3460 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3461 } 3462 3463 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3464 // SIToFP is never a no-op cast, no need to check 3465 SDValue N = getValue(I.getOperand(0)); 3466 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3467 I.getType()); 3468 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3469 } 3470 3471 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3472 // What to do depends on the size of the integer and the size of the pointer. 3473 // We can either truncate, zero extend, or no-op, accordingly. 3474 SDValue N = getValue(I.getOperand(0)); 3475 auto &TLI = DAG.getTargetLoweringInfo(); 3476 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3477 I.getType()); 3478 EVT PtrMemVT = 3479 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3480 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3481 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3482 setValue(&I, N); 3483 } 3484 3485 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3486 // What to do depends on the size of the integer and the size of the pointer. 3487 // We can either truncate, zero extend, or no-op, accordingly. 3488 SDValue N = getValue(I.getOperand(0)); 3489 auto &TLI = DAG.getTargetLoweringInfo(); 3490 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3491 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3492 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3493 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3494 setValue(&I, N); 3495 } 3496 3497 void SelectionDAGBuilder::visitBitCast(const User &I) { 3498 SDValue N = getValue(I.getOperand(0)); 3499 SDLoc dl = getCurSDLoc(); 3500 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3501 I.getType()); 3502 3503 // BitCast assures us that source and destination are the same size so this is 3504 // either a BITCAST or a no-op. 3505 if (DestVT != N.getValueType()) 3506 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3507 DestVT, N)); // convert types. 3508 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3509 // might fold any kind of constant expression to an integer constant and that 3510 // is not what we are looking for. Only recognize a bitcast of a genuine 3511 // constant integer as an opaque constant. 3512 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3513 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3514 /*isOpaque*/true)); 3515 else 3516 setValue(&I, N); // noop cast. 3517 } 3518 3519 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3520 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3521 const Value *SV = I.getOperand(0); 3522 SDValue N = getValue(SV); 3523 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3524 3525 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3526 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3527 3528 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3529 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3530 3531 setValue(&I, N); 3532 } 3533 3534 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3535 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3536 SDValue InVec = getValue(I.getOperand(0)); 3537 SDValue InVal = getValue(I.getOperand(1)); 3538 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3539 TLI.getVectorIdxTy(DAG.getDataLayout())); 3540 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3541 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3542 InVec, InVal, InIdx)); 3543 } 3544 3545 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3546 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3547 SDValue InVec = getValue(I.getOperand(0)); 3548 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3549 TLI.getVectorIdxTy(DAG.getDataLayout())); 3550 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3551 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3552 InVec, InIdx)); 3553 } 3554 3555 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3556 SDValue Src1 = getValue(I.getOperand(0)); 3557 SDValue Src2 = getValue(I.getOperand(1)); 3558 ArrayRef<int> Mask; 3559 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3560 Mask = SVI->getShuffleMask(); 3561 else 3562 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3563 SDLoc DL = getCurSDLoc(); 3564 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3565 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3566 EVT SrcVT = Src1.getValueType(); 3567 3568 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3569 VT.isScalableVector()) { 3570 // Canonical splat form of first element of first input vector. 3571 SDValue FirstElt = 3572 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3573 DAG.getVectorIdxConstant(0, DL)); 3574 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3575 return; 3576 } 3577 3578 // For now, we only handle splats for scalable vectors. 3579 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3580 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3581 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3582 3583 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3584 unsigned MaskNumElts = Mask.size(); 3585 3586 if (SrcNumElts == MaskNumElts) { 3587 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3588 return; 3589 } 3590 3591 // Normalize the shuffle vector since mask and vector length don't match. 3592 if (SrcNumElts < MaskNumElts) { 3593 // Mask is longer than the source vectors. We can use concatenate vector to 3594 // make the mask and vectors lengths match. 3595 3596 if (MaskNumElts % SrcNumElts == 0) { 3597 // Mask length is a multiple of the source vector length. 3598 // Check if the shuffle is some kind of concatenation of the input 3599 // vectors. 3600 unsigned NumConcat = MaskNumElts / SrcNumElts; 3601 bool IsConcat = true; 3602 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3603 for (unsigned i = 0; i != MaskNumElts; ++i) { 3604 int Idx = Mask[i]; 3605 if (Idx < 0) 3606 continue; 3607 // Ensure the indices in each SrcVT sized piece are sequential and that 3608 // the same source is used for the whole piece. 3609 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3610 (ConcatSrcs[i / SrcNumElts] >= 0 && 3611 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3612 IsConcat = false; 3613 break; 3614 } 3615 // Remember which source this index came from. 3616 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3617 } 3618 3619 // The shuffle is concatenating multiple vectors together. Just emit 3620 // a CONCAT_VECTORS operation. 3621 if (IsConcat) { 3622 SmallVector<SDValue, 8> ConcatOps; 3623 for (auto Src : ConcatSrcs) { 3624 if (Src < 0) 3625 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3626 else if (Src == 0) 3627 ConcatOps.push_back(Src1); 3628 else 3629 ConcatOps.push_back(Src2); 3630 } 3631 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3632 return; 3633 } 3634 } 3635 3636 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3637 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3638 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3639 PaddedMaskNumElts); 3640 3641 // Pad both vectors with undefs to make them the same length as the mask. 3642 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3643 3644 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3645 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3646 MOps1[0] = Src1; 3647 MOps2[0] = Src2; 3648 3649 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3650 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3651 3652 // Readjust mask for new input vector length. 3653 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3654 for (unsigned i = 0; i != MaskNumElts; ++i) { 3655 int Idx = Mask[i]; 3656 if (Idx >= (int)SrcNumElts) 3657 Idx -= SrcNumElts - PaddedMaskNumElts; 3658 MappedOps[i] = Idx; 3659 } 3660 3661 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3662 3663 // If the concatenated vector was padded, extract a subvector with the 3664 // correct number of elements. 3665 if (MaskNumElts != PaddedMaskNumElts) 3666 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3667 DAG.getVectorIdxConstant(0, DL)); 3668 3669 setValue(&I, Result); 3670 return; 3671 } 3672 3673 if (SrcNumElts > MaskNumElts) { 3674 // Analyze the access pattern of the vector to see if we can extract 3675 // two subvectors and do the shuffle. 3676 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3677 bool CanExtract = true; 3678 for (int Idx : Mask) { 3679 unsigned Input = 0; 3680 if (Idx < 0) 3681 continue; 3682 3683 if (Idx >= (int)SrcNumElts) { 3684 Input = 1; 3685 Idx -= SrcNumElts; 3686 } 3687 3688 // If all the indices come from the same MaskNumElts sized portion of 3689 // the sources we can use extract. Also make sure the extract wouldn't 3690 // extract past the end of the source. 3691 int NewStartIdx = alignDown(Idx, MaskNumElts); 3692 if (NewStartIdx + MaskNumElts > SrcNumElts || 3693 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3694 CanExtract = false; 3695 // Make sure we always update StartIdx as we use it to track if all 3696 // elements are undef. 3697 StartIdx[Input] = NewStartIdx; 3698 } 3699 3700 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3701 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3702 return; 3703 } 3704 if (CanExtract) { 3705 // Extract appropriate subvector and generate a vector shuffle 3706 for (unsigned Input = 0; Input < 2; ++Input) { 3707 SDValue &Src = Input == 0 ? Src1 : Src2; 3708 if (StartIdx[Input] < 0) 3709 Src = DAG.getUNDEF(VT); 3710 else { 3711 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3712 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3713 } 3714 } 3715 3716 // Calculate new mask. 3717 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3718 for (int &Idx : MappedOps) { 3719 if (Idx >= (int)SrcNumElts) 3720 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3721 else if (Idx >= 0) 3722 Idx -= StartIdx[0]; 3723 } 3724 3725 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3726 return; 3727 } 3728 } 3729 3730 // We can't use either concat vectors or extract subvectors so fall back to 3731 // replacing the shuffle with extract and build vector. 3732 // to insert and build vector. 3733 EVT EltVT = VT.getVectorElementType(); 3734 SmallVector<SDValue,8> Ops; 3735 for (int Idx : Mask) { 3736 SDValue Res; 3737 3738 if (Idx < 0) { 3739 Res = DAG.getUNDEF(EltVT); 3740 } else { 3741 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3742 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3743 3744 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3745 DAG.getVectorIdxConstant(Idx, DL)); 3746 } 3747 3748 Ops.push_back(Res); 3749 } 3750 3751 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3752 } 3753 3754 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3755 ArrayRef<unsigned> Indices; 3756 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3757 Indices = IV->getIndices(); 3758 else 3759 Indices = cast<ConstantExpr>(&I)->getIndices(); 3760 3761 const Value *Op0 = I.getOperand(0); 3762 const Value *Op1 = I.getOperand(1); 3763 Type *AggTy = I.getType(); 3764 Type *ValTy = Op1->getType(); 3765 bool IntoUndef = isa<UndefValue>(Op0); 3766 bool FromUndef = isa<UndefValue>(Op1); 3767 3768 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3769 3770 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3771 SmallVector<EVT, 4> AggValueVTs; 3772 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3773 SmallVector<EVT, 4> ValValueVTs; 3774 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3775 3776 unsigned NumAggValues = AggValueVTs.size(); 3777 unsigned NumValValues = ValValueVTs.size(); 3778 SmallVector<SDValue, 4> Values(NumAggValues); 3779 3780 // Ignore an insertvalue that produces an empty object 3781 if (!NumAggValues) { 3782 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3783 return; 3784 } 3785 3786 SDValue Agg = getValue(Op0); 3787 unsigned i = 0; 3788 // Copy the beginning value(s) from the original aggregate. 3789 for (; i != LinearIndex; ++i) 3790 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3791 SDValue(Agg.getNode(), Agg.getResNo() + i); 3792 // Copy values from the inserted value(s). 3793 if (NumValValues) { 3794 SDValue Val = getValue(Op1); 3795 for (; i != LinearIndex + NumValValues; ++i) 3796 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3797 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3798 } 3799 // Copy remaining value(s) from the original aggregate. 3800 for (; i != NumAggValues; ++i) 3801 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3802 SDValue(Agg.getNode(), Agg.getResNo() + i); 3803 3804 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3805 DAG.getVTList(AggValueVTs), Values)); 3806 } 3807 3808 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3809 ArrayRef<unsigned> Indices; 3810 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3811 Indices = EV->getIndices(); 3812 else 3813 Indices = cast<ConstantExpr>(&I)->getIndices(); 3814 3815 const Value *Op0 = I.getOperand(0); 3816 Type *AggTy = Op0->getType(); 3817 Type *ValTy = I.getType(); 3818 bool OutOfUndef = isa<UndefValue>(Op0); 3819 3820 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3821 3822 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3823 SmallVector<EVT, 4> ValValueVTs; 3824 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3825 3826 unsigned NumValValues = ValValueVTs.size(); 3827 3828 // Ignore a extractvalue that produces an empty object 3829 if (!NumValValues) { 3830 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3831 return; 3832 } 3833 3834 SmallVector<SDValue, 4> Values(NumValValues); 3835 3836 SDValue Agg = getValue(Op0); 3837 // Copy out the selected value(s). 3838 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3839 Values[i - LinearIndex] = 3840 OutOfUndef ? 3841 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3842 SDValue(Agg.getNode(), Agg.getResNo() + i); 3843 3844 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3845 DAG.getVTList(ValValueVTs), Values)); 3846 } 3847 3848 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3849 Value *Op0 = I.getOperand(0); 3850 // Note that the pointer operand may be a vector of pointers. Take the scalar 3851 // element which holds a pointer. 3852 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3853 SDValue N = getValue(Op0); 3854 SDLoc dl = getCurSDLoc(); 3855 auto &TLI = DAG.getTargetLoweringInfo(); 3856 3857 // Normalize Vector GEP - all scalar operands should be converted to the 3858 // splat vector. 3859 bool IsVectorGEP = I.getType()->isVectorTy(); 3860 ElementCount VectorElementCount = 3861 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3862 : ElementCount::getFixed(0); 3863 3864 if (IsVectorGEP && !N.getValueType().isVector()) { 3865 LLVMContext &Context = *DAG.getContext(); 3866 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3867 if (VectorElementCount.isScalable()) 3868 N = DAG.getSplatVector(VT, dl, N); 3869 else 3870 N = DAG.getSplatBuildVector(VT, dl, N); 3871 } 3872 3873 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3874 GTI != E; ++GTI) { 3875 const Value *Idx = GTI.getOperand(); 3876 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3877 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3878 if (Field) { 3879 // N = N + Offset 3880 uint64_t Offset = 3881 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3882 3883 // In an inbounds GEP with an offset that is nonnegative even when 3884 // interpreted as signed, assume there is no unsigned overflow. 3885 SDNodeFlags Flags; 3886 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3887 Flags.setNoUnsignedWrap(true); 3888 3889 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3890 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3891 } 3892 } else { 3893 // IdxSize is the width of the arithmetic according to IR semantics. 3894 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3895 // (and fix up the result later). 3896 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3897 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3898 TypeSize ElementSize = 3899 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3900 // We intentionally mask away the high bits here; ElementSize may not 3901 // fit in IdxTy. 3902 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3903 bool ElementScalable = ElementSize.isScalable(); 3904 3905 // If this is a scalar constant or a splat vector of constants, 3906 // handle it quickly. 3907 const auto *C = dyn_cast<Constant>(Idx); 3908 if (C && isa<VectorType>(C->getType())) 3909 C = C->getSplatValue(); 3910 3911 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3912 if (CI && CI->isZero()) 3913 continue; 3914 if (CI && !ElementScalable) { 3915 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3916 LLVMContext &Context = *DAG.getContext(); 3917 SDValue OffsVal; 3918 if (IsVectorGEP) 3919 OffsVal = DAG.getConstant( 3920 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3921 else 3922 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3923 3924 // In an inbounds GEP with an offset that is nonnegative even when 3925 // interpreted as signed, assume there is no unsigned overflow. 3926 SDNodeFlags Flags; 3927 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3928 Flags.setNoUnsignedWrap(true); 3929 3930 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3931 3932 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3933 continue; 3934 } 3935 3936 // N = N + Idx * ElementMul; 3937 SDValue IdxN = getValue(Idx); 3938 3939 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3940 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3941 VectorElementCount); 3942 if (VectorElementCount.isScalable()) 3943 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3944 else 3945 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3946 } 3947 3948 // If the index is smaller or larger than intptr_t, truncate or extend 3949 // it. 3950 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3951 3952 if (ElementScalable) { 3953 EVT VScaleTy = N.getValueType().getScalarType(); 3954 SDValue VScale = DAG.getNode( 3955 ISD::VSCALE, dl, VScaleTy, 3956 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3957 if (IsVectorGEP) 3958 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3959 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3960 } else { 3961 // If this is a multiply by a power of two, turn it into a shl 3962 // immediately. This is a very common case. 3963 if (ElementMul != 1) { 3964 if (ElementMul.isPowerOf2()) { 3965 unsigned Amt = ElementMul.logBase2(); 3966 IdxN = DAG.getNode(ISD::SHL, dl, 3967 N.getValueType(), IdxN, 3968 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3969 } else { 3970 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3971 IdxN.getValueType()); 3972 IdxN = DAG.getNode(ISD::MUL, dl, 3973 N.getValueType(), IdxN, Scale); 3974 } 3975 } 3976 } 3977 3978 N = DAG.getNode(ISD::ADD, dl, 3979 N.getValueType(), N, IdxN); 3980 } 3981 } 3982 3983 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3984 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3985 if (IsVectorGEP) { 3986 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3987 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3988 } 3989 3990 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3991 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3992 3993 setValue(&I, N); 3994 } 3995 3996 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3997 // If this is a fixed sized alloca in the entry block of the function, 3998 // allocate it statically on the stack. 3999 if (FuncInfo.StaticAllocaMap.count(&I)) 4000 return; // getValue will auto-populate this. 4001 4002 SDLoc dl = getCurSDLoc(); 4003 Type *Ty = I.getAllocatedType(); 4004 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4005 auto &DL = DAG.getDataLayout(); 4006 TypeSize TySize = DL.getTypeAllocSize(Ty); 4007 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4008 4009 SDValue AllocSize = getValue(I.getArraySize()); 4010 4011 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4012 if (AllocSize.getValueType() != IntPtr) 4013 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4014 4015 if (TySize.isScalable()) 4016 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4017 DAG.getVScale(dl, IntPtr, 4018 APInt(IntPtr.getScalarSizeInBits(), 4019 TySize.getKnownMinValue()))); 4020 else 4021 AllocSize = 4022 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4023 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4024 4025 // Handle alignment. If the requested alignment is less than or equal to 4026 // the stack alignment, ignore it. If the size is greater than or equal to 4027 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4028 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4029 if (*Alignment <= StackAlign) 4030 Alignment = None; 4031 4032 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4033 // Round the size of the allocation up to the stack alignment size 4034 // by add SA-1 to the size. This doesn't overflow because we're computing 4035 // an address inside an alloca. 4036 SDNodeFlags Flags; 4037 Flags.setNoUnsignedWrap(true); 4038 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4039 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4040 4041 // Mask out the low bits for alignment purposes. 4042 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4043 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4044 4045 SDValue Ops[] = { 4046 getRoot(), AllocSize, 4047 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4048 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4049 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4050 setValue(&I, DSA); 4051 DAG.setRoot(DSA.getValue(1)); 4052 4053 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4054 } 4055 4056 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4057 if (I.isAtomic()) 4058 return visitAtomicLoad(I); 4059 4060 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4061 const Value *SV = I.getOperand(0); 4062 if (TLI.supportSwiftError()) { 4063 // Swifterror values can come from either a function parameter with 4064 // swifterror attribute or an alloca with swifterror attribute. 4065 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4066 if (Arg->hasSwiftErrorAttr()) 4067 return visitLoadFromSwiftError(I); 4068 } 4069 4070 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4071 if (Alloca->isSwiftError()) 4072 return visitLoadFromSwiftError(I); 4073 } 4074 } 4075 4076 SDValue Ptr = getValue(SV); 4077 4078 Type *Ty = I.getType(); 4079 Align Alignment = I.getAlign(); 4080 4081 AAMDNodes AAInfo = I.getAAMetadata(); 4082 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4083 4084 SmallVector<EVT, 4> ValueVTs, MemVTs; 4085 SmallVector<uint64_t, 4> Offsets; 4086 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4087 unsigned NumValues = ValueVTs.size(); 4088 if (NumValues == 0) 4089 return; 4090 4091 bool isVolatile = I.isVolatile(); 4092 4093 SDValue Root; 4094 bool ConstantMemory = false; 4095 if (isVolatile) 4096 // Serialize volatile loads with other side effects. 4097 Root = getRoot(); 4098 else if (NumValues > MaxParallelChains) 4099 Root = getMemoryRoot(); 4100 else if (AA && 4101 AA->pointsToConstantMemory(MemoryLocation( 4102 SV, 4103 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4104 AAInfo))) { 4105 // Do not serialize (non-volatile) loads of constant memory with anything. 4106 Root = DAG.getEntryNode(); 4107 ConstantMemory = true; 4108 } else { 4109 // Do not serialize non-volatile loads against each other. 4110 Root = DAG.getRoot(); 4111 } 4112 4113 SDLoc dl = getCurSDLoc(); 4114 4115 if (isVolatile) 4116 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4117 4118 // An aggregate load cannot wrap around the address space, so offsets to its 4119 // parts don't wrap either. 4120 SDNodeFlags Flags; 4121 Flags.setNoUnsignedWrap(true); 4122 4123 SmallVector<SDValue, 4> Values(NumValues); 4124 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4125 EVT PtrVT = Ptr.getValueType(); 4126 4127 MachineMemOperand::Flags MMOFlags 4128 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4129 4130 unsigned ChainI = 0; 4131 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4132 // Serializing loads here may result in excessive register pressure, and 4133 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4134 // could recover a bit by hoisting nodes upward in the chain by recognizing 4135 // they are side-effect free or do not alias. The optimizer should really 4136 // avoid this case by converting large object/array copies to llvm.memcpy 4137 // (MaxParallelChains should always remain as failsafe). 4138 if (ChainI == MaxParallelChains) { 4139 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4140 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4141 makeArrayRef(Chains.data(), ChainI)); 4142 Root = Chain; 4143 ChainI = 0; 4144 } 4145 SDValue A = DAG.getNode(ISD::ADD, dl, 4146 PtrVT, Ptr, 4147 DAG.getConstant(Offsets[i], dl, PtrVT), 4148 Flags); 4149 4150 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4151 MachinePointerInfo(SV, Offsets[i]), Alignment, 4152 MMOFlags, AAInfo, Ranges); 4153 Chains[ChainI] = L.getValue(1); 4154 4155 if (MemVTs[i] != ValueVTs[i]) 4156 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4157 4158 Values[i] = L; 4159 } 4160 4161 if (!ConstantMemory) { 4162 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4163 makeArrayRef(Chains.data(), ChainI)); 4164 if (isVolatile) 4165 DAG.setRoot(Chain); 4166 else 4167 PendingLoads.push_back(Chain); 4168 } 4169 4170 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4171 DAG.getVTList(ValueVTs), Values)); 4172 } 4173 4174 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4175 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4176 "call visitStoreToSwiftError when backend supports swifterror"); 4177 4178 SmallVector<EVT, 4> ValueVTs; 4179 SmallVector<uint64_t, 4> Offsets; 4180 const Value *SrcV = I.getOperand(0); 4181 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4182 SrcV->getType(), ValueVTs, &Offsets); 4183 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4184 "expect a single EVT for swifterror"); 4185 4186 SDValue Src = getValue(SrcV); 4187 // Create a virtual register, then update the virtual register. 4188 Register VReg = 4189 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4190 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4191 // Chain can be getRoot or getControlRoot. 4192 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4193 SDValue(Src.getNode(), Src.getResNo())); 4194 DAG.setRoot(CopyNode); 4195 } 4196 4197 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4198 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4199 "call visitLoadFromSwiftError when backend supports swifterror"); 4200 4201 assert(!I.isVolatile() && 4202 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4203 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4204 "Support volatile, non temporal, invariant for load_from_swift_error"); 4205 4206 const Value *SV = I.getOperand(0); 4207 Type *Ty = I.getType(); 4208 assert( 4209 (!AA || 4210 !AA->pointsToConstantMemory(MemoryLocation( 4211 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4212 I.getAAMetadata()))) && 4213 "load_from_swift_error should not be constant memory"); 4214 4215 SmallVector<EVT, 4> ValueVTs; 4216 SmallVector<uint64_t, 4> Offsets; 4217 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4218 ValueVTs, &Offsets); 4219 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4220 "expect a single EVT for swifterror"); 4221 4222 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4223 SDValue L = DAG.getCopyFromReg( 4224 getRoot(), getCurSDLoc(), 4225 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4226 4227 setValue(&I, L); 4228 } 4229 4230 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4231 if (I.isAtomic()) 4232 return visitAtomicStore(I); 4233 4234 const Value *SrcV = I.getOperand(0); 4235 const Value *PtrV = I.getOperand(1); 4236 4237 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4238 if (TLI.supportSwiftError()) { 4239 // Swifterror values can come from either a function parameter with 4240 // swifterror attribute or an alloca with swifterror attribute. 4241 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4242 if (Arg->hasSwiftErrorAttr()) 4243 return visitStoreToSwiftError(I); 4244 } 4245 4246 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4247 if (Alloca->isSwiftError()) 4248 return visitStoreToSwiftError(I); 4249 } 4250 } 4251 4252 SmallVector<EVT, 4> ValueVTs, MemVTs; 4253 SmallVector<uint64_t, 4> Offsets; 4254 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4255 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4256 unsigned NumValues = ValueVTs.size(); 4257 if (NumValues == 0) 4258 return; 4259 4260 // Get the lowered operands. Note that we do this after 4261 // checking if NumResults is zero, because with zero results 4262 // the operands won't have values in the map. 4263 SDValue Src = getValue(SrcV); 4264 SDValue Ptr = getValue(PtrV); 4265 4266 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4267 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4268 SDLoc dl = getCurSDLoc(); 4269 Align Alignment = I.getAlign(); 4270 AAMDNodes AAInfo = I.getAAMetadata(); 4271 4272 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4273 4274 // An aggregate load cannot wrap around the address space, so offsets to its 4275 // parts don't wrap either. 4276 SDNodeFlags Flags; 4277 Flags.setNoUnsignedWrap(true); 4278 4279 unsigned ChainI = 0; 4280 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4281 // See visitLoad comments. 4282 if (ChainI == MaxParallelChains) { 4283 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4284 makeArrayRef(Chains.data(), ChainI)); 4285 Root = Chain; 4286 ChainI = 0; 4287 } 4288 SDValue Add = 4289 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4290 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4291 if (MemVTs[i] != ValueVTs[i]) 4292 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4293 SDValue St = 4294 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4295 Alignment, MMOFlags, AAInfo); 4296 Chains[ChainI] = St; 4297 } 4298 4299 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4300 makeArrayRef(Chains.data(), ChainI)); 4301 DAG.setRoot(StoreNode); 4302 } 4303 4304 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4305 bool IsCompressing) { 4306 SDLoc sdl = getCurSDLoc(); 4307 4308 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4309 MaybeAlign &Alignment) { 4310 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4311 Src0 = I.getArgOperand(0); 4312 Ptr = I.getArgOperand(1); 4313 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4314 Mask = I.getArgOperand(3); 4315 }; 4316 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4317 MaybeAlign &Alignment) { 4318 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4319 Src0 = I.getArgOperand(0); 4320 Ptr = I.getArgOperand(1); 4321 Mask = I.getArgOperand(2); 4322 Alignment = None; 4323 }; 4324 4325 Value *PtrOperand, *MaskOperand, *Src0Operand; 4326 MaybeAlign Alignment; 4327 if (IsCompressing) 4328 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4329 else 4330 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4331 4332 SDValue Ptr = getValue(PtrOperand); 4333 SDValue Src0 = getValue(Src0Operand); 4334 SDValue Mask = getValue(MaskOperand); 4335 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4336 4337 EVT VT = Src0.getValueType(); 4338 if (!Alignment) 4339 Alignment = DAG.getEVTAlign(VT); 4340 4341 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4342 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4343 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4344 SDValue StoreNode = 4345 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4346 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4347 DAG.setRoot(StoreNode); 4348 setValue(&I, StoreNode); 4349 } 4350 4351 // Get a uniform base for the Gather/Scatter intrinsic. 4352 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4353 // We try to represent it as a base pointer + vector of indices. 4354 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4355 // The first operand of the GEP may be a single pointer or a vector of pointers 4356 // Example: 4357 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4358 // or 4359 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4360 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4361 // 4362 // When the first GEP operand is a single pointer - it is the uniform base we 4363 // are looking for. If first operand of the GEP is a splat vector - we 4364 // extract the splat value and use it as a uniform base. 4365 // In all other cases the function returns 'false'. 4366 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4367 ISD::MemIndexType &IndexType, SDValue &Scale, 4368 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4369 SelectionDAG& DAG = SDB->DAG; 4370 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4371 const DataLayout &DL = DAG.getDataLayout(); 4372 4373 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4374 4375 // Handle splat constant pointer. 4376 if (auto *C = dyn_cast<Constant>(Ptr)) { 4377 C = C->getSplatValue(); 4378 if (!C) 4379 return false; 4380 4381 Base = SDB->getValue(C); 4382 4383 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4384 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4385 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4386 IndexType = ISD::SIGNED_SCALED; 4387 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4388 return true; 4389 } 4390 4391 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4392 if (!GEP || GEP->getParent() != CurBB) 4393 return false; 4394 4395 if (GEP->getNumOperands() != 2) 4396 return false; 4397 4398 const Value *BasePtr = GEP->getPointerOperand(); 4399 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4400 4401 // Make sure the base is scalar and the index is a vector. 4402 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4403 return false; 4404 4405 Base = SDB->getValue(BasePtr); 4406 Index = SDB->getValue(IndexVal); 4407 IndexType = ISD::SIGNED_SCALED; 4408 Scale = DAG.getTargetConstant( 4409 DL.getTypeAllocSize(GEP->getResultElementType()), 4410 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4411 return true; 4412 } 4413 4414 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4415 SDLoc sdl = getCurSDLoc(); 4416 4417 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4418 const Value *Ptr = I.getArgOperand(1); 4419 SDValue Src0 = getValue(I.getArgOperand(0)); 4420 SDValue Mask = getValue(I.getArgOperand(3)); 4421 EVT VT = Src0.getValueType(); 4422 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4423 ->getMaybeAlignValue() 4424 .getValueOr(DAG.getEVTAlign(VT.getScalarType())); 4425 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4426 4427 SDValue Base; 4428 SDValue Index; 4429 ISD::MemIndexType IndexType; 4430 SDValue Scale; 4431 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4432 I.getParent()); 4433 4434 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4435 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4436 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4437 // TODO: Make MachineMemOperands aware of scalable 4438 // vectors. 4439 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4440 if (!UniformBase) { 4441 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4442 Index = getValue(Ptr); 4443 IndexType = ISD::SIGNED_UNSCALED; 4444 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4445 } 4446 4447 EVT IdxVT = Index.getValueType(); 4448 EVT EltTy = IdxVT.getVectorElementType(); 4449 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4450 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4451 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4452 } 4453 4454 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4455 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4456 Ops, MMO, IndexType, false); 4457 DAG.setRoot(Scatter); 4458 setValue(&I, Scatter); 4459 } 4460 4461 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4462 SDLoc sdl = getCurSDLoc(); 4463 4464 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4465 MaybeAlign &Alignment) { 4466 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4467 Ptr = I.getArgOperand(0); 4468 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4469 Mask = I.getArgOperand(2); 4470 Src0 = I.getArgOperand(3); 4471 }; 4472 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4473 MaybeAlign &Alignment) { 4474 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4475 Ptr = I.getArgOperand(0); 4476 Alignment = None; 4477 Mask = I.getArgOperand(1); 4478 Src0 = I.getArgOperand(2); 4479 }; 4480 4481 Value *PtrOperand, *MaskOperand, *Src0Operand; 4482 MaybeAlign Alignment; 4483 if (IsExpanding) 4484 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4485 else 4486 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4487 4488 SDValue Ptr = getValue(PtrOperand); 4489 SDValue Src0 = getValue(Src0Operand); 4490 SDValue Mask = getValue(MaskOperand); 4491 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4492 4493 EVT VT = Src0.getValueType(); 4494 if (!Alignment) 4495 Alignment = DAG.getEVTAlign(VT); 4496 4497 AAMDNodes AAInfo = I.getAAMetadata(); 4498 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4499 4500 // Do not serialize masked loads of constant memory with anything. 4501 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4502 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4503 4504 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4505 4506 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4507 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4508 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4509 4510 SDValue Load = 4511 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4512 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4513 if (AddToChain) 4514 PendingLoads.push_back(Load.getValue(1)); 4515 setValue(&I, Load); 4516 } 4517 4518 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4519 SDLoc sdl = getCurSDLoc(); 4520 4521 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4522 const Value *Ptr = I.getArgOperand(0); 4523 SDValue Src0 = getValue(I.getArgOperand(3)); 4524 SDValue Mask = getValue(I.getArgOperand(2)); 4525 4526 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4527 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4528 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4529 ->getMaybeAlignValue() 4530 .getValueOr(DAG.getEVTAlign(VT.getScalarType())); 4531 4532 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4533 4534 SDValue Root = DAG.getRoot(); 4535 SDValue Base; 4536 SDValue Index; 4537 ISD::MemIndexType IndexType; 4538 SDValue Scale; 4539 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4540 I.getParent()); 4541 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4542 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4543 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4544 // TODO: Make MachineMemOperands aware of scalable 4545 // vectors. 4546 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4547 4548 if (!UniformBase) { 4549 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4550 Index = getValue(Ptr); 4551 IndexType = ISD::SIGNED_UNSCALED; 4552 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4553 } 4554 4555 EVT IdxVT = Index.getValueType(); 4556 EVT EltTy = IdxVT.getVectorElementType(); 4557 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4558 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4559 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4560 } 4561 4562 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4563 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4564 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4565 4566 PendingLoads.push_back(Gather.getValue(1)); 4567 setValue(&I, Gather); 4568 } 4569 4570 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4571 SDLoc dl = getCurSDLoc(); 4572 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4573 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4574 SyncScope::ID SSID = I.getSyncScopeID(); 4575 4576 SDValue InChain = getRoot(); 4577 4578 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4579 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4580 4581 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4582 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4583 4584 MachineFunction &MF = DAG.getMachineFunction(); 4585 MachineMemOperand *MMO = MF.getMachineMemOperand( 4586 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4587 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4588 FailureOrdering); 4589 4590 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4591 dl, MemVT, VTs, InChain, 4592 getValue(I.getPointerOperand()), 4593 getValue(I.getCompareOperand()), 4594 getValue(I.getNewValOperand()), MMO); 4595 4596 SDValue OutChain = L.getValue(2); 4597 4598 setValue(&I, L); 4599 DAG.setRoot(OutChain); 4600 } 4601 4602 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4603 SDLoc dl = getCurSDLoc(); 4604 ISD::NodeType NT; 4605 switch (I.getOperation()) { 4606 default: llvm_unreachable("Unknown atomicrmw operation"); 4607 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4608 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4609 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4610 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4611 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4612 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4613 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4614 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4615 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4616 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4617 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4618 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4619 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4620 } 4621 AtomicOrdering Ordering = I.getOrdering(); 4622 SyncScope::ID SSID = I.getSyncScopeID(); 4623 4624 SDValue InChain = getRoot(); 4625 4626 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4627 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4628 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4629 4630 MachineFunction &MF = DAG.getMachineFunction(); 4631 MachineMemOperand *MMO = MF.getMachineMemOperand( 4632 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4633 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4634 4635 SDValue L = 4636 DAG.getAtomic(NT, dl, MemVT, InChain, 4637 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4638 MMO); 4639 4640 SDValue OutChain = L.getValue(1); 4641 4642 setValue(&I, L); 4643 DAG.setRoot(OutChain); 4644 } 4645 4646 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4647 SDLoc dl = getCurSDLoc(); 4648 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4649 SDValue Ops[3]; 4650 Ops[0] = getRoot(); 4651 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4652 TLI.getFenceOperandTy(DAG.getDataLayout())); 4653 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4654 TLI.getFenceOperandTy(DAG.getDataLayout())); 4655 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4656 } 4657 4658 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4659 SDLoc dl = getCurSDLoc(); 4660 AtomicOrdering Order = I.getOrdering(); 4661 SyncScope::ID SSID = I.getSyncScopeID(); 4662 4663 SDValue InChain = getRoot(); 4664 4665 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4666 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4667 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4668 4669 if (!TLI.supportsUnalignedAtomics() && 4670 I.getAlignment() < MemVT.getSizeInBits() / 8) 4671 report_fatal_error("Cannot generate unaligned atomic load"); 4672 4673 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4674 4675 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4676 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4677 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4678 4679 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4680 4681 SDValue Ptr = getValue(I.getPointerOperand()); 4682 4683 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4684 // TODO: Once this is better exercised by tests, it should be merged with 4685 // the normal path for loads to prevent future divergence. 4686 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4687 if (MemVT != VT) 4688 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4689 4690 setValue(&I, L); 4691 SDValue OutChain = L.getValue(1); 4692 if (!I.isUnordered()) 4693 DAG.setRoot(OutChain); 4694 else 4695 PendingLoads.push_back(OutChain); 4696 return; 4697 } 4698 4699 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4700 Ptr, MMO); 4701 4702 SDValue OutChain = L.getValue(1); 4703 if (MemVT != VT) 4704 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4705 4706 setValue(&I, L); 4707 DAG.setRoot(OutChain); 4708 } 4709 4710 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4711 SDLoc dl = getCurSDLoc(); 4712 4713 AtomicOrdering Ordering = I.getOrdering(); 4714 SyncScope::ID SSID = I.getSyncScopeID(); 4715 4716 SDValue InChain = getRoot(); 4717 4718 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4719 EVT MemVT = 4720 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4721 4722 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4723 report_fatal_error("Cannot generate unaligned atomic store"); 4724 4725 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4726 4727 MachineFunction &MF = DAG.getMachineFunction(); 4728 MachineMemOperand *MMO = MF.getMachineMemOperand( 4729 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4730 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4731 4732 SDValue Val = getValue(I.getValueOperand()); 4733 if (Val.getValueType() != MemVT) 4734 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4735 SDValue Ptr = getValue(I.getPointerOperand()); 4736 4737 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4738 // TODO: Once this is better exercised by tests, it should be merged with 4739 // the normal path for stores to prevent future divergence. 4740 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4741 DAG.setRoot(S); 4742 return; 4743 } 4744 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4745 Ptr, Val, MMO); 4746 4747 4748 DAG.setRoot(OutChain); 4749 } 4750 4751 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4752 /// node. 4753 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4754 unsigned Intrinsic) { 4755 // Ignore the callsite's attributes. A specific call site may be marked with 4756 // readnone, but the lowering code will expect the chain based on the 4757 // definition. 4758 const Function *F = I.getCalledFunction(); 4759 bool HasChain = !F->doesNotAccessMemory(); 4760 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4761 4762 // Build the operand list. 4763 SmallVector<SDValue, 8> Ops; 4764 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4765 if (OnlyLoad) { 4766 // We don't need to serialize loads against other loads. 4767 Ops.push_back(DAG.getRoot()); 4768 } else { 4769 Ops.push_back(getRoot()); 4770 } 4771 } 4772 4773 // Info is set by getTgtMemInstrinsic 4774 TargetLowering::IntrinsicInfo Info; 4775 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4776 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4777 DAG.getMachineFunction(), 4778 Intrinsic); 4779 4780 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4781 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4782 Info.opc == ISD::INTRINSIC_W_CHAIN) 4783 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4784 TLI.getPointerTy(DAG.getDataLayout()))); 4785 4786 // Add all operands of the call to the operand list. 4787 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4788 const Value *Arg = I.getArgOperand(i); 4789 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4790 Ops.push_back(getValue(Arg)); 4791 continue; 4792 } 4793 4794 // Use TargetConstant instead of a regular constant for immarg. 4795 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4796 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4797 assert(CI->getBitWidth() <= 64 && 4798 "large intrinsic immediates not handled"); 4799 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4800 } else { 4801 Ops.push_back( 4802 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4803 } 4804 } 4805 4806 SmallVector<EVT, 4> ValueVTs; 4807 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4808 4809 if (HasChain) 4810 ValueVTs.push_back(MVT::Other); 4811 4812 SDVTList VTs = DAG.getVTList(ValueVTs); 4813 4814 // Propagate fast-math-flags from IR to node(s). 4815 SDNodeFlags Flags; 4816 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4817 Flags.copyFMF(*FPMO); 4818 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4819 4820 // Create the node. 4821 SDValue Result; 4822 if (IsTgtIntrinsic) { 4823 // This is target intrinsic that touches memory 4824 Result = 4825 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4826 MachinePointerInfo(Info.ptrVal, Info.offset), 4827 Info.align, Info.flags, Info.size, 4828 I.getAAMetadata()); 4829 } else if (!HasChain) { 4830 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4831 } else if (!I.getType()->isVoidTy()) { 4832 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4833 } else { 4834 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4835 } 4836 4837 if (HasChain) { 4838 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4839 if (OnlyLoad) 4840 PendingLoads.push_back(Chain); 4841 else 4842 DAG.setRoot(Chain); 4843 } 4844 4845 if (!I.getType()->isVoidTy()) { 4846 if (!isa<VectorType>(I.getType())) 4847 Result = lowerRangeToAssertZExt(DAG, I, Result); 4848 4849 MaybeAlign Alignment = I.getRetAlign(); 4850 if (!Alignment) 4851 Alignment = F->getAttributes().getRetAlignment(); 4852 // Insert `assertalign` node if there's an alignment. 4853 if (InsertAssertAlign && Alignment) { 4854 Result = 4855 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4856 } 4857 4858 setValue(&I, Result); 4859 } 4860 } 4861 4862 /// GetSignificand - Get the significand and build it into a floating-point 4863 /// number with exponent of 1: 4864 /// 4865 /// Op = (Op & 0x007fffff) | 0x3f800000; 4866 /// 4867 /// where Op is the hexadecimal representation of floating point value. 4868 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4869 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4870 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4871 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4872 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4873 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4874 } 4875 4876 /// GetExponent - Get the exponent: 4877 /// 4878 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4879 /// 4880 /// where Op is the hexadecimal representation of floating point value. 4881 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4882 const TargetLowering &TLI, const SDLoc &dl) { 4883 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4884 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4885 SDValue t1 = DAG.getNode( 4886 ISD::SRL, dl, MVT::i32, t0, 4887 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4888 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4889 DAG.getConstant(127, dl, MVT::i32)); 4890 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4891 } 4892 4893 /// getF32Constant - Get 32-bit floating point constant. 4894 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4895 const SDLoc &dl) { 4896 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4897 MVT::f32); 4898 } 4899 4900 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4901 SelectionDAG &DAG) { 4902 // TODO: What fast-math-flags should be set on the floating-point nodes? 4903 4904 // IntegerPartOfX = ((int32_t)(t0); 4905 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4906 4907 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4908 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4909 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4910 4911 // IntegerPartOfX <<= 23; 4912 IntegerPartOfX = DAG.getNode( 4913 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4914 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4915 DAG.getDataLayout()))); 4916 4917 SDValue TwoToFractionalPartOfX; 4918 if (LimitFloatPrecision <= 6) { 4919 // For floating-point precision of 6: 4920 // 4921 // TwoToFractionalPartOfX = 4922 // 0.997535578f + 4923 // (0.735607626f + 0.252464424f * x) * x; 4924 // 4925 // error 0.0144103317, which is 6 bits 4926 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4927 getF32Constant(DAG, 0x3e814304, dl)); 4928 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4929 getF32Constant(DAG, 0x3f3c50c8, dl)); 4930 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4931 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4932 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4933 } else if (LimitFloatPrecision <= 12) { 4934 // For floating-point precision of 12: 4935 // 4936 // TwoToFractionalPartOfX = 4937 // 0.999892986f + 4938 // (0.696457318f + 4939 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4940 // 4941 // error 0.000107046256, which is 13 to 14 bits 4942 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4943 getF32Constant(DAG, 0x3da235e3, dl)); 4944 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4945 getF32Constant(DAG, 0x3e65b8f3, dl)); 4946 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4947 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4948 getF32Constant(DAG, 0x3f324b07, dl)); 4949 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4950 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4951 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4952 } else { // LimitFloatPrecision <= 18 4953 // For floating-point precision of 18: 4954 // 4955 // TwoToFractionalPartOfX = 4956 // 0.999999982f + 4957 // (0.693148872f + 4958 // (0.240227044f + 4959 // (0.554906021e-1f + 4960 // (0.961591928e-2f + 4961 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4962 // error 2.47208000*10^(-7), which is better than 18 bits 4963 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4964 getF32Constant(DAG, 0x3924b03e, dl)); 4965 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4966 getF32Constant(DAG, 0x3ab24b87, dl)); 4967 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4968 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4969 getF32Constant(DAG, 0x3c1d8c17, dl)); 4970 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4971 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4972 getF32Constant(DAG, 0x3d634a1d, dl)); 4973 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4974 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4975 getF32Constant(DAG, 0x3e75fe14, dl)); 4976 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4977 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4978 getF32Constant(DAG, 0x3f317234, dl)); 4979 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4980 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4981 getF32Constant(DAG, 0x3f800000, dl)); 4982 } 4983 4984 // Add the exponent into the result in integer domain. 4985 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4986 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4987 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4988 } 4989 4990 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4991 /// limited-precision mode. 4992 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4993 const TargetLowering &TLI, SDNodeFlags Flags) { 4994 if (Op.getValueType() == MVT::f32 && 4995 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4996 4997 // Put the exponent in the right bit position for later addition to the 4998 // final result: 4999 // 5000 // t0 = Op * log2(e) 5001 5002 // TODO: What fast-math-flags should be set here? 5003 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5004 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5005 return getLimitedPrecisionExp2(t0, dl, DAG); 5006 } 5007 5008 // No special expansion. 5009 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5010 } 5011 5012 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5013 /// limited-precision mode. 5014 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5015 const TargetLowering &TLI, SDNodeFlags Flags) { 5016 // TODO: What fast-math-flags should be set on the floating-point nodes? 5017 5018 if (Op.getValueType() == MVT::f32 && 5019 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5020 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5021 5022 // Scale the exponent by log(2). 5023 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5024 SDValue LogOfExponent = 5025 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5026 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5027 5028 // Get the significand and build it into a floating-point number with 5029 // exponent of 1. 5030 SDValue X = GetSignificand(DAG, Op1, dl); 5031 5032 SDValue LogOfMantissa; 5033 if (LimitFloatPrecision <= 6) { 5034 // For floating-point precision of 6: 5035 // 5036 // LogofMantissa = 5037 // -1.1609546f + 5038 // (1.4034025f - 0.23903021f * x) * x; 5039 // 5040 // error 0.0034276066, which is better than 8 bits 5041 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5042 getF32Constant(DAG, 0xbe74c456, dl)); 5043 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5044 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5045 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5046 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5047 getF32Constant(DAG, 0x3f949a29, dl)); 5048 } else if (LimitFloatPrecision <= 12) { 5049 // For floating-point precision of 12: 5050 // 5051 // LogOfMantissa = 5052 // -1.7417939f + 5053 // (2.8212026f + 5054 // (-1.4699568f + 5055 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5056 // 5057 // error 0.000061011436, which is 14 bits 5058 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5059 getF32Constant(DAG, 0xbd67b6d6, dl)); 5060 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5061 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5062 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5063 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5064 getF32Constant(DAG, 0x3fbc278b, dl)); 5065 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5066 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5067 getF32Constant(DAG, 0x40348e95, dl)); 5068 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5069 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5070 getF32Constant(DAG, 0x3fdef31a, dl)); 5071 } else { // LimitFloatPrecision <= 18 5072 // For floating-point precision of 18: 5073 // 5074 // LogOfMantissa = 5075 // -2.1072184f + 5076 // (4.2372794f + 5077 // (-3.7029485f + 5078 // (2.2781945f + 5079 // (-0.87823314f + 5080 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5081 // 5082 // error 0.0000023660568, which is better than 18 bits 5083 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5084 getF32Constant(DAG, 0xbc91e5ac, dl)); 5085 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5086 getF32Constant(DAG, 0x3e4350aa, dl)); 5087 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5088 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5089 getF32Constant(DAG, 0x3f60d3e3, dl)); 5090 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5091 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5092 getF32Constant(DAG, 0x4011cdf0, dl)); 5093 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5094 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5095 getF32Constant(DAG, 0x406cfd1c, dl)); 5096 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5097 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5098 getF32Constant(DAG, 0x408797cb, dl)); 5099 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5100 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5101 getF32Constant(DAG, 0x4006dcab, dl)); 5102 } 5103 5104 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5105 } 5106 5107 // No special expansion. 5108 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5109 } 5110 5111 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5112 /// limited-precision mode. 5113 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5114 const TargetLowering &TLI, SDNodeFlags Flags) { 5115 // TODO: What fast-math-flags should be set on the floating-point nodes? 5116 5117 if (Op.getValueType() == MVT::f32 && 5118 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5119 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5120 5121 // Get the exponent. 5122 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5123 5124 // Get the significand and build it into a floating-point number with 5125 // exponent of 1. 5126 SDValue X = GetSignificand(DAG, Op1, dl); 5127 5128 // Different possible minimax approximations of significand in 5129 // floating-point for various degrees of accuracy over [1,2]. 5130 SDValue Log2ofMantissa; 5131 if (LimitFloatPrecision <= 6) { 5132 // For floating-point precision of 6: 5133 // 5134 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5135 // 5136 // error 0.0049451742, which is more than 7 bits 5137 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5138 getF32Constant(DAG, 0xbeb08fe0, dl)); 5139 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5140 getF32Constant(DAG, 0x40019463, dl)); 5141 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5142 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5143 getF32Constant(DAG, 0x3fd6633d, dl)); 5144 } else if (LimitFloatPrecision <= 12) { 5145 // For floating-point precision of 12: 5146 // 5147 // Log2ofMantissa = 5148 // -2.51285454f + 5149 // (4.07009056f + 5150 // (-2.12067489f + 5151 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5152 // 5153 // error 0.0000876136000, which is better than 13 bits 5154 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5155 getF32Constant(DAG, 0xbda7262e, dl)); 5156 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5157 getF32Constant(DAG, 0x3f25280b, dl)); 5158 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5159 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5160 getF32Constant(DAG, 0x4007b923, dl)); 5161 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5162 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5163 getF32Constant(DAG, 0x40823e2f, dl)); 5164 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5165 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5166 getF32Constant(DAG, 0x4020d29c, dl)); 5167 } else { // LimitFloatPrecision <= 18 5168 // For floating-point precision of 18: 5169 // 5170 // Log2ofMantissa = 5171 // -3.0400495f + 5172 // (6.1129976f + 5173 // (-5.3420409f + 5174 // (3.2865683f + 5175 // (-1.2669343f + 5176 // (0.27515199f - 5177 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5178 // 5179 // error 0.0000018516, which is better than 18 bits 5180 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5181 getF32Constant(DAG, 0xbcd2769e, dl)); 5182 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5183 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5184 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5185 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5186 getF32Constant(DAG, 0x3fa22ae7, dl)); 5187 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5188 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5189 getF32Constant(DAG, 0x40525723, dl)); 5190 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5191 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5192 getF32Constant(DAG, 0x40aaf200, dl)); 5193 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5194 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5195 getF32Constant(DAG, 0x40c39dad, dl)); 5196 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5197 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5198 getF32Constant(DAG, 0x4042902c, dl)); 5199 } 5200 5201 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5202 } 5203 5204 // No special expansion. 5205 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5206 } 5207 5208 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5209 /// limited-precision mode. 5210 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5211 const TargetLowering &TLI, SDNodeFlags Flags) { 5212 // TODO: What fast-math-flags should be set on the floating-point nodes? 5213 5214 if (Op.getValueType() == MVT::f32 && 5215 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5216 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5217 5218 // Scale the exponent by log10(2) [0.30102999f]. 5219 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5220 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5221 getF32Constant(DAG, 0x3e9a209a, dl)); 5222 5223 // Get the significand and build it into a floating-point number with 5224 // exponent of 1. 5225 SDValue X = GetSignificand(DAG, Op1, dl); 5226 5227 SDValue Log10ofMantissa; 5228 if (LimitFloatPrecision <= 6) { 5229 // For floating-point precision of 6: 5230 // 5231 // Log10ofMantissa = 5232 // -0.50419619f + 5233 // (0.60948995f - 0.10380950f * x) * x; 5234 // 5235 // error 0.0014886165, which is 6 bits 5236 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5237 getF32Constant(DAG, 0xbdd49a13, dl)); 5238 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5239 getF32Constant(DAG, 0x3f1c0789, dl)); 5240 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5241 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5242 getF32Constant(DAG, 0x3f011300, dl)); 5243 } else if (LimitFloatPrecision <= 12) { 5244 // For floating-point precision of 12: 5245 // 5246 // Log10ofMantissa = 5247 // -0.64831180f + 5248 // (0.91751397f + 5249 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5250 // 5251 // error 0.00019228036, which is better than 12 bits 5252 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5253 getF32Constant(DAG, 0x3d431f31, dl)); 5254 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5255 getF32Constant(DAG, 0x3ea21fb2, dl)); 5256 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5257 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5258 getF32Constant(DAG, 0x3f6ae232, dl)); 5259 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5260 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5261 getF32Constant(DAG, 0x3f25f7c3, dl)); 5262 } else { // LimitFloatPrecision <= 18 5263 // For floating-point precision of 18: 5264 // 5265 // Log10ofMantissa = 5266 // -0.84299375f + 5267 // (1.5327582f + 5268 // (-1.0688956f + 5269 // (0.49102474f + 5270 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5271 // 5272 // error 0.0000037995730, which is better than 18 bits 5273 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5274 getF32Constant(DAG, 0x3c5d51ce, dl)); 5275 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5276 getF32Constant(DAG, 0x3e00685a, dl)); 5277 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5278 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5279 getF32Constant(DAG, 0x3efb6798, dl)); 5280 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5281 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5282 getF32Constant(DAG, 0x3f88d192, dl)); 5283 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5284 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5285 getF32Constant(DAG, 0x3fc4316c, dl)); 5286 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5287 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5288 getF32Constant(DAG, 0x3f57ce70, dl)); 5289 } 5290 5291 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5292 } 5293 5294 // No special expansion. 5295 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5296 } 5297 5298 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5299 /// limited-precision mode. 5300 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5301 const TargetLowering &TLI, SDNodeFlags Flags) { 5302 if (Op.getValueType() == MVT::f32 && 5303 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5304 return getLimitedPrecisionExp2(Op, dl, DAG); 5305 5306 // No special expansion. 5307 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5308 } 5309 5310 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5311 /// limited-precision mode with x == 10.0f. 5312 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5313 SelectionDAG &DAG, const TargetLowering &TLI, 5314 SDNodeFlags Flags) { 5315 bool IsExp10 = false; 5316 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5317 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5318 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5319 APFloat Ten(10.0f); 5320 IsExp10 = LHSC->isExactlyValue(Ten); 5321 } 5322 } 5323 5324 // TODO: What fast-math-flags should be set on the FMUL node? 5325 if (IsExp10) { 5326 // Put the exponent in the right bit position for later addition to the 5327 // final result: 5328 // 5329 // #define LOG2OF10 3.3219281f 5330 // t0 = Op * LOG2OF10; 5331 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5332 getF32Constant(DAG, 0x40549a78, dl)); 5333 return getLimitedPrecisionExp2(t0, dl, DAG); 5334 } 5335 5336 // No special expansion. 5337 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5338 } 5339 5340 /// ExpandPowI - Expand a llvm.powi intrinsic. 5341 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5342 SelectionDAG &DAG) { 5343 // If RHS is a constant, we can expand this out to a multiplication tree, 5344 // otherwise we end up lowering to a call to __powidf2 (for example). When 5345 // optimizing for size, we only want to do this if the expansion would produce 5346 // a small number of multiplies, otherwise we do the full expansion. 5347 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5348 // Get the exponent as a positive value. 5349 unsigned Val = RHSC->getSExtValue(); 5350 if ((int)Val < 0) Val = -Val; 5351 5352 // powi(x, 0) -> 1.0 5353 if (Val == 0) 5354 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5355 5356 bool OptForSize = DAG.shouldOptForSize(); 5357 if (!OptForSize || 5358 // If optimizing for size, don't insert too many multiplies. 5359 // This inserts up to 5 multiplies. 5360 countPopulation(Val) + Log2_32(Val) < 7) { 5361 // We use the simple binary decomposition method to generate the multiply 5362 // sequence. There are more optimal ways to do this (for example, 5363 // powi(x,15) generates one more multiply than it should), but this has 5364 // the benefit of being both really simple and much better than a libcall. 5365 SDValue Res; // Logically starts equal to 1.0 5366 SDValue CurSquare = LHS; 5367 // TODO: Intrinsics should have fast-math-flags that propagate to these 5368 // nodes. 5369 while (Val) { 5370 if (Val & 1) { 5371 if (Res.getNode()) 5372 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5373 else 5374 Res = CurSquare; // 1.0*CurSquare. 5375 } 5376 5377 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5378 CurSquare, CurSquare); 5379 Val >>= 1; 5380 } 5381 5382 // If the original was negative, invert the result, producing 1/(x*x*x). 5383 if (RHSC->getSExtValue() < 0) 5384 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5385 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5386 return Res; 5387 } 5388 } 5389 5390 // Otherwise, expand to a libcall. 5391 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5392 } 5393 5394 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5395 SDValue LHS, SDValue RHS, SDValue Scale, 5396 SelectionDAG &DAG, const TargetLowering &TLI) { 5397 EVT VT = LHS.getValueType(); 5398 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5399 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5400 LLVMContext &Ctx = *DAG.getContext(); 5401 5402 // If the type is legal but the operation isn't, this node might survive all 5403 // the way to operation legalization. If we end up there and we do not have 5404 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5405 // node. 5406 5407 // Coax the legalizer into expanding the node during type legalization instead 5408 // by bumping the size by one bit. This will force it to Promote, enabling the 5409 // early expansion and avoiding the need to expand later. 5410 5411 // We don't have to do this if Scale is 0; that can always be expanded, unless 5412 // it's a saturating signed operation. Those can experience true integer 5413 // division overflow, a case which we must avoid. 5414 5415 // FIXME: We wouldn't have to do this (or any of the early 5416 // expansion/promotion) if it was possible to expand a libcall of an 5417 // illegal type during operation legalization. But it's not, so things 5418 // get a bit hacky. 5419 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5420 if ((ScaleInt > 0 || (Saturating && Signed)) && 5421 (TLI.isTypeLegal(VT) || 5422 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5423 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5424 Opcode, VT, ScaleInt); 5425 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5426 EVT PromVT; 5427 if (VT.isScalarInteger()) 5428 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5429 else if (VT.isVector()) { 5430 PromVT = VT.getVectorElementType(); 5431 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5432 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5433 } else 5434 llvm_unreachable("Wrong VT for DIVFIX?"); 5435 if (Signed) { 5436 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5437 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5438 } else { 5439 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5440 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5441 } 5442 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5443 // For saturating operations, we need to shift up the LHS to get the 5444 // proper saturation width, and then shift down again afterwards. 5445 if (Saturating) 5446 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5447 DAG.getConstant(1, DL, ShiftTy)); 5448 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5449 if (Saturating) 5450 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5451 DAG.getConstant(1, DL, ShiftTy)); 5452 return DAG.getZExtOrTrunc(Res, DL, VT); 5453 } 5454 } 5455 5456 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5457 } 5458 5459 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5460 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5461 static void 5462 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5463 const SDValue &N) { 5464 switch (N.getOpcode()) { 5465 case ISD::CopyFromReg: { 5466 SDValue Op = N.getOperand(1); 5467 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5468 Op.getValueType().getSizeInBits()); 5469 return; 5470 } 5471 case ISD::BITCAST: 5472 case ISD::AssertZext: 5473 case ISD::AssertSext: 5474 case ISD::TRUNCATE: 5475 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5476 return; 5477 case ISD::BUILD_PAIR: 5478 case ISD::BUILD_VECTOR: 5479 case ISD::CONCAT_VECTORS: 5480 for (SDValue Op : N->op_values()) 5481 getUnderlyingArgRegs(Regs, Op); 5482 return; 5483 default: 5484 return; 5485 } 5486 } 5487 5488 /// If the DbgValueInst is a dbg_value of a function argument, create the 5489 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5490 /// instruction selection, they will be inserted to the entry BB. 5491 /// We don't currently support this for variadic dbg_values, as they shouldn't 5492 /// appear for function arguments or in the prologue. 5493 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5494 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5495 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5496 const Argument *Arg = dyn_cast<Argument>(V); 5497 if (!Arg) 5498 return false; 5499 5500 MachineFunction &MF = DAG.getMachineFunction(); 5501 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5502 5503 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5504 // we've been asked to pursue. 5505 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5506 bool Indirect) { 5507 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5508 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5509 // pointing at the VReg, which will be patched up later. 5510 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5511 auto MIB = BuildMI(MF, DL, Inst); 5512 MIB.addReg(Reg); 5513 MIB.addImm(0); 5514 MIB.addMetadata(Variable); 5515 auto *NewDIExpr = FragExpr; 5516 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5517 // the DIExpression. 5518 if (Indirect) 5519 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5520 MIB.addMetadata(NewDIExpr); 5521 return MIB; 5522 } else { 5523 // Create a completely standard DBG_VALUE. 5524 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5525 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5526 } 5527 }; 5528 5529 if (!IsDbgDeclare) { 5530 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5531 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5532 // the entry block. 5533 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5534 if (!IsInEntryBlock) 5535 return false; 5536 5537 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5538 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5539 // variable that also is a param. 5540 // 5541 // Although, if we are at the top of the entry block already, we can still 5542 // emit using ArgDbgValue. This might catch some situations when the 5543 // dbg.value refers to an argument that isn't used in the entry block, so 5544 // any CopyToReg node would be optimized out and the only way to express 5545 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5546 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5547 // we should only emit as ArgDbgValue if the Variable is an argument to the 5548 // current function, and the dbg.value intrinsic is found in the entry 5549 // block. 5550 bool VariableIsFunctionInputArg = Variable->isParameter() && 5551 !DL->getInlinedAt(); 5552 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5553 if (!IsInPrologue && !VariableIsFunctionInputArg) 5554 return false; 5555 5556 // Here we assume that a function argument on IR level only can be used to 5557 // describe one input parameter on source level. If we for example have 5558 // source code like this 5559 // 5560 // struct A { long x, y; }; 5561 // void foo(struct A a, long b) { 5562 // ... 5563 // b = a.x; 5564 // ... 5565 // } 5566 // 5567 // and IR like this 5568 // 5569 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5570 // entry: 5571 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5572 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5573 // call void @llvm.dbg.value(metadata i32 %b, "b", 5574 // ... 5575 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5576 // ... 5577 // 5578 // then the last dbg.value is describing a parameter "b" using a value that 5579 // is an argument. But since we already has used %a1 to describe a parameter 5580 // we should not handle that last dbg.value here (that would result in an 5581 // incorrect hoisting of the DBG_VALUE to the function entry). 5582 // Notice that we allow one dbg.value per IR level argument, to accommodate 5583 // for the situation with fragments above. 5584 if (VariableIsFunctionInputArg) { 5585 unsigned ArgNo = Arg->getArgNo(); 5586 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5587 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5588 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5589 return false; 5590 FuncInfo.DescribedArgs.set(ArgNo); 5591 } 5592 } 5593 5594 bool IsIndirect = false; 5595 Optional<MachineOperand> Op; 5596 // Some arguments' frame index is recorded during argument lowering. 5597 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5598 if (FI != std::numeric_limits<int>::max()) 5599 Op = MachineOperand::CreateFI(FI); 5600 5601 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5602 if (!Op && N.getNode()) { 5603 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5604 Register Reg; 5605 if (ArgRegsAndSizes.size() == 1) 5606 Reg = ArgRegsAndSizes.front().first; 5607 5608 if (Reg && Reg.isVirtual()) { 5609 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5610 Register PR = RegInfo.getLiveInPhysReg(Reg); 5611 if (PR) 5612 Reg = PR; 5613 } 5614 if (Reg) { 5615 Op = MachineOperand::CreateReg(Reg, false); 5616 IsIndirect = IsDbgDeclare; 5617 } 5618 } 5619 5620 if (!Op && N.getNode()) { 5621 // Check if frame index is available. 5622 SDValue LCandidate = peekThroughBitcasts(N); 5623 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5624 if (FrameIndexSDNode *FINode = 5625 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5626 Op = MachineOperand::CreateFI(FINode->getIndex()); 5627 } 5628 5629 if (!Op) { 5630 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5631 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5632 SplitRegs) { 5633 unsigned Offset = 0; 5634 for (const auto &RegAndSize : SplitRegs) { 5635 // If the expression is already a fragment, the current register 5636 // offset+size might extend beyond the fragment. In this case, only 5637 // the register bits that are inside the fragment are relevant. 5638 int RegFragmentSizeInBits = RegAndSize.second; 5639 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5640 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5641 // The register is entirely outside the expression fragment, 5642 // so is irrelevant for debug info. 5643 if (Offset >= ExprFragmentSizeInBits) 5644 break; 5645 // The register is partially outside the expression fragment, only 5646 // the low bits within the fragment are relevant for debug info. 5647 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5648 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5649 } 5650 } 5651 5652 auto FragmentExpr = DIExpression::createFragmentExpression( 5653 Expr, Offset, RegFragmentSizeInBits); 5654 Offset += RegAndSize.second; 5655 // If a valid fragment expression cannot be created, the variable's 5656 // correct value cannot be determined and so it is set as Undef. 5657 if (!FragmentExpr) { 5658 SDDbgValue *SDV = DAG.getConstantDbgValue( 5659 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5660 DAG.AddDbgValue(SDV, false); 5661 continue; 5662 } 5663 MachineInstr *NewMI = 5664 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare); 5665 FuncInfo.ArgDbgValues.push_back(NewMI); 5666 } 5667 }; 5668 5669 // Check if ValueMap has reg number. 5670 DenseMap<const Value *, Register>::const_iterator 5671 VMI = FuncInfo.ValueMap.find(V); 5672 if (VMI != FuncInfo.ValueMap.end()) { 5673 const auto &TLI = DAG.getTargetLoweringInfo(); 5674 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5675 V->getType(), None); 5676 if (RFV.occupiesMultipleRegs()) { 5677 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5678 return true; 5679 } 5680 5681 Op = MachineOperand::CreateReg(VMI->second, false); 5682 IsIndirect = IsDbgDeclare; 5683 } else if (ArgRegsAndSizes.size() > 1) { 5684 // This was split due to the calling convention, and no virtual register 5685 // mapping exists for the value. 5686 splitMultiRegDbgValue(ArgRegsAndSizes); 5687 return true; 5688 } 5689 } 5690 5691 if (!Op) 5692 return false; 5693 5694 assert(Variable->isValidLocationForIntrinsic(DL) && 5695 "Expected inlined-at fields to agree"); 5696 MachineInstr *NewMI = nullptr; 5697 5698 if (Op->isReg()) 5699 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5700 else 5701 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5702 Variable, Expr); 5703 5704 FuncInfo.ArgDbgValues.push_back(NewMI); 5705 return true; 5706 } 5707 5708 /// Return the appropriate SDDbgValue based on N. 5709 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5710 DILocalVariable *Variable, 5711 DIExpression *Expr, 5712 const DebugLoc &dl, 5713 unsigned DbgSDNodeOrder) { 5714 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5715 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5716 // stack slot locations. 5717 // 5718 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5719 // debug values here after optimization: 5720 // 5721 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5722 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5723 // 5724 // Both describe the direct values of their associated variables. 5725 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5726 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5727 } 5728 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5729 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5730 } 5731 5732 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5733 switch (Intrinsic) { 5734 case Intrinsic::smul_fix: 5735 return ISD::SMULFIX; 5736 case Intrinsic::umul_fix: 5737 return ISD::UMULFIX; 5738 case Intrinsic::smul_fix_sat: 5739 return ISD::SMULFIXSAT; 5740 case Intrinsic::umul_fix_sat: 5741 return ISD::UMULFIXSAT; 5742 case Intrinsic::sdiv_fix: 5743 return ISD::SDIVFIX; 5744 case Intrinsic::udiv_fix: 5745 return ISD::UDIVFIX; 5746 case Intrinsic::sdiv_fix_sat: 5747 return ISD::SDIVFIXSAT; 5748 case Intrinsic::udiv_fix_sat: 5749 return ISD::UDIVFIXSAT; 5750 default: 5751 llvm_unreachable("Unhandled fixed point intrinsic"); 5752 } 5753 } 5754 5755 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5756 const char *FunctionName) { 5757 assert(FunctionName && "FunctionName must not be nullptr"); 5758 SDValue Callee = DAG.getExternalSymbol( 5759 FunctionName, 5760 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5761 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5762 } 5763 5764 /// Given a @llvm.call.preallocated.setup, return the corresponding 5765 /// preallocated call. 5766 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5767 assert(cast<CallBase>(PreallocatedSetup) 5768 ->getCalledFunction() 5769 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5770 "expected call_preallocated_setup Value"); 5771 for (auto *U : PreallocatedSetup->users()) { 5772 auto *UseCall = cast<CallBase>(U); 5773 const Function *Fn = UseCall->getCalledFunction(); 5774 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5775 return UseCall; 5776 } 5777 } 5778 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5779 } 5780 5781 /// Lower the call to the specified intrinsic function. 5782 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5783 unsigned Intrinsic) { 5784 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5785 SDLoc sdl = getCurSDLoc(); 5786 DebugLoc dl = getCurDebugLoc(); 5787 SDValue Res; 5788 5789 SDNodeFlags Flags; 5790 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5791 Flags.copyFMF(*FPOp); 5792 5793 switch (Intrinsic) { 5794 default: 5795 // By default, turn this into a target intrinsic node. 5796 visitTargetIntrinsic(I, Intrinsic); 5797 return; 5798 case Intrinsic::vscale: { 5799 match(&I, m_VScale(DAG.getDataLayout())); 5800 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5801 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5802 return; 5803 } 5804 case Intrinsic::vastart: visitVAStart(I); return; 5805 case Intrinsic::vaend: visitVAEnd(I); return; 5806 case Intrinsic::vacopy: visitVACopy(I); return; 5807 case Intrinsic::returnaddress: 5808 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5809 TLI.getPointerTy(DAG.getDataLayout()), 5810 getValue(I.getArgOperand(0)))); 5811 return; 5812 case Intrinsic::addressofreturnaddress: 5813 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5814 TLI.getPointerTy(DAG.getDataLayout()))); 5815 return; 5816 case Intrinsic::sponentry: 5817 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5818 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5819 return; 5820 case Intrinsic::frameaddress: 5821 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5822 TLI.getFrameIndexTy(DAG.getDataLayout()), 5823 getValue(I.getArgOperand(0)))); 5824 return; 5825 case Intrinsic::read_volatile_register: 5826 case Intrinsic::read_register: { 5827 Value *Reg = I.getArgOperand(0); 5828 SDValue Chain = getRoot(); 5829 SDValue RegName = 5830 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5831 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5832 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5833 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5834 setValue(&I, Res); 5835 DAG.setRoot(Res.getValue(1)); 5836 return; 5837 } 5838 case Intrinsic::write_register: { 5839 Value *Reg = I.getArgOperand(0); 5840 Value *RegValue = I.getArgOperand(1); 5841 SDValue Chain = getRoot(); 5842 SDValue RegName = 5843 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5844 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5845 RegName, getValue(RegValue))); 5846 return; 5847 } 5848 case Intrinsic::memcpy: { 5849 const auto &MCI = cast<MemCpyInst>(I); 5850 SDValue Op1 = getValue(I.getArgOperand(0)); 5851 SDValue Op2 = getValue(I.getArgOperand(1)); 5852 SDValue Op3 = getValue(I.getArgOperand(2)); 5853 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5854 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5855 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5856 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5857 bool isVol = MCI.isVolatile(); 5858 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5859 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5860 // node. 5861 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5862 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5863 /* AlwaysInline */ false, isTC, 5864 MachinePointerInfo(I.getArgOperand(0)), 5865 MachinePointerInfo(I.getArgOperand(1)), 5866 I.getAAMetadata()); 5867 updateDAGForMaybeTailCall(MC); 5868 return; 5869 } 5870 case Intrinsic::memcpy_inline: { 5871 const auto &MCI = cast<MemCpyInlineInst>(I); 5872 SDValue Dst = getValue(I.getArgOperand(0)); 5873 SDValue Src = getValue(I.getArgOperand(1)); 5874 SDValue Size = getValue(I.getArgOperand(2)); 5875 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5876 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5877 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5878 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5879 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5880 bool isVol = MCI.isVolatile(); 5881 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5882 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5883 // node. 5884 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5885 /* AlwaysInline */ true, isTC, 5886 MachinePointerInfo(I.getArgOperand(0)), 5887 MachinePointerInfo(I.getArgOperand(1)), 5888 I.getAAMetadata()); 5889 updateDAGForMaybeTailCall(MC); 5890 return; 5891 } 5892 case Intrinsic::memset: { 5893 const auto &MSI = cast<MemSetInst>(I); 5894 SDValue Op1 = getValue(I.getArgOperand(0)); 5895 SDValue Op2 = getValue(I.getArgOperand(1)); 5896 SDValue Op3 = getValue(I.getArgOperand(2)); 5897 // @llvm.memset defines 0 and 1 to both mean no alignment. 5898 Align Alignment = MSI.getDestAlign().valueOrOne(); 5899 bool isVol = MSI.isVolatile(); 5900 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5901 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5902 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5903 MachinePointerInfo(I.getArgOperand(0)), 5904 I.getAAMetadata()); 5905 updateDAGForMaybeTailCall(MS); 5906 return; 5907 } 5908 case Intrinsic::memmove: { 5909 const auto &MMI = cast<MemMoveInst>(I); 5910 SDValue Op1 = getValue(I.getArgOperand(0)); 5911 SDValue Op2 = getValue(I.getArgOperand(1)); 5912 SDValue Op3 = getValue(I.getArgOperand(2)); 5913 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5914 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5915 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5916 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5917 bool isVol = MMI.isVolatile(); 5918 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5919 // FIXME: Support passing different dest/src alignments to the memmove DAG 5920 // node. 5921 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5922 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5923 isTC, MachinePointerInfo(I.getArgOperand(0)), 5924 MachinePointerInfo(I.getArgOperand(1)), 5925 I.getAAMetadata()); 5926 updateDAGForMaybeTailCall(MM); 5927 return; 5928 } 5929 case Intrinsic::memcpy_element_unordered_atomic: { 5930 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5931 SDValue Dst = getValue(MI.getRawDest()); 5932 SDValue Src = getValue(MI.getRawSource()); 5933 SDValue Length = getValue(MI.getLength()); 5934 5935 unsigned DstAlign = MI.getDestAlignment(); 5936 unsigned SrcAlign = MI.getSourceAlignment(); 5937 Type *LengthTy = MI.getLength()->getType(); 5938 unsigned ElemSz = MI.getElementSizeInBytes(); 5939 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5940 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5941 SrcAlign, Length, LengthTy, ElemSz, isTC, 5942 MachinePointerInfo(MI.getRawDest()), 5943 MachinePointerInfo(MI.getRawSource())); 5944 updateDAGForMaybeTailCall(MC); 5945 return; 5946 } 5947 case Intrinsic::memmove_element_unordered_atomic: { 5948 auto &MI = cast<AtomicMemMoveInst>(I); 5949 SDValue Dst = getValue(MI.getRawDest()); 5950 SDValue Src = getValue(MI.getRawSource()); 5951 SDValue Length = getValue(MI.getLength()); 5952 5953 unsigned DstAlign = MI.getDestAlignment(); 5954 unsigned SrcAlign = MI.getSourceAlignment(); 5955 Type *LengthTy = MI.getLength()->getType(); 5956 unsigned ElemSz = MI.getElementSizeInBytes(); 5957 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5958 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5959 SrcAlign, Length, LengthTy, ElemSz, isTC, 5960 MachinePointerInfo(MI.getRawDest()), 5961 MachinePointerInfo(MI.getRawSource())); 5962 updateDAGForMaybeTailCall(MC); 5963 return; 5964 } 5965 case Intrinsic::memset_element_unordered_atomic: { 5966 auto &MI = cast<AtomicMemSetInst>(I); 5967 SDValue Dst = getValue(MI.getRawDest()); 5968 SDValue Val = getValue(MI.getValue()); 5969 SDValue Length = getValue(MI.getLength()); 5970 5971 unsigned DstAlign = MI.getDestAlignment(); 5972 Type *LengthTy = MI.getLength()->getType(); 5973 unsigned ElemSz = MI.getElementSizeInBytes(); 5974 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5975 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5976 LengthTy, ElemSz, isTC, 5977 MachinePointerInfo(MI.getRawDest())); 5978 updateDAGForMaybeTailCall(MC); 5979 return; 5980 } 5981 case Intrinsic::call_preallocated_setup: { 5982 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5983 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5984 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5985 getRoot(), SrcValue); 5986 setValue(&I, Res); 5987 DAG.setRoot(Res); 5988 return; 5989 } 5990 case Intrinsic::call_preallocated_arg: { 5991 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5992 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5993 SDValue Ops[3]; 5994 Ops[0] = getRoot(); 5995 Ops[1] = SrcValue; 5996 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5997 MVT::i32); // arg index 5998 SDValue Res = DAG.getNode( 5999 ISD::PREALLOCATED_ARG, sdl, 6000 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6001 setValue(&I, Res); 6002 DAG.setRoot(Res.getValue(1)); 6003 return; 6004 } 6005 case Intrinsic::dbg_addr: 6006 case Intrinsic::dbg_declare: { 6007 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6008 // they are non-variadic. 6009 const auto &DI = cast<DbgVariableIntrinsic>(I); 6010 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6011 DILocalVariable *Variable = DI.getVariable(); 6012 DIExpression *Expression = DI.getExpression(); 6013 dropDanglingDebugInfo(Variable, Expression); 6014 assert(Variable && "Missing variable"); 6015 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6016 << "\n"); 6017 // Check if address has undef value. 6018 const Value *Address = DI.getVariableLocationOp(0); 6019 if (!Address || isa<UndefValue>(Address) || 6020 (Address->use_empty() && !isa<Argument>(Address))) { 6021 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6022 << " (bad/undef/unused-arg address)\n"); 6023 return; 6024 } 6025 6026 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6027 6028 // Check if this variable can be described by a frame index, typically 6029 // either as a static alloca or a byval parameter. 6030 int FI = std::numeric_limits<int>::max(); 6031 if (const auto *AI = 6032 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6033 if (AI->isStaticAlloca()) { 6034 auto I = FuncInfo.StaticAllocaMap.find(AI); 6035 if (I != FuncInfo.StaticAllocaMap.end()) 6036 FI = I->second; 6037 } 6038 } else if (const auto *Arg = dyn_cast<Argument>( 6039 Address->stripInBoundsConstantOffsets())) { 6040 FI = FuncInfo.getArgumentFrameIndex(Arg); 6041 } 6042 6043 // llvm.dbg.addr is control dependent and always generates indirect 6044 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6045 // the MachineFunction variable table. 6046 if (FI != std::numeric_limits<int>::max()) { 6047 if (Intrinsic == Intrinsic::dbg_addr) { 6048 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6049 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6050 dl, SDNodeOrder); 6051 DAG.AddDbgValue(SDV, isParameter); 6052 } else { 6053 LLVM_DEBUG(dbgs() << "Skipping " << DI 6054 << " (variable info stashed in MF side table)\n"); 6055 } 6056 return; 6057 } 6058 6059 SDValue &N = NodeMap[Address]; 6060 if (!N.getNode() && isa<Argument>(Address)) 6061 // Check unused arguments map. 6062 N = UnusedArgNodeMap[Address]; 6063 SDDbgValue *SDV; 6064 if (N.getNode()) { 6065 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6066 Address = BCI->getOperand(0); 6067 // Parameters are handled specially. 6068 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6069 if (isParameter && FINode) { 6070 // Byval parameter. We have a frame index at this point. 6071 SDV = 6072 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6073 /*IsIndirect*/ true, dl, SDNodeOrder); 6074 } else if (isa<Argument>(Address)) { 6075 // Address is an argument, so try to emit its dbg value using 6076 // virtual register info from the FuncInfo.ValueMap. 6077 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6078 return; 6079 } else { 6080 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6081 true, dl, SDNodeOrder); 6082 } 6083 DAG.AddDbgValue(SDV, isParameter); 6084 } else { 6085 // If Address is an argument then try to emit its dbg value using 6086 // virtual register info from the FuncInfo.ValueMap. 6087 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6088 N)) { 6089 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6090 << " (could not emit func-arg dbg_value)\n"); 6091 } 6092 } 6093 return; 6094 } 6095 case Intrinsic::dbg_label: { 6096 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6097 DILabel *Label = DI.getLabel(); 6098 assert(Label && "Missing label"); 6099 6100 SDDbgLabel *SDV; 6101 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6102 DAG.AddDbgLabel(SDV); 6103 return; 6104 } 6105 case Intrinsic::dbg_value: { 6106 const DbgValueInst &DI = cast<DbgValueInst>(I); 6107 assert(DI.getVariable() && "Missing variable"); 6108 6109 DILocalVariable *Variable = DI.getVariable(); 6110 DIExpression *Expression = DI.getExpression(); 6111 dropDanglingDebugInfo(Variable, Expression); 6112 SmallVector<Value *, 4> Values(DI.getValues()); 6113 if (Values.empty()) 6114 return; 6115 6116 if (llvm::is_contained(Values, nullptr)) 6117 return; 6118 6119 bool IsVariadic = DI.hasArgList(); 6120 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6121 SDNodeOrder, IsVariadic)) 6122 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6123 return; 6124 } 6125 6126 case Intrinsic::eh_typeid_for: { 6127 // Find the type id for the given typeinfo. 6128 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6129 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6130 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6131 setValue(&I, Res); 6132 return; 6133 } 6134 6135 case Intrinsic::eh_return_i32: 6136 case Intrinsic::eh_return_i64: 6137 DAG.getMachineFunction().setCallsEHReturn(true); 6138 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6139 MVT::Other, 6140 getControlRoot(), 6141 getValue(I.getArgOperand(0)), 6142 getValue(I.getArgOperand(1)))); 6143 return; 6144 case Intrinsic::eh_unwind_init: 6145 DAG.getMachineFunction().setCallsUnwindInit(true); 6146 return; 6147 case Intrinsic::eh_dwarf_cfa: 6148 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6149 TLI.getPointerTy(DAG.getDataLayout()), 6150 getValue(I.getArgOperand(0)))); 6151 return; 6152 case Intrinsic::eh_sjlj_callsite: { 6153 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6154 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6155 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6156 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6157 6158 MMI.setCurrentCallSite(CI->getZExtValue()); 6159 return; 6160 } 6161 case Intrinsic::eh_sjlj_functioncontext: { 6162 // Get and store the index of the function context. 6163 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6164 AllocaInst *FnCtx = 6165 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6166 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6167 MFI.setFunctionContextIndex(FI); 6168 return; 6169 } 6170 case Intrinsic::eh_sjlj_setjmp: { 6171 SDValue Ops[2]; 6172 Ops[0] = getRoot(); 6173 Ops[1] = getValue(I.getArgOperand(0)); 6174 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6175 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6176 setValue(&I, Op.getValue(0)); 6177 DAG.setRoot(Op.getValue(1)); 6178 return; 6179 } 6180 case Intrinsic::eh_sjlj_longjmp: 6181 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6182 getRoot(), getValue(I.getArgOperand(0)))); 6183 return; 6184 case Intrinsic::eh_sjlj_setup_dispatch: 6185 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6186 getRoot())); 6187 return; 6188 case Intrinsic::masked_gather: 6189 visitMaskedGather(I); 6190 return; 6191 case Intrinsic::masked_load: 6192 visitMaskedLoad(I); 6193 return; 6194 case Intrinsic::masked_scatter: 6195 visitMaskedScatter(I); 6196 return; 6197 case Intrinsic::masked_store: 6198 visitMaskedStore(I); 6199 return; 6200 case Intrinsic::masked_expandload: 6201 visitMaskedLoad(I, true /* IsExpanding */); 6202 return; 6203 case Intrinsic::masked_compressstore: 6204 visitMaskedStore(I, true /* IsCompressing */); 6205 return; 6206 case Intrinsic::powi: 6207 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6208 getValue(I.getArgOperand(1)), DAG)); 6209 return; 6210 case Intrinsic::log: 6211 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6212 return; 6213 case Intrinsic::log2: 6214 setValue(&I, 6215 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6216 return; 6217 case Intrinsic::log10: 6218 setValue(&I, 6219 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6220 return; 6221 case Intrinsic::exp: 6222 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6223 return; 6224 case Intrinsic::exp2: 6225 setValue(&I, 6226 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6227 return; 6228 case Intrinsic::pow: 6229 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6230 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6231 return; 6232 case Intrinsic::sqrt: 6233 case Intrinsic::fabs: 6234 case Intrinsic::sin: 6235 case Intrinsic::cos: 6236 case Intrinsic::floor: 6237 case Intrinsic::ceil: 6238 case Intrinsic::trunc: 6239 case Intrinsic::rint: 6240 case Intrinsic::nearbyint: 6241 case Intrinsic::round: 6242 case Intrinsic::roundeven: 6243 case Intrinsic::canonicalize: { 6244 unsigned Opcode; 6245 switch (Intrinsic) { 6246 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6247 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6248 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6249 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6250 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6251 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6252 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6253 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6254 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6255 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6256 case Intrinsic::round: Opcode = ISD::FROUND; break; 6257 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6258 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6259 } 6260 6261 setValue(&I, DAG.getNode(Opcode, sdl, 6262 getValue(I.getArgOperand(0)).getValueType(), 6263 getValue(I.getArgOperand(0)), Flags)); 6264 return; 6265 } 6266 case Intrinsic::lround: 6267 case Intrinsic::llround: 6268 case Intrinsic::lrint: 6269 case Intrinsic::llrint: { 6270 unsigned Opcode; 6271 switch (Intrinsic) { 6272 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6273 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6274 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6275 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6276 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6277 } 6278 6279 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6280 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6281 getValue(I.getArgOperand(0)))); 6282 return; 6283 } 6284 case Intrinsic::minnum: 6285 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6286 getValue(I.getArgOperand(0)).getValueType(), 6287 getValue(I.getArgOperand(0)), 6288 getValue(I.getArgOperand(1)), Flags)); 6289 return; 6290 case Intrinsic::maxnum: 6291 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6292 getValue(I.getArgOperand(0)).getValueType(), 6293 getValue(I.getArgOperand(0)), 6294 getValue(I.getArgOperand(1)), Flags)); 6295 return; 6296 case Intrinsic::minimum: 6297 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6298 getValue(I.getArgOperand(0)).getValueType(), 6299 getValue(I.getArgOperand(0)), 6300 getValue(I.getArgOperand(1)), Flags)); 6301 return; 6302 case Intrinsic::maximum: 6303 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6304 getValue(I.getArgOperand(0)).getValueType(), 6305 getValue(I.getArgOperand(0)), 6306 getValue(I.getArgOperand(1)), Flags)); 6307 return; 6308 case Intrinsic::copysign: 6309 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6310 getValue(I.getArgOperand(0)).getValueType(), 6311 getValue(I.getArgOperand(0)), 6312 getValue(I.getArgOperand(1)), Flags)); 6313 return; 6314 case Intrinsic::arithmetic_fence: { 6315 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6316 getValue(I.getArgOperand(0)).getValueType(), 6317 getValue(I.getArgOperand(0)), Flags)); 6318 return; 6319 } 6320 case Intrinsic::fma: 6321 setValue(&I, DAG.getNode( 6322 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6323 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6324 getValue(I.getArgOperand(2)), Flags)); 6325 return; 6326 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6327 case Intrinsic::INTRINSIC: 6328 #include "llvm/IR/ConstrainedOps.def" 6329 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6330 return; 6331 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6332 #include "llvm/IR/VPIntrinsics.def" 6333 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6334 return; 6335 case Intrinsic::fptrunc_round: { 6336 // Get the last argument, the metadata and convert it to an integer in the 6337 // call 6338 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6339 Optional<RoundingMode> RoundMode = 6340 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6341 6342 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6343 6344 // Propagate fast-math-flags from IR to node(s). 6345 SDNodeFlags Flags; 6346 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6347 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6348 6349 SDValue Result; 6350 Result = DAG.getNode( 6351 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6352 DAG.getTargetConstant((int)RoundMode.getValue(), sdl, 6353 TLI.getPointerTy(DAG.getDataLayout()))); 6354 setValue(&I, Result); 6355 6356 return; 6357 } 6358 case Intrinsic::fmuladd: { 6359 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6360 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6361 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6362 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6363 getValue(I.getArgOperand(0)).getValueType(), 6364 getValue(I.getArgOperand(0)), 6365 getValue(I.getArgOperand(1)), 6366 getValue(I.getArgOperand(2)), Flags)); 6367 } else { 6368 // TODO: Intrinsic calls should have fast-math-flags. 6369 SDValue Mul = DAG.getNode( 6370 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6371 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6372 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6373 getValue(I.getArgOperand(0)).getValueType(), 6374 Mul, getValue(I.getArgOperand(2)), Flags); 6375 setValue(&I, Add); 6376 } 6377 return; 6378 } 6379 case Intrinsic::convert_to_fp16: 6380 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6381 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6382 getValue(I.getArgOperand(0)), 6383 DAG.getTargetConstant(0, sdl, 6384 MVT::i32)))); 6385 return; 6386 case Intrinsic::convert_from_fp16: 6387 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6388 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6389 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6390 getValue(I.getArgOperand(0))))); 6391 return; 6392 case Intrinsic::fptosi_sat: { 6393 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6394 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6395 getValue(I.getArgOperand(0)), 6396 DAG.getValueType(VT.getScalarType()))); 6397 return; 6398 } 6399 case Intrinsic::fptoui_sat: { 6400 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6401 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6402 getValue(I.getArgOperand(0)), 6403 DAG.getValueType(VT.getScalarType()))); 6404 return; 6405 } 6406 case Intrinsic::set_rounding: 6407 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6408 {getRoot(), getValue(I.getArgOperand(0))}); 6409 setValue(&I, Res); 6410 DAG.setRoot(Res.getValue(0)); 6411 return; 6412 case Intrinsic::pcmarker: { 6413 SDValue Tmp = getValue(I.getArgOperand(0)); 6414 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6415 return; 6416 } 6417 case Intrinsic::readcyclecounter: { 6418 SDValue Op = getRoot(); 6419 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6420 DAG.getVTList(MVT::i64, MVT::Other), Op); 6421 setValue(&I, Res); 6422 DAG.setRoot(Res.getValue(1)); 6423 return; 6424 } 6425 case Intrinsic::bitreverse: 6426 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6427 getValue(I.getArgOperand(0)).getValueType(), 6428 getValue(I.getArgOperand(0)))); 6429 return; 6430 case Intrinsic::bswap: 6431 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6432 getValue(I.getArgOperand(0)).getValueType(), 6433 getValue(I.getArgOperand(0)))); 6434 return; 6435 case Intrinsic::cttz: { 6436 SDValue Arg = getValue(I.getArgOperand(0)); 6437 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6438 EVT Ty = Arg.getValueType(); 6439 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6440 sdl, Ty, Arg)); 6441 return; 6442 } 6443 case Intrinsic::ctlz: { 6444 SDValue Arg = getValue(I.getArgOperand(0)); 6445 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6446 EVT Ty = Arg.getValueType(); 6447 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6448 sdl, Ty, Arg)); 6449 return; 6450 } 6451 case Intrinsic::ctpop: { 6452 SDValue Arg = getValue(I.getArgOperand(0)); 6453 EVT Ty = Arg.getValueType(); 6454 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6455 return; 6456 } 6457 case Intrinsic::fshl: 6458 case Intrinsic::fshr: { 6459 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6460 SDValue X = getValue(I.getArgOperand(0)); 6461 SDValue Y = getValue(I.getArgOperand(1)); 6462 SDValue Z = getValue(I.getArgOperand(2)); 6463 EVT VT = X.getValueType(); 6464 6465 if (X == Y) { 6466 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6467 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6468 } else { 6469 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6470 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6471 } 6472 return; 6473 } 6474 case Intrinsic::sadd_sat: { 6475 SDValue Op1 = getValue(I.getArgOperand(0)); 6476 SDValue Op2 = getValue(I.getArgOperand(1)); 6477 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6478 return; 6479 } 6480 case Intrinsic::uadd_sat: { 6481 SDValue Op1 = getValue(I.getArgOperand(0)); 6482 SDValue Op2 = getValue(I.getArgOperand(1)); 6483 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6484 return; 6485 } 6486 case Intrinsic::ssub_sat: { 6487 SDValue Op1 = getValue(I.getArgOperand(0)); 6488 SDValue Op2 = getValue(I.getArgOperand(1)); 6489 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6490 return; 6491 } 6492 case Intrinsic::usub_sat: { 6493 SDValue Op1 = getValue(I.getArgOperand(0)); 6494 SDValue Op2 = getValue(I.getArgOperand(1)); 6495 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6496 return; 6497 } 6498 case Intrinsic::sshl_sat: { 6499 SDValue Op1 = getValue(I.getArgOperand(0)); 6500 SDValue Op2 = getValue(I.getArgOperand(1)); 6501 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6502 return; 6503 } 6504 case Intrinsic::ushl_sat: { 6505 SDValue Op1 = getValue(I.getArgOperand(0)); 6506 SDValue Op2 = getValue(I.getArgOperand(1)); 6507 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6508 return; 6509 } 6510 case Intrinsic::smul_fix: 6511 case Intrinsic::umul_fix: 6512 case Intrinsic::smul_fix_sat: 6513 case Intrinsic::umul_fix_sat: { 6514 SDValue Op1 = getValue(I.getArgOperand(0)); 6515 SDValue Op2 = getValue(I.getArgOperand(1)); 6516 SDValue Op3 = getValue(I.getArgOperand(2)); 6517 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6518 Op1.getValueType(), Op1, Op2, Op3)); 6519 return; 6520 } 6521 case Intrinsic::sdiv_fix: 6522 case Intrinsic::udiv_fix: 6523 case Intrinsic::sdiv_fix_sat: 6524 case Intrinsic::udiv_fix_sat: { 6525 SDValue Op1 = getValue(I.getArgOperand(0)); 6526 SDValue Op2 = getValue(I.getArgOperand(1)); 6527 SDValue Op3 = getValue(I.getArgOperand(2)); 6528 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6529 Op1, Op2, Op3, DAG, TLI)); 6530 return; 6531 } 6532 case Intrinsic::smax: { 6533 SDValue Op1 = getValue(I.getArgOperand(0)); 6534 SDValue Op2 = getValue(I.getArgOperand(1)); 6535 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6536 return; 6537 } 6538 case Intrinsic::smin: { 6539 SDValue Op1 = getValue(I.getArgOperand(0)); 6540 SDValue Op2 = getValue(I.getArgOperand(1)); 6541 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6542 return; 6543 } 6544 case Intrinsic::umax: { 6545 SDValue Op1 = getValue(I.getArgOperand(0)); 6546 SDValue Op2 = getValue(I.getArgOperand(1)); 6547 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6548 return; 6549 } 6550 case Intrinsic::umin: { 6551 SDValue Op1 = getValue(I.getArgOperand(0)); 6552 SDValue Op2 = getValue(I.getArgOperand(1)); 6553 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6554 return; 6555 } 6556 case Intrinsic::abs: { 6557 // TODO: Preserve "int min is poison" arg in SDAG? 6558 SDValue Op1 = getValue(I.getArgOperand(0)); 6559 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6560 return; 6561 } 6562 case Intrinsic::stacksave: { 6563 SDValue Op = getRoot(); 6564 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6565 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6566 setValue(&I, Res); 6567 DAG.setRoot(Res.getValue(1)); 6568 return; 6569 } 6570 case Intrinsic::stackrestore: 6571 Res = getValue(I.getArgOperand(0)); 6572 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6573 return; 6574 case Intrinsic::get_dynamic_area_offset: { 6575 SDValue Op = getRoot(); 6576 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6577 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6578 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6579 // target. 6580 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6581 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6582 " intrinsic!"); 6583 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6584 Op); 6585 DAG.setRoot(Op); 6586 setValue(&I, Res); 6587 return; 6588 } 6589 case Intrinsic::stackguard: { 6590 MachineFunction &MF = DAG.getMachineFunction(); 6591 const Module &M = *MF.getFunction().getParent(); 6592 SDValue Chain = getRoot(); 6593 if (TLI.useLoadStackGuardNode()) { 6594 Res = getLoadStackGuard(DAG, sdl, Chain); 6595 } else { 6596 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6597 const Value *Global = TLI.getSDagStackGuard(M); 6598 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6599 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6600 MachinePointerInfo(Global, 0), Align, 6601 MachineMemOperand::MOVolatile); 6602 } 6603 if (TLI.useStackGuardXorFP()) 6604 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6605 DAG.setRoot(Chain); 6606 setValue(&I, Res); 6607 return; 6608 } 6609 case Intrinsic::stackprotector: { 6610 // Emit code into the DAG to store the stack guard onto the stack. 6611 MachineFunction &MF = DAG.getMachineFunction(); 6612 MachineFrameInfo &MFI = MF.getFrameInfo(); 6613 SDValue Src, Chain = getRoot(); 6614 6615 if (TLI.useLoadStackGuardNode()) 6616 Src = getLoadStackGuard(DAG, sdl, Chain); 6617 else 6618 Src = getValue(I.getArgOperand(0)); // The guard's value. 6619 6620 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6621 6622 int FI = FuncInfo.StaticAllocaMap[Slot]; 6623 MFI.setStackProtectorIndex(FI); 6624 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6625 6626 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6627 6628 // Store the stack protector onto the stack. 6629 Res = DAG.getStore( 6630 Chain, sdl, Src, FIN, 6631 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6632 MaybeAlign(), MachineMemOperand::MOVolatile); 6633 setValue(&I, Res); 6634 DAG.setRoot(Res); 6635 return; 6636 } 6637 case Intrinsic::objectsize: 6638 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6639 6640 case Intrinsic::is_constant: 6641 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6642 6643 case Intrinsic::annotation: 6644 case Intrinsic::ptr_annotation: 6645 case Intrinsic::launder_invariant_group: 6646 case Intrinsic::strip_invariant_group: 6647 // Drop the intrinsic, but forward the value 6648 setValue(&I, getValue(I.getOperand(0))); 6649 return; 6650 6651 case Intrinsic::assume: 6652 case Intrinsic::experimental_noalias_scope_decl: 6653 case Intrinsic::var_annotation: 6654 case Intrinsic::sideeffect: 6655 // Discard annotate attributes, noalias scope declarations, assumptions, and 6656 // artificial side-effects. 6657 return; 6658 6659 case Intrinsic::codeview_annotation: { 6660 // Emit a label associated with this metadata. 6661 MachineFunction &MF = DAG.getMachineFunction(); 6662 MCSymbol *Label = 6663 MF.getMMI().getContext().createTempSymbol("annotation", true); 6664 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6665 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6666 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6667 DAG.setRoot(Res); 6668 return; 6669 } 6670 6671 case Intrinsic::init_trampoline: { 6672 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6673 6674 SDValue Ops[6]; 6675 Ops[0] = getRoot(); 6676 Ops[1] = getValue(I.getArgOperand(0)); 6677 Ops[2] = getValue(I.getArgOperand(1)); 6678 Ops[3] = getValue(I.getArgOperand(2)); 6679 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6680 Ops[5] = DAG.getSrcValue(F); 6681 6682 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6683 6684 DAG.setRoot(Res); 6685 return; 6686 } 6687 case Intrinsic::adjust_trampoline: 6688 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6689 TLI.getPointerTy(DAG.getDataLayout()), 6690 getValue(I.getArgOperand(0)))); 6691 return; 6692 case Intrinsic::gcroot: { 6693 assert(DAG.getMachineFunction().getFunction().hasGC() && 6694 "only valid in functions with gc specified, enforced by Verifier"); 6695 assert(GFI && "implied by previous"); 6696 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6697 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6698 6699 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6700 GFI->addStackRoot(FI->getIndex(), TypeMap); 6701 return; 6702 } 6703 case Intrinsic::gcread: 6704 case Intrinsic::gcwrite: 6705 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6706 case Intrinsic::flt_rounds: 6707 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6708 setValue(&I, Res); 6709 DAG.setRoot(Res.getValue(1)); 6710 return; 6711 6712 case Intrinsic::expect: 6713 // Just replace __builtin_expect(exp, c) with EXP. 6714 setValue(&I, getValue(I.getArgOperand(0))); 6715 return; 6716 6717 case Intrinsic::ubsantrap: 6718 case Intrinsic::debugtrap: 6719 case Intrinsic::trap: { 6720 StringRef TrapFuncName = 6721 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6722 if (TrapFuncName.empty()) { 6723 switch (Intrinsic) { 6724 case Intrinsic::trap: 6725 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6726 break; 6727 case Intrinsic::debugtrap: 6728 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6729 break; 6730 case Intrinsic::ubsantrap: 6731 DAG.setRoot(DAG.getNode( 6732 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6733 DAG.getTargetConstant( 6734 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6735 MVT::i32))); 6736 break; 6737 default: llvm_unreachable("unknown trap intrinsic"); 6738 } 6739 return; 6740 } 6741 TargetLowering::ArgListTy Args; 6742 if (Intrinsic == Intrinsic::ubsantrap) { 6743 Args.push_back(TargetLoweringBase::ArgListEntry()); 6744 Args[0].Val = I.getArgOperand(0); 6745 Args[0].Node = getValue(Args[0].Val); 6746 Args[0].Ty = Args[0].Val->getType(); 6747 } 6748 6749 TargetLowering::CallLoweringInfo CLI(DAG); 6750 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6751 CallingConv::C, I.getType(), 6752 DAG.getExternalSymbol(TrapFuncName.data(), 6753 TLI.getPointerTy(DAG.getDataLayout())), 6754 std::move(Args)); 6755 6756 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6757 DAG.setRoot(Result.second); 6758 return; 6759 } 6760 6761 case Intrinsic::uadd_with_overflow: 6762 case Intrinsic::sadd_with_overflow: 6763 case Intrinsic::usub_with_overflow: 6764 case Intrinsic::ssub_with_overflow: 6765 case Intrinsic::umul_with_overflow: 6766 case Intrinsic::smul_with_overflow: { 6767 ISD::NodeType Op; 6768 switch (Intrinsic) { 6769 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6770 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6771 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6772 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6773 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6774 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6775 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6776 } 6777 SDValue Op1 = getValue(I.getArgOperand(0)); 6778 SDValue Op2 = getValue(I.getArgOperand(1)); 6779 6780 EVT ResultVT = Op1.getValueType(); 6781 EVT OverflowVT = MVT::i1; 6782 if (ResultVT.isVector()) 6783 OverflowVT = EVT::getVectorVT( 6784 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6785 6786 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6787 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6788 return; 6789 } 6790 case Intrinsic::prefetch: { 6791 SDValue Ops[5]; 6792 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6793 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6794 Ops[0] = DAG.getRoot(); 6795 Ops[1] = getValue(I.getArgOperand(0)); 6796 Ops[2] = getValue(I.getArgOperand(1)); 6797 Ops[3] = getValue(I.getArgOperand(2)); 6798 Ops[4] = getValue(I.getArgOperand(3)); 6799 SDValue Result = DAG.getMemIntrinsicNode( 6800 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6801 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6802 /* align */ None, Flags); 6803 6804 // Chain the prefetch in parallell with any pending loads, to stay out of 6805 // the way of later optimizations. 6806 PendingLoads.push_back(Result); 6807 Result = getRoot(); 6808 DAG.setRoot(Result); 6809 return; 6810 } 6811 case Intrinsic::lifetime_start: 6812 case Intrinsic::lifetime_end: { 6813 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6814 // Stack coloring is not enabled in O0, discard region information. 6815 if (TM.getOptLevel() == CodeGenOpt::None) 6816 return; 6817 6818 const int64_t ObjectSize = 6819 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6820 Value *const ObjectPtr = I.getArgOperand(1); 6821 SmallVector<const Value *, 4> Allocas; 6822 getUnderlyingObjects(ObjectPtr, Allocas); 6823 6824 for (const Value *Alloca : Allocas) { 6825 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6826 6827 // Could not find an Alloca. 6828 if (!LifetimeObject) 6829 continue; 6830 6831 // First check that the Alloca is static, otherwise it won't have a 6832 // valid frame index. 6833 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6834 if (SI == FuncInfo.StaticAllocaMap.end()) 6835 return; 6836 6837 const int FrameIndex = SI->second; 6838 int64_t Offset; 6839 if (GetPointerBaseWithConstantOffset( 6840 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6841 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6842 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6843 Offset); 6844 DAG.setRoot(Res); 6845 } 6846 return; 6847 } 6848 case Intrinsic::pseudoprobe: { 6849 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6850 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6851 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6852 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6853 DAG.setRoot(Res); 6854 return; 6855 } 6856 case Intrinsic::invariant_start: 6857 // Discard region information. 6858 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6859 return; 6860 case Intrinsic::invariant_end: 6861 // Discard region information. 6862 return; 6863 case Intrinsic::clear_cache: 6864 /// FunctionName may be null. 6865 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6866 lowerCallToExternalSymbol(I, FunctionName); 6867 return; 6868 case Intrinsic::donothing: 6869 case Intrinsic::seh_try_begin: 6870 case Intrinsic::seh_scope_begin: 6871 case Intrinsic::seh_try_end: 6872 case Intrinsic::seh_scope_end: 6873 // ignore 6874 return; 6875 case Intrinsic::experimental_stackmap: 6876 visitStackmap(I); 6877 return; 6878 case Intrinsic::experimental_patchpoint_void: 6879 case Intrinsic::experimental_patchpoint_i64: 6880 visitPatchpoint(I); 6881 return; 6882 case Intrinsic::experimental_gc_statepoint: 6883 LowerStatepoint(cast<GCStatepointInst>(I)); 6884 return; 6885 case Intrinsic::experimental_gc_result: 6886 visitGCResult(cast<GCResultInst>(I)); 6887 return; 6888 case Intrinsic::experimental_gc_relocate: 6889 visitGCRelocate(cast<GCRelocateInst>(I)); 6890 return; 6891 case Intrinsic::instrprof_cover: 6892 llvm_unreachable("instrprof failed to lower a cover"); 6893 case Intrinsic::instrprof_increment: 6894 llvm_unreachable("instrprof failed to lower an increment"); 6895 case Intrinsic::instrprof_value_profile: 6896 llvm_unreachable("instrprof failed to lower a value profiling call"); 6897 case Intrinsic::localescape: { 6898 MachineFunction &MF = DAG.getMachineFunction(); 6899 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6900 6901 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6902 // is the same on all targets. 6903 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 6904 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6905 if (isa<ConstantPointerNull>(Arg)) 6906 continue; // Skip null pointers. They represent a hole in index space. 6907 AllocaInst *Slot = cast<AllocaInst>(Arg); 6908 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6909 "can only escape static allocas"); 6910 int FI = FuncInfo.StaticAllocaMap[Slot]; 6911 MCSymbol *FrameAllocSym = 6912 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6913 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6914 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6915 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6916 .addSym(FrameAllocSym) 6917 .addFrameIndex(FI); 6918 } 6919 6920 return; 6921 } 6922 6923 case Intrinsic::localrecover: { 6924 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6925 MachineFunction &MF = DAG.getMachineFunction(); 6926 6927 // Get the symbol that defines the frame offset. 6928 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6929 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6930 unsigned IdxVal = 6931 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6932 MCSymbol *FrameAllocSym = 6933 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6934 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6935 6936 Value *FP = I.getArgOperand(1); 6937 SDValue FPVal = getValue(FP); 6938 EVT PtrVT = FPVal.getValueType(); 6939 6940 // Create a MCSymbol for the label to avoid any target lowering 6941 // that would make this PC relative. 6942 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6943 SDValue OffsetVal = 6944 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6945 6946 // Add the offset to the FP. 6947 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6948 setValue(&I, Add); 6949 6950 return; 6951 } 6952 6953 case Intrinsic::eh_exceptionpointer: 6954 case Intrinsic::eh_exceptioncode: { 6955 // Get the exception pointer vreg, copy from it, and resize it to fit. 6956 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6957 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6958 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6959 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6960 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 6961 if (Intrinsic == Intrinsic::eh_exceptioncode) 6962 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 6963 setValue(&I, N); 6964 return; 6965 } 6966 case Intrinsic::xray_customevent: { 6967 // Here we want to make sure that the intrinsic behaves as if it has a 6968 // specific calling convention, and only for x86_64. 6969 // FIXME: Support other platforms later. 6970 const auto &Triple = DAG.getTarget().getTargetTriple(); 6971 if (Triple.getArch() != Triple::x86_64) 6972 return; 6973 6974 SmallVector<SDValue, 8> Ops; 6975 6976 // We want to say that we always want the arguments in registers. 6977 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6978 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6979 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6980 SDValue Chain = getRoot(); 6981 Ops.push_back(LogEntryVal); 6982 Ops.push_back(StrSizeVal); 6983 Ops.push_back(Chain); 6984 6985 // We need to enforce the calling convention for the callsite, so that 6986 // argument ordering is enforced correctly, and that register allocation can 6987 // see that some registers may be assumed clobbered and have to preserve 6988 // them across calls to the intrinsic. 6989 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6990 sdl, NodeTys, Ops); 6991 SDValue patchableNode = SDValue(MN, 0); 6992 DAG.setRoot(patchableNode); 6993 setValue(&I, patchableNode); 6994 return; 6995 } 6996 case Intrinsic::xray_typedevent: { 6997 // Here we want to make sure that the intrinsic behaves as if it has a 6998 // specific calling convention, and only for x86_64. 6999 // FIXME: Support other platforms later. 7000 const auto &Triple = DAG.getTarget().getTargetTriple(); 7001 if (Triple.getArch() != Triple::x86_64) 7002 return; 7003 7004 SmallVector<SDValue, 8> Ops; 7005 7006 // We want to say that we always want the arguments in registers. 7007 // It's unclear to me how manipulating the selection DAG here forces callers 7008 // to provide arguments in registers instead of on the stack. 7009 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7010 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7011 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7012 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7013 SDValue Chain = getRoot(); 7014 Ops.push_back(LogTypeId); 7015 Ops.push_back(LogEntryVal); 7016 Ops.push_back(StrSizeVal); 7017 Ops.push_back(Chain); 7018 7019 // We need to enforce the calling convention for the callsite, so that 7020 // argument ordering is enforced correctly, and that register allocation can 7021 // see that some registers may be assumed clobbered and have to preserve 7022 // them across calls to the intrinsic. 7023 MachineSDNode *MN = DAG.getMachineNode( 7024 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7025 SDValue patchableNode = SDValue(MN, 0); 7026 DAG.setRoot(patchableNode); 7027 setValue(&I, patchableNode); 7028 return; 7029 } 7030 case Intrinsic::experimental_deoptimize: 7031 LowerDeoptimizeCall(&I); 7032 return; 7033 case Intrinsic::experimental_stepvector: 7034 visitStepVector(I); 7035 return; 7036 case Intrinsic::vector_reduce_fadd: 7037 case Intrinsic::vector_reduce_fmul: 7038 case Intrinsic::vector_reduce_add: 7039 case Intrinsic::vector_reduce_mul: 7040 case Intrinsic::vector_reduce_and: 7041 case Intrinsic::vector_reduce_or: 7042 case Intrinsic::vector_reduce_xor: 7043 case Intrinsic::vector_reduce_smax: 7044 case Intrinsic::vector_reduce_smin: 7045 case Intrinsic::vector_reduce_umax: 7046 case Intrinsic::vector_reduce_umin: 7047 case Intrinsic::vector_reduce_fmax: 7048 case Intrinsic::vector_reduce_fmin: 7049 visitVectorReduce(I, Intrinsic); 7050 return; 7051 7052 case Intrinsic::icall_branch_funnel: { 7053 SmallVector<SDValue, 16> Ops; 7054 Ops.push_back(getValue(I.getArgOperand(0))); 7055 7056 int64_t Offset; 7057 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7058 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7059 if (!Base) 7060 report_fatal_error( 7061 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7062 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7063 7064 struct BranchFunnelTarget { 7065 int64_t Offset; 7066 SDValue Target; 7067 }; 7068 SmallVector<BranchFunnelTarget, 8> Targets; 7069 7070 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7071 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7072 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7073 if (ElemBase != Base) 7074 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7075 "to the same GlobalValue"); 7076 7077 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7078 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7079 if (!GA) 7080 report_fatal_error( 7081 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7082 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7083 GA->getGlobal(), sdl, Val.getValueType(), 7084 GA->getOffset())}); 7085 } 7086 llvm::sort(Targets, 7087 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7088 return T1.Offset < T2.Offset; 7089 }); 7090 7091 for (auto &T : Targets) { 7092 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7093 Ops.push_back(T.Target); 7094 } 7095 7096 Ops.push_back(DAG.getRoot()); // Chain 7097 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7098 MVT::Other, Ops), 7099 0); 7100 DAG.setRoot(N); 7101 setValue(&I, N); 7102 HasTailCall = true; 7103 return; 7104 } 7105 7106 case Intrinsic::wasm_landingpad_index: 7107 // Information this intrinsic contained has been transferred to 7108 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7109 // delete it now. 7110 return; 7111 7112 case Intrinsic::aarch64_settag: 7113 case Intrinsic::aarch64_settag_zero: { 7114 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7115 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7116 SDValue Val = TSI.EmitTargetCodeForSetTag( 7117 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7118 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7119 ZeroMemory); 7120 DAG.setRoot(Val); 7121 setValue(&I, Val); 7122 return; 7123 } 7124 case Intrinsic::ptrmask: { 7125 SDValue Ptr = getValue(I.getOperand(0)); 7126 SDValue Const = getValue(I.getOperand(1)); 7127 7128 EVT PtrVT = Ptr.getValueType(); 7129 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7130 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7131 return; 7132 } 7133 case Intrinsic::get_active_lane_mask: { 7134 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7135 SDValue Index = getValue(I.getOperand(0)); 7136 EVT ElementVT = Index.getValueType(); 7137 7138 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7139 visitTargetIntrinsic(I, Intrinsic); 7140 return; 7141 } 7142 7143 SDValue TripCount = getValue(I.getOperand(1)); 7144 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7145 7146 SDValue VectorIndex, VectorTripCount; 7147 if (VecTy.isScalableVector()) { 7148 VectorIndex = DAG.getSplatVector(VecTy, sdl, Index); 7149 VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount); 7150 } else { 7151 VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index); 7152 VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount); 7153 } 7154 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7155 SDValue VectorInduction = DAG.getNode( 7156 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7157 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7158 VectorTripCount, ISD::CondCode::SETULT); 7159 setValue(&I, SetCC); 7160 return; 7161 } 7162 case Intrinsic::experimental_vector_insert: { 7163 SDValue Vec = getValue(I.getOperand(0)); 7164 SDValue SubVec = getValue(I.getOperand(1)); 7165 SDValue Index = getValue(I.getOperand(2)); 7166 7167 // The intrinsic's index type is i64, but the SDNode requires an index type 7168 // suitable for the target. Convert the index as required. 7169 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7170 if (Index.getValueType() != VectorIdxTy) 7171 Index = DAG.getVectorIdxConstant( 7172 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7173 7174 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7175 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7176 Index)); 7177 return; 7178 } 7179 case Intrinsic::experimental_vector_extract: { 7180 SDValue Vec = getValue(I.getOperand(0)); 7181 SDValue Index = getValue(I.getOperand(1)); 7182 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7183 7184 // The intrinsic's index type is i64, but the SDNode requires an index type 7185 // suitable for the target. Convert the index as required. 7186 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7187 if (Index.getValueType() != VectorIdxTy) 7188 Index = DAG.getVectorIdxConstant( 7189 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7190 7191 setValue(&I, 7192 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7193 return; 7194 } 7195 case Intrinsic::experimental_vector_reverse: 7196 visitVectorReverse(I); 7197 return; 7198 case Intrinsic::experimental_vector_splice: 7199 visitVectorSplice(I); 7200 return; 7201 } 7202 } 7203 7204 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7205 const ConstrainedFPIntrinsic &FPI) { 7206 SDLoc sdl = getCurSDLoc(); 7207 7208 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7209 SmallVector<EVT, 4> ValueVTs; 7210 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7211 ValueVTs.push_back(MVT::Other); // Out chain 7212 7213 // We do not need to serialize constrained FP intrinsics against 7214 // each other or against (nonvolatile) loads, so they can be 7215 // chained like loads. 7216 SDValue Chain = DAG.getRoot(); 7217 SmallVector<SDValue, 4> Opers; 7218 Opers.push_back(Chain); 7219 if (FPI.isUnaryOp()) { 7220 Opers.push_back(getValue(FPI.getArgOperand(0))); 7221 } else if (FPI.isTernaryOp()) { 7222 Opers.push_back(getValue(FPI.getArgOperand(0))); 7223 Opers.push_back(getValue(FPI.getArgOperand(1))); 7224 Opers.push_back(getValue(FPI.getArgOperand(2))); 7225 } else { 7226 Opers.push_back(getValue(FPI.getArgOperand(0))); 7227 Opers.push_back(getValue(FPI.getArgOperand(1))); 7228 } 7229 7230 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7231 assert(Result.getNode()->getNumValues() == 2); 7232 7233 // Push node to the appropriate list so that future instructions can be 7234 // chained up correctly. 7235 SDValue OutChain = Result.getValue(1); 7236 switch (EB) { 7237 case fp::ExceptionBehavior::ebIgnore: 7238 // The only reason why ebIgnore nodes still need to be chained is that 7239 // they might depend on the current rounding mode, and therefore must 7240 // not be moved across instruction that may change that mode. 7241 LLVM_FALLTHROUGH; 7242 case fp::ExceptionBehavior::ebMayTrap: 7243 // These must not be moved across calls or instructions that may change 7244 // floating-point exception masks. 7245 PendingConstrainedFP.push_back(OutChain); 7246 break; 7247 case fp::ExceptionBehavior::ebStrict: 7248 // These must not be moved across calls or instructions that may change 7249 // floating-point exception masks or read floating-point exception flags. 7250 // In addition, they cannot be optimized out even if unused. 7251 PendingConstrainedFPStrict.push_back(OutChain); 7252 break; 7253 } 7254 }; 7255 7256 SDVTList VTs = DAG.getVTList(ValueVTs); 7257 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7258 7259 SDNodeFlags Flags; 7260 if (EB == fp::ExceptionBehavior::ebIgnore) 7261 Flags.setNoFPExcept(true); 7262 7263 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7264 Flags.copyFMF(*FPOp); 7265 7266 unsigned Opcode; 7267 switch (FPI.getIntrinsicID()) { 7268 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7269 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7270 case Intrinsic::INTRINSIC: \ 7271 Opcode = ISD::STRICT_##DAGN; \ 7272 break; 7273 #include "llvm/IR/ConstrainedOps.def" 7274 case Intrinsic::experimental_constrained_fmuladd: { 7275 Opcode = ISD::STRICT_FMA; 7276 // Break fmuladd into fmul and fadd. 7277 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7278 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7279 ValueVTs[0])) { 7280 Opers.pop_back(); 7281 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7282 pushOutChain(Mul, EB); 7283 Opcode = ISD::STRICT_FADD; 7284 Opers.clear(); 7285 Opers.push_back(Mul.getValue(1)); 7286 Opers.push_back(Mul.getValue(0)); 7287 Opers.push_back(getValue(FPI.getArgOperand(2))); 7288 } 7289 break; 7290 } 7291 } 7292 7293 // A few strict DAG nodes carry additional operands that are not 7294 // set up by the default code above. 7295 switch (Opcode) { 7296 default: break; 7297 case ISD::STRICT_FP_ROUND: 7298 Opers.push_back( 7299 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7300 break; 7301 case ISD::STRICT_FSETCC: 7302 case ISD::STRICT_FSETCCS: { 7303 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7304 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7305 if (TM.Options.NoNaNsFPMath) 7306 Condition = getFCmpCodeWithoutNaN(Condition); 7307 Opers.push_back(DAG.getCondCode(Condition)); 7308 break; 7309 } 7310 } 7311 7312 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7313 pushOutChain(Result, EB); 7314 7315 SDValue FPResult = Result.getValue(0); 7316 setValue(&FPI, FPResult); 7317 } 7318 7319 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7320 Optional<unsigned> ResOPC; 7321 switch (VPIntrin.getIntrinsicID()) { 7322 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 7323 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) ResOPC = ISD::VPSD; 7324 #define END_REGISTER_VP_INTRINSIC(VPID) break; 7325 #include "llvm/IR/VPIntrinsics.def" 7326 } 7327 7328 if (!ResOPC.hasValue()) 7329 llvm_unreachable( 7330 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7331 7332 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7333 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7334 if (VPIntrin.getFastMathFlags().allowReassoc()) 7335 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7336 : ISD::VP_REDUCE_FMUL; 7337 } 7338 7339 return ResOPC.getValue(); 7340 } 7341 7342 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT, 7343 SmallVector<SDValue, 7> &OpValues, 7344 bool IsGather) { 7345 SDLoc DL = getCurSDLoc(); 7346 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7347 Value *PtrOperand = VPIntrin.getArgOperand(0); 7348 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7349 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7350 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7351 SDValue LD; 7352 bool AddToChain = true; 7353 if (!IsGather) { 7354 // Do not serialize variable-length loads of constant memory with 7355 // anything. 7356 if (!Alignment) 7357 Alignment = DAG.getEVTAlign(VT); 7358 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7359 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7360 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7361 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7362 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7363 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7364 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7365 MMO, false /*IsExpanding */); 7366 } else { 7367 if (!Alignment) 7368 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7369 unsigned AS = 7370 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7371 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7372 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7373 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7374 SDValue Base, Index, Scale; 7375 ISD::MemIndexType IndexType; 7376 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7377 this, VPIntrin.getParent()); 7378 if (!UniformBase) { 7379 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7380 Index = getValue(PtrOperand); 7381 IndexType = ISD::SIGNED_UNSCALED; 7382 Scale = 7383 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7384 } 7385 EVT IdxVT = Index.getValueType(); 7386 EVT EltTy = IdxVT.getVectorElementType(); 7387 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7388 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7389 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7390 } 7391 LD = DAG.getGatherVP( 7392 DAG.getVTList(VT, MVT::Other), VT, DL, 7393 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7394 IndexType); 7395 } 7396 if (AddToChain) 7397 PendingLoads.push_back(LD.getValue(1)); 7398 setValue(&VPIntrin, LD); 7399 } 7400 7401 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin, 7402 SmallVector<SDValue, 7> &OpValues, 7403 bool IsScatter) { 7404 SDLoc DL = getCurSDLoc(); 7405 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7406 Value *PtrOperand = VPIntrin.getArgOperand(1); 7407 EVT VT = OpValues[0].getValueType(); 7408 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7409 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7410 SDValue ST; 7411 if (!IsScatter) { 7412 if (!Alignment) 7413 Alignment = DAG.getEVTAlign(VT); 7414 SDValue Ptr = OpValues[1]; 7415 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7416 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7417 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7418 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7419 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7420 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7421 /* IsTruncating */ false, /*IsCompressing*/ false); 7422 } else { 7423 if (!Alignment) 7424 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7425 unsigned AS = 7426 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7427 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7428 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7429 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7430 SDValue Base, Index, Scale; 7431 ISD::MemIndexType IndexType; 7432 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7433 this, VPIntrin.getParent()); 7434 if (!UniformBase) { 7435 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7436 Index = getValue(PtrOperand); 7437 IndexType = ISD::SIGNED_UNSCALED; 7438 Scale = 7439 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7440 } 7441 EVT IdxVT = Index.getValueType(); 7442 EVT EltTy = IdxVT.getVectorElementType(); 7443 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7444 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7445 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7446 } 7447 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7448 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7449 OpValues[2], OpValues[3]}, 7450 MMO, IndexType); 7451 } 7452 DAG.setRoot(ST); 7453 setValue(&VPIntrin, ST); 7454 } 7455 7456 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7457 const VPIntrinsic &VPIntrin) { 7458 SDLoc DL = getCurSDLoc(); 7459 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7460 7461 SmallVector<EVT, 4> ValueVTs; 7462 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7463 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7464 SDVTList VTs = DAG.getVTList(ValueVTs); 7465 7466 auto EVLParamPos = 7467 VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID()); 7468 7469 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7470 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7471 "Unexpected target EVL type"); 7472 7473 // Request operands. 7474 SmallVector<SDValue, 7> OpValues; 7475 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7476 auto Op = getValue(VPIntrin.getArgOperand(I)); 7477 if (I == EVLParamPos) 7478 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7479 OpValues.push_back(Op); 7480 } 7481 7482 switch (Opcode) { 7483 default: { 7484 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7485 setValue(&VPIntrin, Result); 7486 break; 7487 } 7488 case ISD::VP_LOAD: 7489 case ISD::VP_GATHER: 7490 visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues, 7491 Opcode == ISD::VP_GATHER); 7492 break; 7493 case ISD::VP_STORE: 7494 case ISD::VP_SCATTER: 7495 visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER); 7496 break; 7497 } 7498 } 7499 7500 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7501 const BasicBlock *EHPadBB, 7502 MCSymbol *&BeginLabel) { 7503 MachineFunction &MF = DAG.getMachineFunction(); 7504 MachineModuleInfo &MMI = MF.getMMI(); 7505 7506 // Insert a label before the invoke call to mark the try range. This can be 7507 // used to detect deletion of the invoke via the MachineModuleInfo. 7508 BeginLabel = MMI.getContext().createTempSymbol(); 7509 7510 // For SjLj, keep track of which landing pads go with which invokes 7511 // so as to maintain the ordering of pads in the LSDA. 7512 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7513 if (CallSiteIndex) { 7514 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7515 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7516 7517 // Now that the call site is handled, stop tracking it. 7518 MMI.setCurrentCallSite(0); 7519 } 7520 7521 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7522 } 7523 7524 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7525 const BasicBlock *EHPadBB, 7526 MCSymbol *BeginLabel) { 7527 assert(BeginLabel && "BeginLabel should've been set"); 7528 7529 MachineFunction &MF = DAG.getMachineFunction(); 7530 MachineModuleInfo &MMI = MF.getMMI(); 7531 7532 // Insert a label at the end of the invoke call to mark the try range. This 7533 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7534 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7535 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7536 7537 // Inform MachineModuleInfo of range. 7538 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7539 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7540 // actually use outlined funclets and their LSDA info style. 7541 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7542 assert(II && "II should've been set"); 7543 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7544 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7545 } else if (!isScopedEHPersonality(Pers)) { 7546 assert(EHPadBB); 7547 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7548 } 7549 7550 return Chain; 7551 } 7552 7553 std::pair<SDValue, SDValue> 7554 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7555 const BasicBlock *EHPadBB) { 7556 MCSymbol *BeginLabel = nullptr; 7557 7558 if (EHPadBB) { 7559 // Both PendingLoads and PendingExports must be flushed here; 7560 // this call might not return. 7561 (void)getRoot(); 7562 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7563 CLI.setChain(getRoot()); 7564 } 7565 7566 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7567 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7568 7569 assert((CLI.IsTailCall || Result.second.getNode()) && 7570 "Non-null chain expected with non-tail call!"); 7571 assert((Result.second.getNode() || !Result.first.getNode()) && 7572 "Null value expected with tail call!"); 7573 7574 if (!Result.second.getNode()) { 7575 // As a special case, a null chain means that a tail call has been emitted 7576 // and the DAG root is already updated. 7577 HasTailCall = true; 7578 7579 // Since there's no actual continuation from this block, nothing can be 7580 // relying on us setting vregs for them. 7581 PendingExports.clear(); 7582 } else { 7583 DAG.setRoot(Result.second); 7584 } 7585 7586 if (EHPadBB) { 7587 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7588 BeginLabel)); 7589 } 7590 7591 return Result; 7592 } 7593 7594 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7595 bool isTailCall, 7596 bool isMustTailCall, 7597 const BasicBlock *EHPadBB) { 7598 auto &DL = DAG.getDataLayout(); 7599 FunctionType *FTy = CB.getFunctionType(); 7600 Type *RetTy = CB.getType(); 7601 7602 TargetLowering::ArgListTy Args; 7603 Args.reserve(CB.arg_size()); 7604 7605 const Value *SwiftErrorVal = nullptr; 7606 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7607 7608 if (isTailCall) { 7609 // Avoid emitting tail calls in functions with the disable-tail-calls 7610 // attribute. 7611 auto *Caller = CB.getParent()->getParent(); 7612 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7613 "true" && !isMustTailCall) 7614 isTailCall = false; 7615 7616 // We can't tail call inside a function with a swifterror argument. Lowering 7617 // does not support this yet. It would have to move into the swifterror 7618 // register before the call. 7619 if (TLI.supportSwiftError() && 7620 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7621 isTailCall = false; 7622 } 7623 7624 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7625 TargetLowering::ArgListEntry Entry; 7626 const Value *V = *I; 7627 7628 // Skip empty types 7629 if (V->getType()->isEmptyTy()) 7630 continue; 7631 7632 SDValue ArgNode = getValue(V); 7633 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7634 7635 Entry.setAttributes(&CB, I - CB.arg_begin()); 7636 7637 // Use swifterror virtual register as input to the call. 7638 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7639 SwiftErrorVal = V; 7640 // We find the virtual register for the actual swifterror argument. 7641 // Instead of using the Value, we use the virtual register instead. 7642 Entry.Node = 7643 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7644 EVT(TLI.getPointerTy(DL))); 7645 } 7646 7647 Args.push_back(Entry); 7648 7649 // If we have an explicit sret argument that is an Instruction, (i.e., it 7650 // might point to function-local memory), we can't meaningfully tail-call. 7651 if (Entry.IsSRet && isa<Instruction>(V)) 7652 isTailCall = false; 7653 } 7654 7655 // If call site has a cfguardtarget operand bundle, create and add an 7656 // additional ArgListEntry. 7657 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7658 TargetLowering::ArgListEntry Entry; 7659 Value *V = Bundle->Inputs[0]; 7660 SDValue ArgNode = getValue(V); 7661 Entry.Node = ArgNode; 7662 Entry.Ty = V->getType(); 7663 Entry.IsCFGuardTarget = true; 7664 Args.push_back(Entry); 7665 } 7666 7667 // Check if target-independent constraints permit a tail call here. 7668 // Target-dependent constraints are checked within TLI->LowerCallTo. 7669 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7670 isTailCall = false; 7671 7672 // Disable tail calls if there is an swifterror argument. Targets have not 7673 // been updated to support tail calls. 7674 if (TLI.supportSwiftError() && SwiftErrorVal) 7675 isTailCall = false; 7676 7677 TargetLowering::CallLoweringInfo CLI(DAG); 7678 CLI.setDebugLoc(getCurSDLoc()) 7679 .setChain(getRoot()) 7680 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7681 .setTailCall(isTailCall) 7682 .setConvergent(CB.isConvergent()) 7683 .setIsPreallocated( 7684 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7685 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7686 7687 if (Result.first.getNode()) { 7688 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7689 setValue(&CB, Result.first); 7690 } 7691 7692 // The last element of CLI.InVals has the SDValue for swifterror return. 7693 // Here we copy it to a virtual register and update SwiftErrorMap for 7694 // book-keeping. 7695 if (SwiftErrorVal && TLI.supportSwiftError()) { 7696 // Get the last element of InVals. 7697 SDValue Src = CLI.InVals.back(); 7698 Register VReg = 7699 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7700 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7701 DAG.setRoot(CopyNode); 7702 } 7703 } 7704 7705 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7706 SelectionDAGBuilder &Builder) { 7707 // Check to see if this load can be trivially constant folded, e.g. if the 7708 // input is from a string literal. 7709 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7710 // Cast pointer to the type we really want to load. 7711 Type *LoadTy = 7712 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7713 if (LoadVT.isVector()) 7714 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7715 7716 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7717 PointerType::getUnqual(LoadTy)); 7718 7719 if (const Constant *LoadCst = 7720 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 7721 LoadTy, Builder.DAG.getDataLayout())) 7722 return Builder.getValue(LoadCst); 7723 } 7724 7725 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7726 // still constant memory, the input chain can be the entry node. 7727 SDValue Root; 7728 bool ConstantMemory = false; 7729 7730 // Do not serialize (non-volatile) loads of constant memory with anything. 7731 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7732 Root = Builder.DAG.getEntryNode(); 7733 ConstantMemory = true; 7734 } else { 7735 // Do not serialize non-volatile loads against each other. 7736 Root = Builder.DAG.getRoot(); 7737 } 7738 7739 SDValue Ptr = Builder.getValue(PtrVal); 7740 SDValue LoadVal = 7741 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7742 MachinePointerInfo(PtrVal), Align(1)); 7743 7744 if (!ConstantMemory) 7745 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7746 return LoadVal; 7747 } 7748 7749 /// Record the value for an instruction that produces an integer result, 7750 /// converting the type where necessary. 7751 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7752 SDValue Value, 7753 bool IsSigned) { 7754 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7755 I.getType(), true); 7756 if (IsSigned) 7757 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7758 else 7759 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7760 setValue(&I, Value); 7761 } 7762 7763 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7764 /// true and lower it. Otherwise return false, and it will be lowered like a 7765 /// normal call. 7766 /// The caller already checked that \p I calls the appropriate LibFunc with a 7767 /// correct prototype. 7768 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7769 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7770 const Value *Size = I.getArgOperand(2); 7771 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7772 if (CSize && CSize->getZExtValue() == 0) { 7773 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7774 I.getType(), true); 7775 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7776 return true; 7777 } 7778 7779 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7780 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7781 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7782 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7783 if (Res.first.getNode()) { 7784 processIntegerCallValue(I, Res.first, true); 7785 PendingLoads.push_back(Res.second); 7786 return true; 7787 } 7788 7789 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7790 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7791 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7792 return false; 7793 7794 // If the target has a fast compare for the given size, it will return a 7795 // preferred load type for that size. Require that the load VT is legal and 7796 // that the target supports unaligned loads of that type. Otherwise, return 7797 // INVALID. 7798 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7799 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7800 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7801 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7802 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7803 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7804 // TODO: Check alignment of src and dest ptrs. 7805 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7806 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7807 if (!TLI.isTypeLegal(LVT) || 7808 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7809 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7810 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7811 } 7812 7813 return LVT; 7814 }; 7815 7816 // This turns into unaligned loads. We only do this if the target natively 7817 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7818 // we'll only produce a small number of byte loads. 7819 MVT LoadVT; 7820 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7821 switch (NumBitsToCompare) { 7822 default: 7823 return false; 7824 case 16: 7825 LoadVT = MVT::i16; 7826 break; 7827 case 32: 7828 LoadVT = MVT::i32; 7829 break; 7830 case 64: 7831 case 128: 7832 case 256: 7833 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7834 break; 7835 } 7836 7837 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7838 return false; 7839 7840 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7841 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7842 7843 // Bitcast to a wide integer type if the loads are vectors. 7844 if (LoadVT.isVector()) { 7845 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7846 LoadL = DAG.getBitcast(CmpVT, LoadL); 7847 LoadR = DAG.getBitcast(CmpVT, LoadR); 7848 } 7849 7850 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7851 processIntegerCallValue(I, Cmp, false); 7852 return true; 7853 } 7854 7855 /// See if we can lower a memchr call into an optimized form. If so, return 7856 /// true and lower it. Otherwise return false, and it will be lowered like a 7857 /// normal call. 7858 /// The caller already checked that \p I calls the appropriate LibFunc with a 7859 /// correct prototype. 7860 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7861 const Value *Src = I.getArgOperand(0); 7862 const Value *Char = I.getArgOperand(1); 7863 const Value *Length = I.getArgOperand(2); 7864 7865 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7866 std::pair<SDValue, SDValue> Res = 7867 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7868 getValue(Src), getValue(Char), getValue(Length), 7869 MachinePointerInfo(Src)); 7870 if (Res.first.getNode()) { 7871 setValue(&I, Res.first); 7872 PendingLoads.push_back(Res.second); 7873 return true; 7874 } 7875 7876 return false; 7877 } 7878 7879 /// See if we can lower a mempcpy call into an optimized form. If so, return 7880 /// true and lower it. Otherwise return false, and it will be lowered like a 7881 /// normal call. 7882 /// The caller already checked that \p I calls the appropriate LibFunc with a 7883 /// correct prototype. 7884 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7885 SDValue Dst = getValue(I.getArgOperand(0)); 7886 SDValue Src = getValue(I.getArgOperand(1)); 7887 SDValue Size = getValue(I.getArgOperand(2)); 7888 7889 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7890 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7891 // DAG::getMemcpy needs Alignment to be defined. 7892 Align Alignment = std::min(DstAlign, SrcAlign); 7893 7894 bool isVol = false; 7895 SDLoc sdl = getCurSDLoc(); 7896 7897 // In the mempcpy context we need to pass in a false value for isTailCall 7898 // because the return pointer needs to be adjusted by the size of 7899 // the copied memory. 7900 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7901 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7902 /*isTailCall=*/false, 7903 MachinePointerInfo(I.getArgOperand(0)), 7904 MachinePointerInfo(I.getArgOperand(1)), 7905 I.getAAMetadata()); 7906 assert(MC.getNode() != nullptr && 7907 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7908 DAG.setRoot(MC); 7909 7910 // Check if Size needs to be truncated or extended. 7911 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7912 7913 // Adjust return pointer to point just past the last dst byte. 7914 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7915 Dst, Size); 7916 setValue(&I, DstPlusSize); 7917 return true; 7918 } 7919 7920 /// See if we can lower a strcpy call into an optimized form. If so, return 7921 /// true and lower it, otherwise return false and it will be lowered like a 7922 /// normal call. 7923 /// The caller already checked that \p I calls the appropriate LibFunc with a 7924 /// correct prototype. 7925 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7926 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7927 7928 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7929 std::pair<SDValue, SDValue> Res = 7930 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7931 getValue(Arg0), getValue(Arg1), 7932 MachinePointerInfo(Arg0), 7933 MachinePointerInfo(Arg1), isStpcpy); 7934 if (Res.first.getNode()) { 7935 setValue(&I, Res.first); 7936 DAG.setRoot(Res.second); 7937 return true; 7938 } 7939 7940 return false; 7941 } 7942 7943 /// See if we can lower a strcmp call into an optimized form. If so, return 7944 /// true and lower it, otherwise return false and it will be lowered like a 7945 /// normal call. 7946 /// The caller already checked that \p I calls the appropriate LibFunc with a 7947 /// correct prototype. 7948 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7949 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7950 7951 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7952 std::pair<SDValue, SDValue> Res = 7953 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7954 getValue(Arg0), getValue(Arg1), 7955 MachinePointerInfo(Arg0), 7956 MachinePointerInfo(Arg1)); 7957 if (Res.first.getNode()) { 7958 processIntegerCallValue(I, Res.first, true); 7959 PendingLoads.push_back(Res.second); 7960 return true; 7961 } 7962 7963 return false; 7964 } 7965 7966 /// See if we can lower a strlen call into an optimized form. If so, return 7967 /// true and lower it, otherwise return false and it will be lowered like a 7968 /// normal call. 7969 /// The caller already checked that \p I calls the appropriate LibFunc with a 7970 /// correct prototype. 7971 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7972 const Value *Arg0 = I.getArgOperand(0); 7973 7974 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7975 std::pair<SDValue, SDValue> Res = 7976 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7977 getValue(Arg0), MachinePointerInfo(Arg0)); 7978 if (Res.first.getNode()) { 7979 processIntegerCallValue(I, Res.first, false); 7980 PendingLoads.push_back(Res.second); 7981 return true; 7982 } 7983 7984 return false; 7985 } 7986 7987 /// See if we can lower a strnlen call into an optimized form. If so, return 7988 /// true and lower it, otherwise return false and it will be lowered like a 7989 /// normal call. 7990 /// The caller already checked that \p I calls the appropriate LibFunc with a 7991 /// correct prototype. 7992 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7993 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7994 7995 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7996 std::pair<SDValue, SDValue> Res = 7997 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7998 getValue(Arg0), getValue(Arg1), 7999 MachinePointerInfo(Arg0)); 8000 if (Res.first.getNode()) { 8001 processIntegerCallValue(I, Res.first, false); 8002 PendingLoads.push_back(Res.second); 8003 return true; 8004 } 8005 8006 return false; 8007 } 8008 8009 /// See if we can lower a unary floating-point operation into an SDNode with 8010 /// the specified Opcode. If so, return true and lower it, otherwise return 8011 /// false and it will be lowered like a normal call. 8012 /// The caller already checked that \p I calls the appropriate LibFunc with a 8013 /// correct prototype. 8014 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8015 unsigned Opcode) { 8016 // We already checked this call's prototype; verify it doesn't modify errno. 8017 if (!I.onlyReadsMemory()) 8018 return false; 8019 8020 SDNodeFlags Flags; 8021 Flags.copyFMF(cast<FPMathOperator>(I)); 8022 8023 SDValue Tmp = getValue(I.getArgOperand(0)); 8024 setValue(&I, 8025 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8026 return true; 8027 } 8028 8029 /// See if we can lower a binary floating-point operation into an SDNode with 8030 /// the specified Opcode. If so, return true and lower it. Otherwise return 8031 /// false, and it will be lowered like a normal call. 8032 /// The caller already checked that \p I calls the appropriate LibFunc with a 8033 /// correct prototype. 8034 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8035 unsigned Opcode) { 8036 // We already checked this call's prototype; verify it doesn't modify errno. 8037 if (!I.onlyReadsMemory()) 8038 return false; 8039 8040 SDNodeFlags Flags; 8041 Flags.copyFMF(cast<FPMathOperator>(I)); 8042 8043 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8044 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8045 EVT VT = Tmp0.getValueType(); 8046 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8047 return true; 8048 } 8049 8050 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8051 // Handle inline assembly differently. 8052 if (I.isInlineAsm()) { 8053 visitInlineAsm(I); 8054 return; 8055 } 8056 8057 if (Function *F = I.getCalledFunction()) { 8058 diagnoseDontCall(I); 8059 8060 if (F->isDeclaration()) { 8061 // Is this an LLVM intrinsic or a target-specific intrinsic? 8062 unsigned IID = F->getIntrinsicID(); 8063 if (!IID) 8064 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8065 IID = II->getIntrinsicID(F); 8066 8067 if (IID) { 8068 visitIntrinsicCall(I, IID); 8069 return; 8070 } 8071 } 8072 8073 // Check for well-known libc/libm calls. If the function is internal, it 8074 // can't be a library call. Don't do the check if marked as nobuiltin for 8075 // some reason or the call site requires strict floating point semantics. 8076 LibFunc Func; 8077 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8078 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8079 LibInfo->hasOptimizedCodeGen(Func)) { 8080 switch (Func) { 8081 default: break; 8082 case LibFunc_bcmp: 8083 if (visitMemCmpBCmpCall(I)) 8084 return; 8085 break; 8086 case LibFunc_copysign: 8087 case LibFunc_copysignf: 8088 case LibFunc_copysignl: 8089 // We already checked this call's prototype; verify it doesn't modify 8090 // errno. 8091 if (I.onlyReadsMemory()) { 8092 SDValue LHS = getValue(I.getArgOperand(0)); 8093 SDValue RHS = getValue(I.getArgOperand(1)); 8094 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8095 LHS.getValueType(), LHS, RHS)); 8096 return; 8097 } 8098 break; 8099 case LibFunc_fabs: 8100 case LibFunc_fabsf: 8101 case LibFunc_fabsl: 8102 if (visitUnaryFloatCall(I, ISD::FABS)) 8103 return; 8104 break; 8105 case LibFunc_fmin: 8106 case LibFunc_fminf: 8107 case LibFunc_fminl: 8108 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8109 return; 8110 break; 8111 case LibFunc_fmax: 8112 case LibFunc_fmaxf: 8113 case LibFunc_fmaxl: 8114 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8115 return; 8116 break; 8117 case LibFunc_sin: 8118 case LibFunc_sinf: 8119 case LibFunc_sinl: 8120 if (visitUnaryFloatCall(I, ISD::FSIN)) 8121 return; 8122 break; 8123 case LibFunc_cos: 8124 case LibFunc_cosf: 8125 case LibFunc_cosl: 8126 if (visitUnaryFloatCall(I, ISD::FCOS)) 8127 return; 8128 break; 8129 case LibFunc_sqrt: 8130 case LibFunc_sqrtf: 8131 case LibFunc_sqrtl: 8132 case LibFunc_sqrt_finite: 8133 case LibFunc_sqrtf_finite: 8134 case LibFunc_sqrtl_finite: 8135 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8136 return; 8137 break; 8138 case LibFunc_floor: 8139 case LibFunc_floorf: 8140 case LibFunc_floorl: 8141 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8142 return; 8143 break; 8144 case LibFunc_nearbyint: 8145 case LibFunc_nearbyintf: 8146 case LibFunc_nearbyintl: 8147 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8148 return; 8149 break; 8150 case LibFunc_ceil: 8151 case LibFunc_ceilf: 8152 case LibFunc_ceill: 8153 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8154 return; 8155 break; 8156 case LibFunc_rint: 8157 case LibFunc_rintf: 8158 case LibFunc_rintl: 8159 if (visitUnaryFloatCall(I, ISD::FRINT)) 8160 return; 8161 break; 8162 case LibFunc_round: 8163 case LibFunc_roundf: 8164 case LibFunc_roundl: 8165 if (visitUnaryFloatCall(I, ISD::FROUND)) 8166 return; 8167 break; 8168 case LibFunc_trunc: 8169 case LibFunc_truncf: 8170 case LibFunc_truncl: 8171 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8172 return; 8173 break; 8174 case LibFunc_log2: 8175 case LibFunc_log2f: 8176 case LibFunc_log2l: 8177 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8178 return; 8179 break; 8180 case LibFunc_exp2: 8181 case LibFunc_exp2f: 8182 case LibFunc_exp2l: 8183 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8184 return; 8185 break; 8186 case LibFunc_memcmp: 8187 if (visitMemCmpBCmpCall(I)) 8188 return; 8189 break; 8190 case LibFunc_mempcpy: 8191 if (visitMemPCpyCall(I)) 8192 return; 8193 break; 8194 case LibFunc_memchr: 8195 if (visitMemChrCall(I)) 8196 return; 8197 break; 8198 case LibFunc_strcpy: 8199 if (visitStrCpyCall(I, false)) 8200 return; 8201 break; 8202 case LibFunc_stpcpy: 8203 if (visitStrCpyCall(I, true)) 8204 return; 8205 break; 8206 case LibFunc_strcmp: 8207 if (visitStrCmpCall(I)) 8208 return; 8209 break; 8210 case LibFunc_strlen: 8211 if (visitStrLenCall(I)) 8212 return; 8213 break; 8214 case LibFunc_strnlen: 8215 if (visitStrNLenCall(I)) 8216 return; 8217 break; 8218 } 8219 } 8220 } 8221 8222 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8223 // have to do anything here to lower funclet bundles. 8224 // CFGuardTarget bundles are lowered in LowerCallTo. 8225 assert(!I.hasOperandBundlesOtherThan( 8226 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8227 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8228 LLVMContext::OB_clang_arc_attachedcall}) && 8229 "Cannot lower calls with arbitrary operand bundles!"); 8230 8231 SDValue Callee = getValue(I.getCalledOperand()); 8232 8233 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8234 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8235 else 8236 // Check if we can potentially perform a tail call. More detailed checking 8237 // is be done within LowerCallTo, after more information about the call is 8238 // known. 8239 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8240 } 8241 8242 namespace { 8243 8244 /// AsmOperandInfo - This contains information for each constraint that we are 8245 /// lowering. 8246 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8247 public: 8248 /// CallOperand - If this is the result output operand or a clobber 8249 /// this is null, otherwise it is the incoming operand to the CallInst. 8250 /// This gets modified as the asm is processed. 8251 SDValue CallOperand; 8252 8253 /// AssignedRegs - If this is a register or register class operand, this 8254 /// contains the set of register corresponding to the operand. 8255 RegsForValue AssignedRegs; 8256 8257 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8258 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8259 } 8260 8261 /// Whether or not this operand accesses memory 8262 bool hasMemory(const TargetLowering &TLI) const { 8263 // Indirect operand accesses access memory. 8264 if (isIndirect) 8265 return true; 8266 8267 for (const auto &Code : Codes) 8268 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8269 return true; 8270 8271 return false; 8272 } 8273 8274 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8275 /// corresponds to. If there is no Value* for this operand, it returns 8276 /// MVT::Other. 8277 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8278 const DataLayout &DL, 8279 llvm::Type *ParamElemType) const { 8280 if (!CallOperandVal) return MVT::Other; 8281 8282 if (isa<BasicBlock>(CallOperandVal)) 8283 return TLI.getProgramPointerTy(DL); 8284 8285 llvm::Type *OpTy = CallOperandVal->getType(); 8286 8287 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8288 // If this is an indirect operand, the operand is a pointer to the 8289 // accessed type. 8290 if (isIndirect) { 8291 OpTy = ParamElemType; 8292 assert(OpTy && "Indirect operand must have elementtype attribute"); 8293 } 8294 8295 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8296 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8297 if (STy->getNumElements() == 1) 8298 OpTy = STy->getElementType(0); 8299 8300 // If OpTy is not a single value, it may be a struct/union that we 8301 // can tile with integers. 8302 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8303 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8304 switch (BitSize) { 8305 default: break; 8306 case 1: 8307 case 8: 8308 case 16: 8309 case 32: 8310 case 64: 8311 case 128: 8312 OpTy = IntegerType::get(Context, BitSize); 8313 break; 8314 } 8315 } 8316 8317 return TLI.getAsmOperandValueType(DL, OpTy, true); 8318 } 8319 }; 8320 8321 8322 } // end anonymous namespace 8323 8324 /// Make sure that the output operand \p OpInfo and its corresponding input 8325 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8326 /// out). 8327 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8328 SDISelAsmOperandInfo &MatchingOpInfo, 8329 SelectionDAG &DAG) { 8330 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8331 return; 8332 8333 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8334 const auto &TLI = DAG.getTargetLoweringInfo(); 8335 8336 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8337 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8338 OpInfo.ConstraintVT); 8339 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8340 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8341 MatchingOpInfo.ConstraintVT); 8342 if ((OpInfo.ConstraintVT.isInteger() != 8343 MatchingOpInfo.ConstraintVT.isInteger()) || 8344 (MatchRC.second != InputRC.second)) { 8345 // FIXME: error out in a more elegant fashion 8346 report_fatal_error("Unsupported asm: input constraint" 8347 " with a matching output constraint of" 8348 " incompatible type!"); 8349 } 8350 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8351 } 8352 8353 /// Get a direct memory input to behave well as an indirect operand. 8354 /// This may introduce stores, hence the need for a \p Chain. 8355 /// \return The (possibly updated) chain. 8356 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8357 SDISelAsmOperandInfo &OpInfo, 8358 SelectionDAG &DAG) { 8359 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8360 8361 // If we don't have an indirect input, put it in the constpool if we can, 8362 // otherwise spill it to a stack slot. 8363 // TODO: This isn't quite right. We need to handle these according to 8364 // the addressing mode that the constraint wants. Also, this may take 8365 // an additional register for the computation and we don't want that 8366 // either. 8367 8368 // If the operand is a float, integer, or vector constant, spill to a 8369 // constant pool entry to get its address. 8370 const Value *OpVal = OpInfo.CallOperandVal; 8371 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8372 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8373 OpInfo.CallOperand = DAG.getConstantPool( 8374 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8375 return Chain; 8376 } 8377 8378 // Otherwise, create a stack slot and emit a store to it before the asm. 8379 Type *Ty = OpVal->getType(); 8380 auto &DL = DAG.getDataLayout(); 8381 uint64_t TySize = DL.getTypeAllocSize(Ty); 8382 MachineFunction &MF = DAG.getMachineFunction(); 8383 int SSFI = MF.getFrameInfo().CreateStackObject( 8384 TySize, DL.getPrefTypeAlign(Ty), false); 8385 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8386 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8387 MachinePointerInfo::getFixedStack(MF, SSFI), 8388 TLI.getMemValueType(DL, Ty)); 8389 OpInfo.CallOperand = StackSlot; 8390 8391 return Chain; 8392 } 8393 8394 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8395 /// specified operand. We prefer to assign virtual registers, to allow the 8396 /// register allocator to handle the assignment process. However, if the asm 8397 /// uses features that we can't model on machineinstrs, we have SDISel do the 8398 /// allocation. This produces generally horrible, but correct, code. 8399 /// 8400 /// OpInfo describes the operand 8401 /// RefOpInfo describes the matching operand if any, the operand otherwise 8402 static llvm::Optional<unsigned> 8403 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8404 SDISelAsmOperandInfo &OpInfo, 8405 SDISelAsmOperandInfo &RefOpInfo) { 8406 LLVMContext &Context = *DAG.getContext(); 8407 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8408 8409 MachineFunction &MF = DAG.getMachineFunction(); 8410 SmallVector<unsigned, 4> Regs; 8411 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8412 8413 // No work to do for memory operations. 8414 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8415 return None; 8416 8417 // If this is a constraint for a single physreg, or a constraint for a 8418 // register class, find it. 8419 unsigned AssignedReg; 8420 const TargetRegisterClass *RC; 8421 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8422 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8423 // RC is unset only on failure. Return immediately. 8424 if (!RC) 8425 return None; 8426 8427 // Get the actual register value type. This is important, because the user 8428 // may have asked for (e.g.) the AX register in i32 type. We need to 8429 // remember that AX is actually i16 to get the right extension. 8430 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8431 8432 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8433 // If this is an FP operand in an integer register (or visa versa), or more 8434 // generally if the operand value disagrees with the register class we plan 8435 // to stick it in, fix the operand type. 8436 // 8437 // If this is an input value, the bitcast to the new type is done now. 8438 // Bitcast for output value is done at the end of visitInlineAsm(). 8439 if ((OpInfo.Type == InlineAsm::isOutput || 8440 OpInfo.Type == InlineAsm::isInput) && 8441 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8442 // Try to convert to the first EVT that the reg class contains. If the 8443 // types are identical size, use a bitcast to convert (e.g. two differing 8444 // vector types). Note: output bitcast is done at the end of 8445 // visitInlineAsm(). 8446 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8447 // Exclude indirect inputs while they are unsupported because the code 8448 // to perform the load is missing and thus OpInfo.CallOperand still 8449 // refers to the input address rather than the pointed-to value. 8450 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8451 OpInfo.CallOperand = 8452 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8453 OpInfo.ConstraintVT = RegVT; 8454 // If the operand is an FP value and we want it in integer registers, 8455 // use the corresponding integer type. This turns an f64 value into 8456 // i64, which can be passed with two i32 values on a 32-bit machine. 8457 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8458 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8459 if (OpInfo.Type == InlineAsm::isInput) 8460 OpInfo.CallOperand = 8461 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8462 OpInfo.ConstraintVT = VT; 8463 } 8464 } 8465 } 8466 8467 // No need to allocate a matching input constraint since the constraint it's 8468 // matching to has already been allocated. 8469 if (OpInfo.isMatchingInputConstraint()) 8470 return None; 8471 8472 EVT ValueVT = OpInfo.ConstraintVT; 8473 if (OpInfo.ConstraintVT == MVT::Other) 8474 ValueVT = RegVT; 8475 8476 // Initialize NumRegs. 8477 unsigned NumRegs = 1; 8478 if (OpInfo.ConstraintVT != MVT::Other) 8479 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8480 8481 // If this is a constraint for a specific physical register, like {r17}, 8482 // assign it now. 8483 8484 // If this associated to a specific register, initialize iterator to correct 8485 // place. If virtual, make sure we have enough registers 8486 8487 // Initialize iterator if necessary 8488 TargetRegisterClass::iterator I = RC->begin(); 8489 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8490 8491 // Do not check for single registers. 8492 if (AssignedReg) { 8493 I = std::find(I, RC->end(), AssignedReg); 8494 if (I == RC->end()) { 8495 // RC does not contain the selected register, which indicates a 8496 // mismatch between the register and the required type/bitwidth. 8497 return {AssignedReg}; 8498 } 8499 } 8500 8501 for (; NumRegs; --NumRegs, ++I) { 8502 assert(I != RC->end() && "Ran out of registers to allocate!"); 8503 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8504 Regs.push_back(R); 8505 } 8506 8507 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8508 return None; 8509 } 8510 8511 static unsigned 8512 findMatchingInlineAsmOperand(unsigned OperandNo, 8513 const std::vector<SDValue> &AsmNodeOperands) { 8514 // Scan until we find the definition we already emitted of this operand. 8515 unsigned CurOp = InlineAsm::Op_FirstOperand; 8516 for (; OperandNo; --OperandNo) { 8517 // Advance to the next operand. 8518 unsigned OpFlag = 8519 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8520 assert((InlineAsm::isRegDefKind(OpFlag) || 8521 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8522 InlineAsm::isMemKind(OpFlag)) && 8523 "Skipped past definitions?"); 8524 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8525 } 8526 return CurOp; 8527 } 8528 8529 namespace { 8530 8531 class ExtraFlags { 8532 unsigned Flags = 0; 8533 8534 public: 8535 explicit ExtraFlags(const CallBase &Call) { 8536 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8537 if (IA->hasSideEffects()) 8538 Flags |= InlineAsm::Extra_HasSideEffects; 8539 if (IA->isAlignStack()) 8540 Flags |= InlineAsm::Extra_IsAlignStack; 8541 if (Call.isConvergent()) 8542 Flags |= InlineAsm::Extra_IsConvergent; 8543 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8544 } 8545 8546 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8547 // Ideally, we would only check against memory constraints. However, the 8548 // meaning of an Other constraint can be target-specific and we can't easily 8549 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8550 // for Other constraints as well. 8551 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8552 OpInfo.ConstraintType == TargetLowering::C_Other) { 8553 if (OpInfo.Type == InlineAsm::isInput) 8554 Flags |= InlineAsm::Extra_MayLoad; 8555 else if (OpInfo.Type == InlineAsm::isOutput) 8556 Flags |= InlineAsm::Extra_MayStore; 8557 else if (OpInfo.Type == InlineAsm::isClobber) 8558 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8559 } 8560 } 8561 8562 unsigned get() const { return Flags; } 8563 }; 8564 8565 } // end anonymous namespace 8566 8567 /// visitInlineAsm - Handle a call to an InlineAsm object. 8568 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8569 const BasicBlock *EHPadBB) { 8570 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8571 8572 /// ConstraintOperands - Information about all of the constraints. 8573 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8574 8575 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8576 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8577 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8578 8579 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8580 // AsmDialect, MayLoad, MayStore). 8581 bool HasSideEffect = IA->hasSideEffects(); 8582 ExtraFlags ExtraInfo(Call); 8583 8584 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8585 unsigned ResNo = 0; // ResNo - The result number of the next output. 8586 for (auto &T : TargetConstraints) { 8587 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8588 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8589 8590 // Compute the value type for each operand. 8591 if (OpInfo.hasArg()) { 8592 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 8593 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8594 Type *ParamElemTy = Call.getParamElementType(ArgNo); 8595 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8596 DAG.getDataLayout(), ParamElemTy); 8597 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8598 ArgNo++; 8599 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8600 // The return value of the call is this value. As such, there is no 8601 // corresponding argument. 8602 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8603 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8604 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8605 DAG.getDataLayout(), STy->getElementType(ResNo)); 8606 } else { 8607 assert(ResNo == 0 && "Asm only has one result!"); 8608 OpInfo.ConstraintVT = TLI.getAsmOperandValueType( 8609 DAG.getDataLayout(), Call.getType()).getSimpleVT(); 8610 } 8611 ++ResNo; 8612 } else { 8613 OpInfo.ConstraintVT = MVT::Other; 8614 } 8615 8616 if (!HasSideEffect) 8617 HasSideEffect = OpInfo.hasMemory(TLI); 8618 8619 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8620 // FIXME: Could we compute this on OpInfo rather than T? 8621 8622 // Compute the constraint code and ConstraintType to use. 8623 TLI.ComputeConstraintToUse(T, SDValue()); 8624 8625 if (T.ConstraintType == TargetLowering::C_Immediate && 8626 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8627 // We've delayed emitting a diagnostic like the "n" constraint because 8628 // inlining could cause an integer showing up. 8629 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8630 "' expects an integer constant " 8631 "expression"); 8632 8633 ExtraInfo.update(T); 8634 } 8635 8636 // We won't need to flush pending loads if this asm doesn't touch 8637 // memory and is nonvolatile. 8638 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8639 8640 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8641 if (EmitEHLabels) { 8642 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8643 } 8644 bool IsCallBr = isa<CallBrInst>(Call); 8645 8646 if (IsCallBr || EmitEHLabels) { 8647 // If this is a callbr or invoke we need to flush pending exports since 8648 // inlineasm_br and invoke are terminators. 8649 // We need to do this before nodes are glued to the inlineasm_br node. 8650 Chain = getControlRoot(); 8651 } 8652 8653 MCSymbol *BeginLabel = nullptr; 8654 if (EmitEHLabels) { 8655 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8656 } 8657 8658 // Second pass over the constraints: compute which constraint option to use. 8659 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8660 // If this is an output operand with a matching input operand, look up the 8661 // matching input. If their types mismatch, e.g. one is an integer, the 8662 // other is floating point, or their sizes are different, flag it as an 8663 // error. 8664 if (OpInfo.hasMatchingInput()) { 8665 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8666 patchMatchingInput(OpInfo, Input, DAG); 8667 } 8668 8669 // Compute the constraint code and ConstraintType to use. 8670 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8671 8672 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8673 OpInfo.Type == InlineAsm::isClobber) 8674 continue; 8675 8676 // If this is a memory input, and if the operand is not indirect, do what we 8677 // need to provide an address for the memory input. 8678 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8679 !OpInfo.isIndirect) { 8680 assert((OpInfo.isMultipleAlternative || 8681 (OpInfo.Type == InlineAsm::isInput)) && 8682 "Can only indirectify direct input operands!"); 8683 8684 // Memory operands really want the address of the value. 8685 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8686 8687 // There is no longer a Value* corresponding to this operand. 8688 OpInfo.CallOperandVal = nullptr; 8689 8690 // It is now an indirect operand. 8691 OpInfo.isIndirect = true; 8692 } 8693 8694 } 8695 8696 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8697 std::vector<SDValue> AsmNodeOperands; 8698 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8699 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8700 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8701 8702 // If we have a !srcloc metadata node associated with it, we want to attach 8703 // this to the ultimately generated inline asm machineinstr. To do this, we 8704 // pass in the third operand as this (potentially null) inline asm MDNode. 8705 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8706 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8707 8708 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8709 // bits as operand 3. 8710 AsmNodeOperands.push_back(DAG.getTargetConstant( 8711 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8712 8713 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8714 // this, assign virtual and physical registers for inputs and otput. 8715 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8716 // Assign Registers. 8717 SDISelAsmOperandInfo &RefOpInfo = 8718 OpInfo.isMatchingInputConstraint() 8719 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8720 : OpInfo; 8721 const auto RegError = 8722 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8723 if (RegError.hasValue()) { 8724 const MachineFunction &MF = DAG.getMachineFunction(); 8725 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8726 const char *RegName = TRI.getName(RegError.getValue()); 8727 emitInlineAsmError(Call, "register '" + Twine(RegName) + 8728 "' allocated for constraint '" + 8729 Twine(OpInfo.ConstraintCode) + 8730 "' does not match required type"); 8731 return; 8732 } 8733 8734 auto DetectWriteToReservedRegister = [&]() { 8735 const MachineFunction &MF = DAG.getMachineFunction(); 8736 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8737 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8738 if (Register::isPhysicalRegister(Reg) && 8739 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8740 const char *RegName = TRI.getName(Reg); 8741 emitInlineAsmError(Call, "write to reserved register '" + 8742 Twine(RegName) + "'"); 8743 return true; 8744 } 8745 } 8746 return false; 8747 }; 8748 8749 switch (OpInfo.Type) { 8750 case InlineAsm::isOutput: 8751 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8752 unsigned ConstraintID = 8753 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8754 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8755 "Failed to convert memory constraint code to constraint id."); 8756 8757 // Add information to the INLINEASM node to know about this output. 8758 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8759 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8760 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8761 MVT::i32)); 8762 AsmNodeOperands.push_back(OpInfo.CallOperand); 8763 } else { 8764 // Otherwise, this outputs to a register (directly for C_Register / 8765 // C_RegisterClass, and a target-defined fashion for 8766 // C_Immediate/C_Other). Find a register that we can use. 8767 if (OpInfo.AssignedRegs.Regs.empty()) { 8768 emitInlineAsmError( 8769 Call, "couldn't allocate output register for constraint '" + 8770 Twine(OpInfo.ConstraintCode) + "'"); 8771 return; 8772 } 8773 8774 if (DetectWriteToReservedRegister()) 8775 return; 8776 8777 // Add information to the INLINEASM node to know that this register is 8778 // set. 8779 OpInfo.AssignedRegs.AddInlineAsmOperands( 8780 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8781 : InlineAsm::Kind_RegDef, 8782 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8783 } 8784 break; 8785 8786 case InlineAsm::isInput: { 8787 SDValue InOperandVal = OpInfo.CallOperand; 8788 8789 if (OpInfo.isMatchingInputConstraint()) { 8790 // If this is required to match an output register we have already set, 8791 // just use its register. 8792 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8793 AsmNodeOperands); 8794 unsigned OpFlag = 8795 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8796 if (InlineAsm::isRegDefKind(OpFlag) || 8797 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8798 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8799 if (OpInfo.isIndirect) { 8800 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8801 emitInlineAsmError(Call, "inline asm not supported yet: " 8802 "don't know how to handle tied " 8803 "indirect register inputs"); 8804 return; 8805 } 8806 8807 SmallVector<unsigned, 4> Regs; 8808 MachineFunction &MF = DAG.getMachineFunction(); 8809 MachineRegisterInfo &MRI = MF.getRegInfo(); 8810 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8811 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 8812 Register TiedReg = R->getReg(); 8813 MVT RegVT = R->getSimpleValueType(0); 8814 const TargetRegisterClass *RC = 8815 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 8816 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 8817 : TRI.getMinimalPhysRegClass(TiedReg); 8818 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8819 for (unsigned i = 0; i != NumRegs; ++i) 8820 Regs.push_back(MRI.createVirtualRegister(RC)); 8821 8822 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8823 8824 SDLoc dl = getCurSDLoc(); 8825 // Use the produced MatchedRegs object to 8826 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8827 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8828 true, OpInfo.getMatchedOperand(), dl, 8829 DAG, AsmNodeOperands); 8830 break; 8831 } 8832 8833 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8834 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8835 "Unexpected number of operands"); 8836 // Add information to the INLINEASM node to know about this input. 8837 // See InlineAsm.h isUseOperandTiedToDef. 8838 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8839 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8840 OpInfo.getMatchedOperand()); 8841 AsmNodeOperands.push_back(DAG.getTargetConstant( 8842 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8843 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8844 break; 8845 } 8846 8847 // Treat indirect 'X' constraint as memory. 8848 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8849 OpInfo.isIndirect) 8850 OpInfo.ConstraintType = TargetLowering::C_Memory; 8851 8852 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8853 OpInfo.ConstraintType == TargetLowering::C_Other) { 8854 std::vector<SDValue> Ops; 8855 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8856 Ops, DAG); 8857 if (Ops.empty()) { 8858 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8859 if (isa<ConstantSDNode>(InOperandVal)) { 8860 emitInlineAsmError(Call, "value out of range for constraint '" + 8861 Twine(OpInfo.ConstraintCode) + "'"); 8862 return; 8863 } 8864 8865 emitInlineAsmError(Call, 8866 "invalid operand for inline asm constraint '" + 8867 Twine(OpInfo.ConstraintCode) + "'"); 8868 return; 8869 } 8870 8871 // Add information to the INLINEASM node to know about this input. 8872 unsigned ResOpType = 8873 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8874 AsmNodeOperands.push_back(DAG.getTargetConstant( 8875 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8876 llvm::append_range(AsmNodeOperands, Ops); 8877 break; 8878 } 8879 8880 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8881 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8882 assert(InOperandVal.getValueType() == 8883 TLI.getPointerTy(DAG.getDataLayout()) && 8884 "Memory operands expect pointer values"); 8885 8886 unsigned ConstraintID = 8887 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8888 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8889 "Failed to convert memory constraint code to constraint id."); 8890 8891 // Add information to the INLINEASM node to know about this input. 8892 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8893 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8894 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8895 getCurSDLoc(), 8896 MVT::i32)); 8897 AsmNodeOperands.push_back(InOperandVal); 8898 break; 8899 } 8900 8901 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8902 OpInfo.ConstraintType == TargetLowering::C_Register) && 8903 "Unknown constraint type!"); 8904 8905 // TODO: Support this. 8906 if (OpInfo.isIndirect) { 8907 emitInlineAsmError( 8908 Call, "Don't know how to handle indirect register inputs yet " 8909 "for constraint '" + 8910 Twine(OpInfo.ConstraintCode) + "'"); 8911 return; 8912 } 8913 8914 // Copy the input into the appropriate registers. 8915 if (OpInfo.AssignedRegs.Regs.empty()) { 8916 emitInlineAsmError(Call, 8917 "couldn't allocate input reg for constraint '" + 8918 Twine(OpInfo.ConstraintCode) + "'"); 8919 return; 8920 } 8921 8922 if (DetectWriteToReservedRegister()) 8923 return; 8924 8925 SDLoc dl = getCurSDLoc(); 8926 8927 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8928 &Call); 8929 8930 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8931 dl, DAG, AsmNodeOperands); 8932 break; 8933 } 8934 case InlineAsm::isClobber: 8935 // Add the clobbered value to the operand list, so that the register 8936 // allocator is aware that the physreg got clobbered. 8937 if (!OpInfo.AssignedRegs.Regs.empty()) 8938 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8939 false, 0, getCurSDLoc(), DAG, 8940 AsmNodeOperands); 8941 break; 8942 } 8943 } 8944 8945 // Finish up input operands. Set the input chain and add the flag last. 8946 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8947 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8948 8949 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8950 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8951 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8952 Flag = Chain.getValue(1); 8953 8954 // Do additional work to generate outputs. 8955 8956 SmallVector<EVT, 1> ResultVTs; 8957 SmallVector<SDValue, 1> ResultValues; 8958 SmallVector<SDValue, 8> OutChains; 8959 8960 llvm::Type *CallResultType = Call.getType(); 8961 ArrayRef<Type *> ResultTypes; 8962 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8963 ResultTypes = StructResult->elements(); 8964 else if (!CallResultType->isVoidTy()) 8965 ResultTypes = makeArrayRef(CallResultType); 8966 8967 auto CurResultType = ResultTypes.begin(); 8968 auto handleRegAssign = [&](SDValue V) { 8969 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8970 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8971 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8972 ++CurResultType; 8973 // If the type of the inline asm call site return value is different but has 8974 // same size as the type of the asm output bitcast it. One example of this 8975 // is for vectors with different width / number of elements. This can 8976 // happen for register classes that can contain multiple different value 8977 // types. The preg or vreg allocated may not have the same VT as was 8978 // expected. 8979 // 8980 // This can also happen for a return value that disagrees with the register 8981 // class it is put in, eg. a double in a general-purpose register on a 8982 // 32-bit machine. 8983 if (ResultVT != V.getValueType() && 8984 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8985 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8986 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8987 V.getValueType().isInteger()) { 8988 // If a result value was tied to an input value, the computed result 8989 // may have a wider width than the expected result. Extract the 8990 // relevant portion. 8991 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8992 } 8993 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8994 ResultVTs.push_back(ResultVT); 8995 ResultValues.push_back(V); 8996 }; 8997 8998 // Deal with output operands. 8999 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9000 if (OpInfo.Type == InlineAsm::isOutput) { 9001 SDValue Val; 9002 // Skip trivial output operands. 9003 if (OpInfo.AssignedRegs.Regs.empty()) 9004 continue; 9005 9006 switch (OpInfo.ConstraintType) { 9007 case TargetLowering::C_Register: 9008 case TargetLowering::C_RegisterClass: 9009 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9010 Chain, &Flag, &Call); 9011 break; 9012 case TargetLowering::C_Immediate: 9013 case TargetLowering::C_Other: 9014 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9015 OpInfo, DAG); 9016 break; 9017 case TargetLowering::C_Memory: 9018 break; // Already handled. 9019 case TargetLowering::C_Unknown: 9020 assert(false && "Unexpected unknown constraint"); 9021 } 9022 9023 // Indirect output manifest as stores. Record output chains. 9024 if (OpInfo.isIndirect) { 9025 const Value *Ptr = OpInfo.CallOperandVal; 9026 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9027 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9028 MachinePointerInfo(Ptr)); 9029 OutChains.push_back(Store); 9030 } else { 9031 // generate CopyFromRegs to associated registers. 9032 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9033 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9034 for (const SDValue &V : Val->op_values()) 9035 handleRegAssign(V); 9036 } else 9037 handleRegAssign(Val); 9038 } 9039 } 9040 } 9041 9042 // Set results. 9043 if (!ResultValues.empty()) { 9044 assert(CurResultType == ResultTypes.end() && 9045 "Mismatch in number of ResultTypes"); 9046 assert(ResultValues.size() == ResultTypes.size() && 9047 "Mismatch in number of output operands in asm result"); 9048 9049 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9050 DAG.getVTList(ResultVTs), ResultValues); 9051 setValue(&Call, V); 9052 } 9053 9054 // Collect store chains. 9055 if (!OutChains.empty()) 9056 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9057 9058 if (EmitEHLabels) { 9059 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9060 } 9061 9062 // Only Update Root if inline assembly has a memory effect. 9063 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9064 EmitEHLabels) 9065 DAG.setRoot(Chain); 9066 } 9067 9068 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9069 const Twine &Message) { 9070 LLVMContext &Ctx = *DAG.getContext(); 9071 Ctx.emitError(&Call, Message); 9072 9073 // Make sure we leave the DAG in a valid state 9074 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9075 SmallVector<EVT, 1> ValueVTs; 9076 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9077 9078 if (ValueVTs.empty()) 9079 return; 9080 9081 SmallVector<SDValue, 1> Ops; 9082 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9083 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9084 9085 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9086 } 9087 9088 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9089 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9090 MVT::Other, getRoot(), 9091 getValue(I.getArgOperand(0)), 9092 DAG.getSrcValue(I.getArgOperand(0)))); 9093 } 9094 9095 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9096 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9097 const DataLayout &DL = DAG.getDataLayout(); 9098 SDValue V = DAG.getVAArg( 9099 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9100 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9101 DL.getABITypeAlign(I.getType()).value()); 9102 DAG.setRoot(V.getValue(1)); 9103 9104 if (I.getType()->isPointerTy()) 9105 V = DAG.getPtrExtOrTrunc( 9106 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9107 setValue(&I, V); 9108 } 9109 9110 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9111 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9112 MVT::Other, getRoot(), 9113 getValue(I.getArgOperand(0)), 9114 DAG.getSrcValue(I.getArgOperand(0)))); 9115 } 9116 9117 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9118 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9119 MVT::Other, getRoot(), 9120 getValue(I.getArgOperand(0)), 9121 getValue(I.getArgOperand(1)), 9122 DAG.getSrcValue(I.getArgOperand(0)), 9123 DAG.getSrcValue(I.getArgOperand(1)))); 9124 } 9125 9126 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9127 const Instruction &I, 9128 SDValue Op) { 9129 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9130 if (!Range) 9131 return Op; 9132 9133 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9134 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9135 return Op; 9136 9137 APInt Lo = CR.getUnsignedMin(); 9138 if (!Lo.isMinValue()) 9139 return Op; 9140 9141 APInt Hi = CR.getUnsignedMax(); 9142 unsigned Bits = std::max(Hi.getActiveBits(), 9143 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9144 9145 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9146 9147 SDLoc SL = getCurSDLoc(); 9148 9149 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9150 DAG.getValueType(SmallVT)); 9151 unsigned NumVals = Op.getNode()->getNumValues(); 9152 if (NumVals == 1) 9153 return ZExt; 9154 9155 SmallVector<SDValue, 4> Ops; 9156 9157 Ops.push_back(ZExt); 9158 for (unsigned I = 1; I != NumVals; ++I) 9159 Ops.push_back(Op.getValue(I)); 9160 9161 return DAG.getMergeValues(Ops, SL); 9162 } 9163 9164 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9165 /// the call being lowered. 9166 /// 9167 /// This is a helper for lowering intrinsics that follow a target calling 9168 /// convention or require stack pointer adjustment. Only a subset of the 9169 /// intrinsic's operands need to participate in the calling convention. 9170 void SelectionDAGBuilder::populateCallLoweringInfo( 9171 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9172 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9173 bool IsPatchPoint) { 9174 TargetLowering::ArgListTy Args; 9175 Args.reserve(NumArgs); 9176 9177 // Populate the argument list. 9178 // Attributes for args start at offset 1, after the return attribute. 9179 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9180 ArgI != ArgE; ++ArgI) { 9181 const Value *V = Call->getOperand(ArgI); 9182 9183 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9184 9185 TargetLowering::ArgListEntry Entry; 9186 Entry.Node = getValue(V); 9187 Entry.Ty = V->getType(); 9188 Entry.setAttributes(Call, ArgI); 9189 Args.push_back(Entry); 9190 } 9191 9192 CLI.setDebugLoc(getCurSDLoc()) 9193 .setChain(getRoot()) 9194 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9195 .setDiscardResult(Call->use_empty()) 9196 .setIsPatchPoint(IsPatchPoint) 9197 .setIsPreallocated( 9198 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9199 } 9200 9201 /// Add a stack map intrinsic call's live variable operands to a stackmap 9202 /// or patchpoint target node's operand list. 9203 /// 9204 /// Constants are converted to TargetConstants purely as an optimization to 9205 /// avoid constant materialization and register allocation. 9206 /// 9207 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9208 /// generate addess computation nodes, and so FinalizeISel can convert the 9209 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9210 /// address materialization and register allocation, but may also be required 9211 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9212 /// alloca in the entry block, then the runtime may assume that the alloca's 9213 /// StackMap location can be read immediately after compilation and that the 9214 /// location is valid at any point during execution (this is similar to the 9215 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9216 /// only available in a register, then the runtime would need to trap when 9217 /// execution reaches the StackMap in order to read the alloca's location. 9218 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9219 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9220 SelectionDAGBuilder &Builder) { 9221 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 9222 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 9223 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 9224 Ops.push_back( 9225 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 9226 Ops.push_back( 9227 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 9228 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 9229 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 9230 Ops.push_back(Builder.DAG.getTargetFrameIndex( 9231 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 9232 } else 9233 Ops.push_back(OpVal); 9234 } 9235 } 9236 9237 /// Lower llvm.experimental.stackmap directly to its target opcode. 9238 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9239 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 9240 // [live variables...]) 9241 9242 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9243 9244 SDValue Chain, InFlag, Callee, NullPtr; 9245 SmallVector<SDValue, 32> Ops; 9246 9247 SDLoc DL = getCurSDLoc(); 9248 Callee = getValue(CI.getCalledOperand()); 9249 NullPtr = DAG.getIntPtrConstant(0, DL, true); 9250 9251 // The stackmap intrinsic only records the live variables (the arguments 9252 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9253 // intrinsic, this won't be lowered to a function call. This means we don't 9254 // have to worry about calling conventions and target specific lowering code. 9255 // Instead we perform the call lowering right here. 9256 // 9257 // chain, flag = CALLSEQ_START(chain, 0, 0) 9258 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9259 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9260 // 9261 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9262 InFlag = Chain.getValue(1); 9263 9264 // Add the <id> and <numBytes> constants. 9265 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9266 Ops.push_back(DAG.getTargetConstant( 9267 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9268 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9269 Ops.push_back(DAG.getTargetConstant( 9270 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9271 MVT::i32)); 9272 9273 // Push live variables for the stack map. 9274 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9275 9276 // We are not pushing any register mask info here on the operands list, 9277 // because the stackmap doesn't clobber anything. 9278 9279 // Push the chain and the glue flag. 9280 Ops.push_back(Chain); 9281 Ops.push_back(InFlag); 9282 9283 // Create the STACKMAP node. 9284 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9285 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9286 Chain = SDValue(SM, 0); 9287 InFlag = Chain.getValue(1); 9288 9289 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9290 9291 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9292 9293 // Set the root to the target-lowered call chain. 9294 DAG.setRoot(Chain); 9295 9296 // Inform the Frame Information that we have a stackmap in this function. 9297 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9298 } 9299 9300 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9301 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9302 const BasicBlock *EHPadBB) { 9303 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9304 // i32 <numBytes>, 9305 // i8* <target>, 9306 // i32 <numArgs>, 9307 // [Args...], 9308 // [live variables...]) 9309 9310 CallingConv::ID CC = CB.getCallingConv(); 9311 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9312 bool HasDef = !CB.getType()->isVoidTy(); 9313 SDLoc dl = getCurSDLoc(); 9314 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9315 9316 // Handle immediate and symbolic callees. 9317 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9318 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9319 /*isTarget=*/true); 9320 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9321 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9322 SDLoc(SymbolicCallee), 9323 SymbolicCallee->getValueType(0)); 9324 9325 // Get the real number of arguments participating in the call <numArgs> 9326 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9327 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9328 9329 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9330 // Intrinsics include all meta-operands up to but not including CC. 9331 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9332 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9333 "Not enough arguments provided to the patchpoint intrinsic"); 9334 9335 // For AnyRegCC the arguments are lowered later on manually. 9336 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9337 Type *ReturnTy = 9338 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9339 9340 TargetLowering::CallLoweringInfo CLI(DAG); 9341 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9342 ReturnTy, true); 9343 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9344 9345 SDNode *CallEnd = Result.second.getNode(); 9346 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9347 CallEnd = CallEnd->getOperand(0).getNode(); 9348 9349 /// Get a call instruction from the call sequence chain. 9350 /// Tail calls are not allowed. 9351 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9352 "Expected a callseq node."); 9353 SDNode *Call = CallEnd->getOperand(0).getNode(); 9354 bool HasGlue = Call->getGluedNode(); 9355 9356 // Replace the target specific call node with the patchable intrinsic. 9357 SmallVector<SDValue, 8> Ops; 9358 9359 // Add the <id> and <numBytes> constants. 9360 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9361 Ops.push_back(DAG.getTargetConstant( 9362 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9363 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9364 Ops.push_back(DAG.getTargetConstant( 9365 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9366 MVT::i32)); 9367 9368 // Add the callee. 9369 Ops.push_back(Callee); 9370 9371 // Adjust <numArgs> to account for any arguments that have been passed on the 9372 // stack instead. 9373 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9374 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9375 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9376 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9377 9378 // Add the calling convention 9379 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9380 9381 // Add the arguments we omitted previously. The register allocator should 9382 // place these in any free register. 9383 if (IsAnyRegCC) 9384 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9385 Ops.push_back(getValue(CB.getArgOperand(i))); 9386 9387 // Push the arguments from the call instruction up to the register mask. 9388 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9389 Ops.append(Call->op_begin() + 2, e); 9390 9391 // Push live variables for the stack map. 9392 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9393 9394 // Push the register mask info. 9395 if (HasGlue) 9396 Ops.push_back(*(Call->op_end()-2)); 9397 else 9398 Ops.push_back(*(Call->op_end()-1)); 9399 9400 // Push the chain (this is originally the first operand of the call, but 9401 // becomes now the last or second to last operand). 9402 Ops.push_back(*(Call->op_begin())); 9403 9404 // Push the glue flag (last operand). 9405 if (HasGlue) 9406 Ops.push_back(*(Call->op_end()-1)); 9407 9408 SDVTList NodeTys; 9409 if (IsAnyRegCC && HasDef) { 9410 // Create the return types based on the intrinsic definition 9411 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9412 SmallVector<EVT, 3> ValueVTs; 9413 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9414 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9415 9416 // There is always a chain and a glue type at the end 9417 ValueVTs.push_back(MVT::Other); 9418 ValueVTs.push_back(MVT::Glue); 9419 NodeTys = DAG.getVTList(ValueVTs); 9420 } else 9421 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9422 9423 // Replace the target specific call node with a PATCHPOINT node. 9424 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9425 dl, NodeTys, Ops); 9426 9427 // Update the NodeMap. 9428 if (HasDef) { 9429 if (IsAnyRegCC) 9430 setValue(&CB, SDValue(MN, 0)); 9431 else 9432 setValue(&CB, Result.first); 9433 } 9434 9435 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9436 // call sequence. Furthermore the location of the chain and glue can change 9437 // when the AnyReg calling convention is used and the intrinsic returns a 9438 // value. 9439 if (IsAnyRegCC && HasDef) { 9440 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9441 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9442 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9443 } else 9444 DAG.ReplaceAllUsesWith(Call, MN); 9445 DAG.DeleteNode(Call); 9446 9447 // Inform the Frame Information that we have a patchpoint in this function. 9448 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9449 } 9450 9451 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9452 unsigned Intrinsic) { 9453 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9454 SDValue Op1 = getValue(I.getArgOperand(0)); 9455 SDValue Op2; 9456 if (I.arg_size() > 1) 9457 Op2 = getValue(I.getArgOperand(1)); 9458 SDLoc dl = getCurSDLoc(); 9459 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9460 SDValue Res; 9461 SDNodeFlags SDFlags; 9462 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9463 SDFlags.copyFMF(*FPMO); 9464 9465 switch (Intrinsic) { 9466 case Intrinsic::vector_reduce_fadd: 9467 if (SDFlags.hasAllowReassociation()) 9468 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9469 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9470 SDFlags); 9471 else 9472 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9473 break; 9474 case Intrinsic::vector_reduce_fmul: 9475 if (SDFlags.hasAllowReassociation()) 9476 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9477 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9478 SDFlags); 9479 else 9480 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9481 break; 9482 case Intrinsic::vector_reduce_add: 9483 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9484 break; 9485 case Intrinsic::vector_reduce_mul: 9486 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9487 break; 9488 case Intrinsic::vector_reduce_and: 9489 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9490 break; 9491 case Intrinsic::vector_reduce_or: 9492 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9493 break; 9494 case Intrinsic::vector_reduce_xor: 9495 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9496 break; 9497 case Intrinsic::vector_reduce_smax: 9498 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9499 break; 9500 case Intrinsic::vector_reduce_smin: 9501 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9502 break; 9503 case Intrinsic::vector_reduce_umax: 9504 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9505 break; 9506 case Intrinsic::vector_reduce_umin: 9507 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9508 break; 9509 case Intrinsic::vector_reduce_fmax: 9510 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9511 break; 9512 case Intrinsic::vector_reduce_fmin: 9513 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9514 break; 9515 default: 9516 llvm_unreachable("Unhandled vector reduce intrinsic"); 9517 } 9518 setValue(&I, Res); 9519 } 9520 9521 /// Returns an AttributeList representing the attributes applied to the return 9522 /// value of the given call. 9523 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9524 SmallVector<Attribute::AttrKind, 2> Attrs; 9525 if (CLI.RetSExt) 9526 Attrs.push_back(Attribute::SExt); 9527 if (CLI.RetZExt) 9528 Attrs.push_back(Attribute::ZExt); 9529 if (CLI.IsInReg) 9530 Attrs.push_back(Attribute::InReg); 9531 9532 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9533 Attrs); 9534 } 9535 9536 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9537 /// implementation, which just calls LowerCall. 9538 /// FIXME: When all targets are 9539 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9540 std::pair<SDValue, SDValue> 9541 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9542 // Handle the incoming return values from the call. 9543 CLI.Ins.clear(); 9544 Type *OrigRetTy = CLI.RetTy; 9545 SmallVector<EVT, 4> RetTys; 9546 SmallVector<uint64_t, 4> Offsets; 9547 auto &DL = CLI.DAG.getDataLayout(); 9548 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9549 9550 if (CLI.IsPostTypeLegalization) { 9551 // If we are lowering a libcall after legalization, split the return type. 9552 SmallVector<EVT, 4> OldRetTys; 9553 SmallVector<uint64_t, 4> OldOffsets; 9554 RetTys.swap(OldRetTys); 9555 Offsets.swap(OldOffsets); 9556 9557 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9558 EVT RetVT = OldRetTys[i]; 9559 uint64_t Offset = OldOffsets[i]; 9560 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9561 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9562 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9563 RetTys.append(NumRegs, RegisterVT); 9564 for (unsigned j = 0; j != NumRegs; ++j) 9565 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9566 } 9567 } 9568 9569 SmallVector<ISD::OutputArg, 4> Outs; 9570 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9571 9572 bool CanLowerReturn = 9573 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9574 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9575 9576 SDValue DemoteStackSlot; 9577 int DemoteStackIdx = -100; 9578 if (!CanLowerReturn) { 9579 // FIXME: equivalent assert? 9580 // assert(!CS.hasInAllocaArgument() && 9581 // "sret demotion is incompatible with inalloca"); 9582 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9583 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9584 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9585 DemoteStackIdx = 9586 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9587 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9588 DL.getAllocaAddrSpace()); 9589 9590 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9591 ArgListEntry Entry; 9592 Entry.Node = DemoteStackSlot; 9593 Entry.Ty = StackSlotPtrType; 9594 Entry.IsSExt = false; 9595 Entry.IsZExt = false; 9596 Entry.IsInReg = false; 9597 Entry.IsSRet = true; 9598 Entry.IsNest = false; 9599 Entry.IsByVal = false; 9600 Entry.IsByRef = false; 9601 Entry.IsReturned = false; 9602 Entry.IsSwiftSelf = false; 9603 Entry.IsSwiftAsync = false; 9604 Entry.IsSwiftError = false; 9605 Entry.IsCFGuardTarget = false; 9606 Entry.Alignment = Alignment; 9607 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9608 CLI.NumFixedArgs += 1; 9609 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9610 9611 // sret demotion isn't compatible with tail-calls, since the sret argument 9612 // points into the callers stack frame. 9613 CLI.IsTailCall = false; 9614 } else { 9615 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9616 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9617 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9618 ISD::ArgFlagsTy Flags; 9619 if (NeedsRegBlock) { 9620 Flags.setInConsecutiveRegs(); 9621 if (I == RetTys.size() - 1) 9622 Flags.setInConsecutiveRegsLast(); 9623 } 9624 EVT VT = RetTys[I]; 9625 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9626 CLI.CallConv, VT); 9627 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9628 CLI.CallConv, VT); 9629 for (unsigned i = 0; i != NumRegs; ++i) { 9630 ISD::InputArg MyFlags; 9631 MyFlags.Flags = Flags; 9632 MyFlags.VT = RegisterVT; 9633 MyFlags.ArgVT = VT; 9634 MyFlags.Used = CLI.IsReturnValueUsed; 9635 if (CLI.RetTy->isPointerTy()) { 9636 MyFlags.Flags.setPointer(); 9637 MyFlags.Flags.setPointerAddrSpace( 9638 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9639 } 9640 if (CLI.RetSExt) 9641 MyFlags.Flags.setSExt(); 9642 if (CLI.RetZExt) 9643 MyFlags.Flags.setZExt(); 9644 if (CLI.IsInReg) 9645 MyFlags.Flags.setInReg(); 9646 CLI.Ins.push_back(MyFlags); 9647 } 9648 } 9649 } 9650 9651 // We push in swifterror return as the last element of CLI.Ins. 9652 ArgListTy &Args = CLI.getArgs(); 9653 if (supportSwiftError()) { 9654 for (const ArgListEntry &Arg : Args) { 9655 if (Arg.IsSwiftError) { 9656 ISD::InputArg MyFlags; 9657 MyFlags.VT = getPointerTy(DL); 9658 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9659 MyFlags.Flags.setSwiftError(); 9660 CLI.Ins.push_back(MyFlags); 9661 } 9662 } 9663 } 9664 9665 // Handle all of the outgoing arguments. 9666 CLI.Outs.clear(); 9667 CLI.OutVals.clear(); 9668 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9669 SmallVector<EVT, 4> ValueVTs; 9670 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9671 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9672 Type *FinalType = Args[i].Ty; 9673 if (Args[i].IsByVal) 9674 FinalType = Args[i].IndirectType; 9675 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9676 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9677 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9678 ++Value) { 9679 EVT VT = ValueVTs[Value]; 9680 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9681 SDValue Op = SDValue(Args[i].Node.getNode(), 9682 Args[i].Node.getResNo() + Value); 9683 ISD::ArgFlagsTy Flags; 9684 9685 // Certain targets (such as MIPS), may have a different ABI alignment 9686 // for a type depending on the context. Give the target a chance to 9687 // specify the alignment it wants. 9688 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9689 Flags.setOrigAlign(OriginalAlignment); 9690 9691 if (Args[i].Ty->isPointerTy()) { 9692 Flags.setPointer(); 9693 Flags.setPointerAddrSpace( 9694 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9695 } 9696 if (Args[i].IsZExt) 9697 Flags.setZExt(); 9698 if (Args[i].IsSExt) 9699 Flags.setSExt(); 9700 if (Args[i].IsInReg) { 9701 // If we are using vectorcall calling convention, a structure that is 9702 // passed InReg - is surely an HVA 9703 if (CLI.CallConv == CallingConv::X86_VectorCall && 9704 isa<StructType>(FinalType)) { 9705 // The first value of a structure is marked 9706 if (0 == Value) 9707 Flags.setHvaStart(); 9708 Flags.setHva(); 9709 } 9710 // Set InReg Flag 9711 Flags.setInReg(); 9712 } 9713 if (Args[i].IsSRet) 9714 Flags.setSRet(); 9715 if (Args[i].IsSwiftSelf) 9716 Flags.setSwiftSelf(); 9717 if (Args[i].IsSwiftAsync) 9718 Flags.setSwiftAsync(); 9719 if (Args[i].IsSwiftError) 9720 Flags.setSwiftError(); 9721 if (Args[i].IsCFGuardTarget) 9722 Flags.setCFGuardTarget(); 9723 if (Args[i].IsByVal) 9724 Flags.setByVal(); 9725 if (Args[i].IsByRef) 9726 Flags.setByRef(); 9727 if (Args[i].IsPreallocated) { 9728 Flags.setPreallocated(); 9729 // Set the byval flag for CCAssignFn callbacks that don't know about 9730 // preallocated. This way we can know how many bytes we should've 9731 // allocated and how many bytes a callee cleanup function will pop. If 9732 // we port preallocated to more targets, we'll have to add custom 9733 // preallocated handling in the various CC lowering callbacks. 9734 Flags.setByVal(); 9735 } 9736 if (Args[i].IsInAlloca) { 9737 Flags.setInAlloca(); 9738 // Set the byval flag for CCAssignFn callbacks that don't know about 9739 // inalloca. This way we can know how many bytes we should've allocated 9740 // and how many bytes a callee cleanup function will pop. If we port 9741 // inalloca to more targets, we'll have to add custom inalloca handling 9742 // in the various CC lowering callbacks. 9743 Flags.setByVal(); 9744 } 9745 Align MemAlign; 9746 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9747 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 9748 Flags.setByValSize(FrameSize); 9749 9750 // info is not there but there are cases it cannot get right. 9751 if (auto MA = Args[i].Alignment) 9752 MemAlign = *MA; 9753 else 9754 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 9755 } else if (auto MA = Args[i].Alignment) { 9756 MemAlign = *MA; 9757 } else { 9758 MemAlign = OriginalAlignment; 9759 } 9760 Flags.setMemAlign(MemAlign); 9761 if (Args[i].IsNest) 9762 Flags.setNest(); 9763 if (NeedsRegBlock) 9764 Flags.setInConsecutiveRegs(); 9765 9766 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9767 CLI.CallConv, VT); 9768 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9769 CLI.CallConv, VT); 9770 SmallVector<SDValue, 4> Parts(NumParts); 9771 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9772 9773 if (Args[i].IsSExt) 9774 ExtendKind = ISD::SIGN_EXTEND; 9775 else if (Args[i].IsZExt) 9776 ExtendKind = ISD::ZERO_EXTEND; 9777 9778 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9779 // for now. 9780 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9781 CanLowerReturn) { 9782 assert((CLI.RetTy == Args[i].Ty || 9783 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9784 CLI.RetTy->getPointerAddressSpace() == 9785 Args[i].Ty->getPointerAddressSpace())) && 9786 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9787 // Before passing 'returned' to the target lowering code, ensure that 9788 // either the register MVT and the actual EVT are the same size or that 9789 // the return value and argument are extended in the same way; in these 9790 // cases it's safe to pass the argument register value unchanged as the 9791 // return register value (although it's at the target's option whether 9792 // to do so) 9793 // TODO: allow code generation to take advantage of partially preserved 9794 // registers rather than clobbering the entire register when the 9795 // parameter extension method is not compatible with the return 9796 // extension method 9797 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9798 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9799 CLI.RetZExt == Args[i].IsZExt)) 9800 Flags.setReturned(); 9801 } 9802 9803 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9804 CLI.CallConv, ExtendKind); 9805 9806 for (unsigned j = 0; j != NumParts; ++j) { 9807 // if it isn't first piece, alignment must be 1 9808 // For scalable vectors the scalable part is currently handled 9809 // by individual targets, so we just use the known minimum size here. 9810 ISD::OutputArg MyFlags( 9811 Flags, Parts[j].getValueType().getSimpleVT(), VT, 9812 i < CLI.NumFixedArgs, i, 9813 j * Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9814 if (NumParts > 1 && j == 0) 9815 MyFlags.Flags.setSplit(); 9816 else if (j != 0) { 9817 MyFlags.Flags.setOrigAlign(Align(1)); 9818 if (j == NumParts - 1) 9819 MyFlags.Flags.setSplitEnd(); 9820 } 9821 9822 CLI.Outs.push_back(MyFlags); 9823 CLI.OutVals.push_back(Parts[j]); 9824 } 9825 9826 if (NeedsRegBlock && Value == NumValues - 1) 9827 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9828 } 9829 } 9830 9831 SmallVector<SDValue, 4> InVals; 9832 CLI.Chain = LowerCall(CLI, InVals); 9833 9834 // Update CLI.InVals to use outside of this function. 9835 CLI.InVals = InVals; 9836 9837 // Verify that the target's LowerCall behaved as expected. 9838 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9839 "LowerCall didn't return a valid chain!"); 9840 assert((!CLI.IsTailCall || InVals.empty()) && 9841 "LowerCall emitted a return value for a tail call!"); 9842 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9843 "LowerCall didn't emit the correct number of values!"); 9844 9845 // For a tail call, the return value is merely live-out and there aren't 9846 // any nodes in the DAG representing it. Return a special value to 9847 // indicate that a tail call has been emitted and no more Instructions 9848 // should be processed in the current block. 9849 if (CLI.IsTailCall) { 9850 CLI.DAG.setRoot(CLI.Chain); 9851 return std::make_pair(SDValue(), SDValue()); 9852 } 9853 9854 #ifndef NDEBUG 9855 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9856 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9857 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9858 "LowerCall emitted a value with the wrong type!"); 9859 } 9860 #endif 9861 9862 SmallVector<SDValue, 4> ReturnValues; 9863 if (!CanLowerReturn) { 9864 // The instruction result is the result of loading from the 9865 // hidden sret parameter. 9866 SmallVector<EVT, 1> PVTs; 9867 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9868 9869 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9870 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9871 EVT PtrVT = PVTs[0]; 9872 9873 unsigned NumValues = RetTys.size(); 9874 ReturnValues.resize(NumValues); 9875 SmallVector<SDValue, 4> Chains(NumValues); 9876 9877 // An aggregate return value cannot wrap around the address space, so 9878 // offsets to its parts don't wrap either. 9879 SDNodeFlags Flags; 9880 Flags.setNoUnsignedWrap(true); 9881 9882 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9883 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9884 for (unsigned i = 0; i < NumValues; ++i) { 9885 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9886 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9887 PtrVT), Flags); 9888 SDValue L = CLI.DAG.getLoad( 9889 RetTys[i], CLI.DL, CLI.Chain, Add, 9890 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9891 DemoteStackIdx, Offsets[i]), 9892 HiddenSRetAlign); 9893 ReturnValues[i] = L; 9894 Chains[i] = L.getValue(1); 9895 } 9896 9897 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9898 } else { 9899 // Collect the legal value parts into potentially illegal values 9900 // that correspond to the original function's return values. 9901 Optional<ISD::NodeType> AssertOp; 9902 if (CLI.RetSExt) 9903 AssertOp = ISD::AssertSext; 9904 else if (CLI.RetZExt) 9905 AssertOp = ISD::AssertZext; 9906 unsigned CurReg = 0; 9907 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9908 EVT VT = RetTys[I]; 9909 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9910 CLI.CallConv, VT); 9911 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9912 CLI.CallConv, VT); 9913 9914 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9915 NumRegs, RegisterVT, VT, nullptr, 9916 CLI.CallConv, AssertOp)); 9917 CurReg += NumRegs; 9918 } 9919 9920 // For a function returning void, there is no return value. We can't create 9921 // such a node, so we just return a null return value in that case. In 9922 // that case, nothing will actually look at the value. 9923 if (ReturnValues.empty()) 9924 return std::make_pair(SDValue(), CLI.Chain); 9925 } 9926 9927 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9928 CLI.DAG.getVTList(RetTys), ReturnValues); 9929 return std::make_pair(Res, CLI.Chain); 9930 } 9931 9932 /// Places new result values for the node in Results (their number 9933 /// and types must exactly match those of the original return values of 9934 /// the node), or leaves Results empty, which indicates that the node is not 9935 /// to be custom lowered after all. 9936 void TargetLowering::LowerOperationWrapper(SDNode *N, 9937 SmallVectorImpl<SDValue> &Results, 9938 SelectionDAG &DAG) const { 9939 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9940 9941 if (!Res.getNode()) 9942 return; 9943 9944 // If the original node has one result, take the return value from 9945 // LowerOperation as is. It might not be result number 0. 9946 if (N->getNumValues() == 1) { 9947 Results.push_back(Res); 9948 return; 9949 } 9950 9951 // If the original node has multiple results, then the return node should 9952 // have the same number of results. 9953 assert((N->getNumValues() == Res->getNumValues()) && 9954 "Lowering returned the wrong number of results!"); 9955 9956 // Places new result values base on N result number. 9957 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9958 Results.push_back(Res.getValue(I)); 9959 } 9960 9961 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9962 llvm_unreachable("LowerOperation not implemented for this target!"); 9963 } 9964 9965 void 9966 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9967 SDValue Op = getNonRegisterValue(V); 9968 assert((Op.getOpcode() != ISD::CopyFromReg || 9969 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9970 "Copy from a reg to the same reg!"); 9971 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9972 9973 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9974 // If this is an InlineAsm we have to match the registers required, not the 9975 // notional registers required by the type. 9976 9977 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9978 None); // This is not an ABI copy. 9979 SDValue Chain = DAG.getEntryNode(); 9980 9981 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 9982 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 9983 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 9984 ExtendType = PreferredExtendIt->second; 9985 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9986 PendingExports.push_back(Chain); 9987 } 9988 9989 #include "llvm/CodeGen/SelectionDAGISel.h" 9990 9991 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9992 /// entry block, return true. This includes arguments used by switches, since 9993 /// the switch may expand into multiple basic blocks. 9994 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9995 // With FastISel active, we may be splitting blocks, so force creation 9996 // of virtual registers for all non-dead arguments. 9997 if (FastISel) 9998 return A->use_empty(); 9999 10000 const BasicBlock &Entry = A->getParent()->front(); 10001 for (const User *U : A->users()) 10002 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10003 return false; // Use not in entry block. 10004 10005 return true; 10006 } 10007 10008 using ArgCopyElisionMapTy = 10009 DenseMap<const Argument *, 10010 std::pair<const AllocaInst *, const StoreInst *>>; 10011 10012 /// Scan the entry block of the function in FuncInfo for arguments that look 10013 /// like copies into a local alloca. Record any copied arguments in 10014 /// ArgCopyElisionCandidates. 10015 static void 10016 findArgumentCopyElisionCandidates(const DataLayout &DL, 10017 FunctionLoweringInfo *FuncInfo, 10018 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10019 // Record the state of every static alloca used in the entry block. Argument 10020 // allocas are all used in the entry block, so we need approximately as many 10021 // entries as we have arguments. 10022 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10023 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10024 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10025 StaticAllocas.reserve(NumArgs * 2); 10026 10027 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10028 if (!V) 10029 return nullptr; 10030 V = V->stripPointerCasts(); 10031 const auto *AI = dyn_cast<AllocaInst>(V); 10032 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10033 return nullptr; 10034 auto Iter = StaticAllocas.insert({AI, Unknown}); 10035 return &Iter.first->second; 10036 }; 10037 10038 // Look for stores of arguments to static allocas. Look through bitcasts and 10039 // GEPs to handle type coercions, as long as the alloca is fully initialized 10040 // by the store. Any non-store use of an alloca escapes it and any subsequent 10041 // unanalyzed store might write it. 10042 // FIXME: Handle structs initialized with multiple stores. 10043 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10044 // Look for stores, and handle non-store uses conservatively. 10045 const auto *SI = dyn_cast<StoreInst>(&I); 10046 if (!SI) { 10047 // We will look through cast uses, so ignore them completely. 10048 if (I.isCast()) 10049 continue; 10050 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10051 // to allocas. 10052 if (I.isDebugOrPseudoInst()) 10053 continue; 10054 // This is an unknown instruction. Assume it escapes or writes to all 10055 // static alloca operands. 10056 for (const Use &U : I.operands()) { 10057 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10058 *Info = StaticAllocaInfo::Clobbered; 10059 } 10060 continue; 10061 } 10062 10063 // If the stored value is a static alloca, mark it as escaped. 10064 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10065 *Info = StaticAllocaInfo::Clobbered; 10066 10067 // Check if the destination is a static alloca. 10068 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10069 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10070 if (!Info) 10071 continue; 10072 const AllocaInst *AI = cast<AllocaInst>(Dst); 10073 10074 // Skip allocas that have been initialized or clobbered. 10075 if (*Info != StaticAllocaInfo::Unknown) 10076 continue; 10077 10078 // Check if the stored value is an argument, and that this store fully 10079 // initializes the alloca. 10080 // If the argument type has padding bits we can't directly forward a pointer 10081 // as the upper bits may contain garbage. 10082 // Don't elide copies from the same argument twice. 10083 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10084 const auto *Arg = dyn_cast<Argument>(Val); 10085 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10086 Arg->getType()->isEmptyTy() || 10087 DL.getTypeStoreSize(Arg->getType()) != 10088 DL.getTypeAllocSize(AI->getAllocatedType()) || 10089 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10090 ArgCopyElisionCandidates.count(Arg)) { 10091 *Info = StaticAllocaInfo::Clobbered; 10092 continue; 10093 } 10094 10095 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10096 << '\n'); 10097 10098 // Mark this alloca and store for argument copy elision. 10099 *Info = StaticAllocaInfo::Elidable; 10100 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10101 10102 // Stop scanning if we've seen all arguments. This will happen early in -O0 10103 // builds, which is useful, because -O0 builds have large entry blocks and 10104 // many allocas. 10105 if (ArgCopyElisionCandidates.size() == NumArgs) 10106 break; 10107 } 10108 } 10109 10110 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10111 /// ArgVal is a load from a suitable fixed stack object. 10112 static void tryToElideArgumentCopy( 10113 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10114 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10115 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10116 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10117 SDValue ArgVal, bool &ArgHasUses) { 10118 // Check if this is a load from a fixed stack object. 10119 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10120 if (!LNode) 10121 return; 10122 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10123 if (!FINode) 10124 return; 10125 10126 // Check that the fixed stack object is the right size and alignment. 10127 // Look at the alignment that the user wrote on the alloca instead of looking 10128 // at the stack object. 10129 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10130 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10131 const AllocaInst *AI = ArgCopyIter->second.first; 10132 int FixedIndex = FINode->getIndex(); 10133 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10134 int OldIndex = AllocaIndex; 10135 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10136 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10137 LLVM_DEBUG( 10138 dbgs() << " argument copy elision failed due to bad fixed stack " 10139 "object size\n"); 10140 return; 10141 } 10142 Align RequiredAlignment = AI->getAlign(); 10143 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10144 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10145 "greater than stack argument alignment (" 10146 << DebugStr(RequiredAlignment) << " vs " 10147 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10148 return; 10149 } 10150 10151 // Perform the elision. Delete the old stack object and replace its only use 10152 // in the variable info map. Mark the stack object as mutable. 10153 LLVM_DEBUG({ 10154 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10155 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10156 << '\n'; 10157 }); 10158 MFI.RemoveStackObject(OldIndex); 10159 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10160 AllocaIndex = FixedIndex; 10161 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10162 Chains.push_back(ArgVal.getValue(1)); 10163 10164 // Avoid emitting code for the store implementing the copy. 10165 const StoreInst *SI = ArgCopyIter->second.second; 10166 ElidedArgCopyInstrs.insert(SI); 10167 10168 // Check for uses of the argument again so that we can avoid exporting ArgVal 10169 // if it is't used by anything other than the store. 10170 for (const Value *U : Arg.users()) { 10171 if (U != SI) { 10172 ArgHasUses = true; 10173 break; 10174 } 10175 } 10176 } 10177 10178 void SelectionDAGISel::LowerArguments(const Function &F) { 10179 SelectionDAG &DAG = SDB->DAG; 10180 SDLoc dl = SDB->getCurSDLoc(); 10181 const DataLayout &DL = DAG.getDataLayout(); 10182 SmallVector<ISD::InputArg, 16> Ins; 10183 10184 // In Naked functions we aren't going to save any registers. 10185 if (F.hasFnAttribute(Attribute::Naked)) 10186 return; 10187 10188 if (!FuncInfo->CanLowerReturn) { 10189 // Put in an sret pointer parameter before all the other parameters. 10190 SmallVector<EVT, 1> ValueVTs; 10191 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10192 F.getReturnType()->getPointerTo( 10193 DAG.getDataLayout().getAllocaAddrSpace()), 10194 ValueVTs); 10195 10196 // NOTE: Assuming that a pointer will never break down to more than one VT 10197 // or one register. 10198 ISD::ArgFlagsTy Flags; 10199 Flags.setSRet(); 10200 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10201 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10202 ISD::InputArg::NoArgIndex, 0); 10203 Ins.push_back(RetArg); 10204 } 10205 10206 // Look for stores of arguments to static allocas. Mark such arguments with a 10207 // flag to ask the target to give us the memory location of that argument if 10208 // available. 10209 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10210 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10211 ArgCopyElisionCandidates); 10212 10213 // Set up the incoming argument description vector. 10214 for (const Argument &Arg : F.args()) { 10215 unsigned ArgNo = Arg.getArgNo(); 10216 SmallVector<EVT, 4> ValueVTs; 10217 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10218 bool isArgValueUsed = !Arg.use_empty(); 10219 unsigned PartBase = 0; 10220 Type *FinalType = Arg.getType(); 10221 if (Arg.hasAttribute(Attribute::ByVal)) 10222 FinalType = Arg.getParamByValType(); 10223 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10224 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10225 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10226 Value != NumValues; ++Value) { 10227 EVT VT = ValueVTs[Value]; 10228 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10229 ISD::ArgFlagsTy Flags; 10230 10231 10232 if (Arg.getType()->isPointerTy()) { 10233 Flags.setPointer(); 10234 Flags.setPointerAddrSpace( 10235 cast<PointerType>(Arg.getType())->getAddressSpace()); 10236 } 10237 if (Arg.hasAttribute(Attribute::ZExt)) 10238 Flags.setZExt(); 10239 if (Arg.hasAttribute(Attribute::SExt)) 10240 Flags.setSExt(); 10241 if (Arg.hasAttribute(Attribute::InReg)) { 10242 // If we are using vectorcall calling convention, a structure that is 10243 // passed InReg - is surely an HVA 10244 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10245 isa<StructType>(Arg.getType())) { 10246 // The first value of a structure is marked 10247 if (0 == Value) 10248 Flags.setHvaStart(); 10249 Flags.setHva(); 10250 } 10251 // Set InReg Flag 10252 Flags.setInReg(); 10253 } 10254 if (Arg.hasAttribute(Attribute::StructRet)) 10255 Flags.setSRet(); 10256 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10257 Flags.setSwiftSelf(); 10258 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10259 Flags.setSwiftAsync(); 10260 if (Arg.hasAttribute(Attribute::SwiftError)) 10261 Flags.setSwiftError(); 10262 if (Arg.hasAttribute(Attribute::ByVal)) 10263 Flags.setByVal(); 10264 if (Arg.hasAttribute(Attribute::ByRef)) 10265 Flags.setByRef(); 10266 if (Arg.hasAttribute(Attribute::InAlloca)) { 10267 Flags.setInAlloca(); 10268 // Set the byval flag for CCAssignFn callbacks that don't know about 10269 // inalloca. This way we can know how many bytes we should've allocated 10270 // and how many bytes a callee cleanup function will pop. If we port 10271 // inalloca to more targets, we'll have to add custom inalloca handling 10272 // in the various CC lowering callbacks. 10273 Flags.setByVal(); 10274 } 10275 if (Arg.hasAttribute(Attribute::Preallocated)) { 10276 Flags.setPreallocated(); 10277 // Set the byval flag for CCAssignFn callbacks that don't know about 10278 // preallocated. This way we can know how many bytes we should've 10279 // allocated and how many bytes a callee cleanup function will pop. If 10280 // we port preallocated to more targets, we'll have to add custom 10281 // preallocated handling in the various CC lowering callbacks. 10282 Flags.setByVal(); 10283 } 10284 10285 // Certain targets (such as MIPS), may have a different ABI alignment 10286 // for a type depending on the context. Give the target a chance to 10287 // specify the alignment it wants. 10288 const Align OriginalAlignment( 10289 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10290 Flags.setOrigAlign(OriginalAlignment); 10291 10292 Align MemAlign; 10293 Type *ArgMemTy = nullptr; 10294 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10295 Flags.isByRef()) { 10296 if (!ArgMemTy) 10297 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10298 10299 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10300 10301 // For in-memory arguments, size and alignment should be passed from FE. 10302 // BE will guess if this info is not there but there are cases it cannot 10303 // get right. 10304 if (auto ParamAlign = Arg.getParamStackAlign()) 10305 MemAlign = *ParamAlign; 10306 else if ((ParamAlign = Arg.getParamAlign())) 10307 MemAlign = *ParamAlign; 10308 else 10309 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10310 if (Flags.isByRef()) 10311 Flags.setByRefSize(MemSize); 10312 else 10313 Flags.setByValSize(MemSize); 10314 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10315 MemAlign = *ParamAlign; 10316 } else { 10317 MemAlign = OriginalAlignment; 10318 } 10319 Flags.setMemAlign(MemAlign); 10320 10321 if (Arg.hasAttribute(Attribute::Nest)) 10322 Flags.setNest(); 10323 if (NeedsRegBlock) 10324 Flags.setInConsecutiveRegs(); 10325 if (ArgCopyElisionCandidates.count(&Arg)) 10326 Flags.setCopyElisionCandidate(); 10327 if (Arg.hasAttribute(Attribute::Returned)) 10328 Flags.setReturned(); 10329 10330 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10331 *CurDAG->getContext(), F.getCallingConv(), VT); 10332 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10333 *CurDAG->getContext(), F.getCallingConv(), VT); 10334 for (unsigned i = 0; i != NumRegs; ++i) { 10335 // For scalable vectors, use the minimum size; individual targets 10336 // are responsible for handling scalable vector arguments and 10337 // return values. 10338 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10339 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10340 if (NumRegs > 1 && i == 0) 10341 MyFlags.Flags.setSplit(); 10342 // if it isn't first piece, alignment must be 1 10343 else if (i > 0) { 10344 MyFlags.Flags.setOrigAlign(Align(1)); 10345 if (i == NumRegs - 1) 10346 MyFlags.Flags.setSplitEnd(); 10347 } 10348 Ins.push_back(MyFlags); 10349 } 10350 if (NeedsRegBlock && Value == NumValues - 1) 10351 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10352 PartBase += VT.getStoreSize().getKnownMinSize(); 10353 } 10354 } 10355 10356 // Call the target to set up the argument values. 10357 SmallVector<SDValue, 8> InVals; 10358 SDValue NewRoot = TLI->LowerFormalArguments( 10359 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10360 10361 // Verify that the target's LowerFormalArguments behaved as expected. 10362 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10363 "LowerFormalArguments didn't return a valid chain!"); 10364 assert(InVals.size() == Ins.size() && 10365 "LowerFormalArguments didn't emit the correct number of values!"); 10366 LLVM_DEBUG({ 10367 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10368 assert(InVals[i].getNode() && 10369 "LowerFormalArguments emitted a null value!"); 10370 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10371 "LowerFormalArguments emitted a value with the wrong type!"); 10372 } 10373 }); 10374 10375 // Update the DAG with the new chain value resulting from argument lowering. 10376 DAG.setRoot(NewRoot); 10377 10378 // Set up the argument values. 10379 unsigned i = 0; 10380 if (!FuncInfo->CanLowerReturn) { 10381 // Create a virtual register for the sret pointer, and put in a copy 10382 // from the sret argument into it. 10383 SmallVector<EVT, 1> ValueVTs; 10384 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10385 F.getReturnType()->getPointerTo( 10386 DAG.getDataLayout().getAllocaAddrSpace()), 10387 ValueVTs); 10388 MVT VT = ValueVTs[0].getSimpleVT(); 10389 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10390 Optional<ISD::NodeType> AssertOp = None; 10391 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10392 nullptr, F.getCallingConv(), AssertOp); 10393 10394 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10395 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10396 Register SRetReg = 10397 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10398 FuncInfo->DemoteRegister = SRetReg; 10399 NewRoot = 10400 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10401 DAG.setRoot(NewRoot); 10402 10403 // i indexes lowered arguments. Bump it past the hidden sret argument. 10404 ++i; 10405 } 10406 10407 SmallVector<SDValue, 4> Chains; 10408 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10409 for (const Argument &Arg : F.args()) { 10410 SmallVector<SDValue, 4> ArgValues; 10411 SmallVector<EVT, 4> ValueVTs; 10412 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10413 unsigned NumValues = ValueVTs.size(); 10414 if (NumValues == 0) 10415 continue; 10416 10417 bool ArgHasUses = !Arg.use_empty(); 10418 10419 // Elide the copying store if the target loaded this argument from a 10420 // suitable fixed stack object. 10421 if (Ins[i].Flags.isCopyElisionCandidate()) { 10422 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10423 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10424 InVals[i], ArgHasUses); 10425 } 10426 10427 // If this argument is unused then remember its value. It is used to generate 10428 // debugging information. 10429 bool isSwiftErrorArg = 10430 TLI->supportSwiftError() && 10431 Arg.hasAttribute(Attribute::SwiftError); 10432 if (!ArgHasUses && !isSwiftErrorArg) { 10433 SDB->setUnusedArgValue(&Arg, InVals[i]); 10434 10435 // Also remember any frame index for use in FastISel. 10436 if (FrameIndexSDNode *FI = 10437 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10438 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10439 } 10440 10441 for (unsigned Val = 0; Val != NumValues; ++Val) { 10442 EVT VT = ValueVTs[Val]; 10443 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10444 F.getCallingConv(), VT); 10445 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10446 *CurDAG->getContext(), F.getCallingConv(), VT); 10447 10448 // Even an apparent 'unused' swifterror argument needs to be returned. So 10449 // we do generate a copy for it that can be used on return from the 10450 // function. 10451 if (ArgHasUses || isSwiftErrorArg) { 10452 Optional<ISD::NodeType> AssertOp; 10453 if (Arg.hasAttribute(Attribute::SExt)) 10454 AssertOp = ISD::AssertSext; 10455 else if (Arg.hasAttribute(Attribute::ZExt)) 10456 AssertOp = ISD::AssertZext; 10457 10458 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10459 PartVT, VT, nullptr, 10460 F.getCallingConv(), AssertOp)); 10461 } 10462 10463 i += NumParts; 10464 } 10465 10466 // We don't need to do anything else for unused arguments. 10467 if (ArgValues.empty()) 10468 continue; 10469 10470 // Note down frame index. 10471 if (FrameIndexSDNode *FI = 10472 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10473 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10474 10475 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10476 SDB->getCurSDLoc()); 10477 10478 SDB->setValue(&Arg, Res); 10479 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10480 // We want to associate the argument with the frame index, among 10481 // involved operands, that correspond to the lowest address. The 10482 // getCopyFromParts function, called earlier, is swapping the order of 10483 // the operands to BUILD_PAIR depending on endianness. The result of 10484 // that swapping is that the least significant bits of the argument will 10485 // be in the first operand of the BUILD_PAIR node, and the most 10486 // significant bits will be in the second operand. 10487 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10488 if (LoadSDNode *LNode = 10489 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10490 if (FrameIndexSDNode *FI = 10491 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10492 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10493 } 10494 10495 // Analyses past this point are naive and don't expect an assertion. 10496 if (Res.getOpcode() == ISD::AssertZext) 10497 Res = Res.getOperand(0); 10498 10499 // Update the SwiftErrorVRegDefMap. 10500 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10501 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10502 if (Register::isVirtualRegister(Reg)) 10503 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10504 Reg); 10505 } 10506 10507 // If this argument is live outside of the entry block, insert a copy from 10508 // wherever we got it to the vreg that other BB's will reference it as. 10509 if (Res.getOpcode() == ISD::CopyFromReg) { 10510 // If we can, though, try to skip creating an unnecessary vreg. 10511 // FIXME: This isn't very clean... it would be nice to make this more 10512 // general. 10513 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10514 if (Register::isVirtualRegister(Reg)) { 10515 FuncInfo->ValueMap[&Arg] = Reg; 10516 continue; 10517 } 10518 } 10519 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10520 FuncInfo->InitializeRegForValue(&Arg); 10521 SDB->CopyToExportRegsIfNeeded(&Arg); 10522 } 10523 } 10524 10525 if (!Chains.empty()) { 10526 Chains.push_back(NewRoot); 10527 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10528 } 10529 10530 DAG.setRoot(NewRoot); 10531 10532 assert(i == InVals.size() && "Argument register count mismatch!"); 10533 10534 // If any argument copy elisions occurred and we have debug info, update the 10535 // stale frame indices used in the dbg.declare variable info table. 10536 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10537 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10538 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10539 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10540 if (I != ArgCopyElisionFrameIndexMap.end()) 10541 VI.Slot = I->second; 10542 } 10543 } 10544 10545 // Finally, if the target has anything special to do, allow it to do so. 10546 emitFunctionEntryCode(); 10547 } 10548 10549 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10550 /// ensure constants are generated when needed. Remember the virtual registers 10551 /// that need to be added to the Machine PHI nodes as input. We cannot just 10552 /// directly add them, because expansion might result in multiple MBB's for one 10553 /// BB. As such, the start of the BB might correspond to a different MBB than 10554 /// the end. 10555 void 10556 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10557 const Instruction *TI = LLVMBB->getTerminator(); 10558 10559 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10560 10561 // Check PHI nodes in successors that expect a value to be available from this 10562 // block. 10563 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10564 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10565 if (!isa<PHINode>(SuccBB->begin())) continue; 10566 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10567 10568 // If this terminator has multiple identical successors (common for 10569 // switches), only handle each succ once. 10570 if (!SuccsHandled.insert(SuccMBB).second) 10571 continue; 10572 10573 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10574 10575 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10576 // nodes and Machine PHI nodes, but the incoming operands have not been 10577 // emitted yet. 10578 for (const PHINode &PN : SuccBB->phis()) { 10579 // Ignore dead phi's. 10580 if (PN.use_empty()) 10581 continue; 10582 10583 // Skip empty types 10584 if (PN.getType()->isEmptyTy()) 10585 continue; 10586 10587 unsigned Reg; 10588 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10589 10590 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10591 unsigned &RegOut = ConstantsOut[C]; 10592 if (RegOut == 0) { 10593 RegOut = FuncInfo.CreateRegs(C); 10594 CopyValueToVirtualRegister(C, RegOut); 10595 } 10596 Reg = RegOut; 10597 } else { 10598 DenseMap<const Value *, Register>::iterator I = 10599 FuncInfo.ValueMap.find(PHIOp); 10600 if (I != FuncInfo.ValueMap.end()) 10601 Reg = I->second; 10602 else { 10603 assert(isa<AllocaInst>(PHIOp) && 10604 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10605 "Didn't codegen value into a register!??"); 10606 Reg = FuncInfo.CreateRegs(PHIOp); 10607 CopyValueToVirtualRegister(PHIOp, Reg); 10608 } 10609 } 10610 10611 // Remember that this register needs to added to the machine PHI node as 10612 // the input for this MBB. 10613 SmallVector<EVT, 4> ValueVTs; 10614 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10615 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10616 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10617 EVT VT = ValueVTs[vti]; 10618 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10619 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10620 FuncInfo.PHINodesToUpdate.push_back( 10621 std::make_pair(&*MBBI++, Reg + i)); 10622 Reg += NumRegisters; 10623 } 10624 } 10625 } 10626 10627 ConstantsOut.clear(); 10628 } 10629 10630 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10631 MachineFunction::iterator I(MBB); 10632 if (++I == FuncInfo.MF->end()) 10633 return nullptr; 10634 return &*I; 10635 } 10636 10637 /// During lowering new call nodes can be created (such as memset, etc.). 10638 /// Those will become new roots of the current DAG, but complications arise 10639 /// when they are tail calls. In such cases, the call lowering will update 10640 /// the root, but the builder still needs to know that a tail call has been 10641 /// lowered in order to avoid generating an additional return. 10642 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10643 // If the node is null, we do have a tail call. 10644 if (MaybeTC.getNode() != nullptr) 10645 DAG.setRoot(MaybeTC); 10646 else 10647 HasTailCall = true; 10648 } 10649 10650 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10651 MachineBasicBlock *SwitchMBB, 10652 MachineBasicBlock *DefaultMBB) { 10653 MachineFunction *CurMF = FuncInfo.MF; 10654 MachineBasicBlock *NextMBB = nullptr; 10655 MachineFunction::iterator BBI(W.MBB); 10656 if (++BBI != FuncInfo.MF->end()) 10657 NextMBB = &*BBI; 10658 10659 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10660 10661 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10662 10663 if (Size == 2 && W.MBB == SwitchMBB) { 10664 // If any two of the cases has the same destination, and if one value 10665 // is the same as the other, but has one bit unset that the other has set, 10666 // use bit manipulation to do two compares at once. For example: 10667 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10668 // TODO: This could be extended to merge any 2 cases in switches with 3 10669 // cases. 10670 // TODO: Handle cases where W.CaseBB != SwitchBB. 10671 CaseCluster &Small = *W.FirstCluster; 10672 CaseCluster &Big = *W.LastCluster; 10673 10674 if (Small.Low == Small.High && Big.Low == Big.High && 10675 Small.MBB == Big.MBB) { 10676 const APInt &SmallValue = Small.Low->getValue(); 10677 const APInt &BigValue = Big.Low->getValue(); 10678 10679 // Check that there is only one bit different. 10680 APInt CommonBit = BigValue ^ SmallValue; 10681 if (CommonBit.isPowerOf2()) { 10682 SDValue CondLHS = getValue(Cond); 10683 EVT VT = CondLHS.getValueType(); 10684 SDLoc DL = getCurSDLoc(); 10685 10686 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10687 DAG.getConstant(CommonBit, DL, VT)); 10688 SDValue Cond = DAG.getSetCC( 10689 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10690 ISD::SETEQ); 10691 10692 // Update successor info. 10693 // Both Small and Big will jump to Small.BB, so we sum up the 10694 // probabilities. 10695 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10696 if (BPI) 10697 addSuccessorWithProb( 10698 SwitchMBB, DefaultMBB, 10699 // The default destination is the first successor in IR. 10700 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10701 else 10702 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10703 10704 // Insert the true branch. 10705 SDValue BrCond = 10706 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10707 DAG.getBasicBlock(Small.MBB)); 10708 // Insert the false branch. 10709 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10710 DAG.getBasicBlock(DefaultMBB)); 10711 10712 DAG.setRoot(BrCond); 10713 return; 10714 } 10715 } 10716 } 10717 10718 if (TM.getOptLevel() != CodeGenOpt::None) { 10719 // Here, we order cases by probability so the most likely case will be 10720 // checked first. However, two clusters can have the same probability in 10721 // which case their relative ordering is non-deterministic. So we use Low 10722 // as a tie-breaker as clusters are guaranteed to never overlap. 10723 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10724 [](const CaseCluster &a, const CaseCluster &b) { 10725 return a.Prob != b.Prob ? 10726 a.Prob > b.Prob : 10727 a.Low->getValue().slt(b.Low->getValue()); 10728 }); 10729 10730 // Rearrange the case blocks so that the last one falls through if possible 10731 // without changing the order of probabilities. 10732 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10733 --I; 10734 if (I->Prob > W.LastCluster->Prob) 10735 break; 10736 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10737 std::swap(*I, *W.LastCluster); 10738 break; 10739 } 10740 } 10741 } 10742 10743 // Compute total probability. 10744 BranchProbability DefaultProb = W.DefaultProb; 10745 BranchProbability UnhandledProbs = DefaultProb; 10746 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10747 UnhandledProbs += I->Prob; 10748 10749 MachineBasicBlock *CurMBB = W.MBB; 10750 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10751 bool FallthroughUnreachable = false; 10752 MachineBasicBlock *Fallthrough; 10753 if (I == W.LastCluster) { 10754 // For the last cluster, fall through to the default destination. 10755 Fallthrough = DefaultMBB; 10756 FallthroughUnreachable = isa<UnreachableInst>( 10757 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10758 } else { 10759 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10760 CurMF->insert(BBI, Fallthrough); 10761 // Put Cond in a virtual register to make it available from the new blocks. 10762 ExportFromCurrentBlock(Cond); 10763 } 10764 UnhandledProbs -= I->Prob; 10765 10766 switch (I->Kind) { 10767 case CC_JumpTable: { 10768 // FIXME: Optimize away range check based on pivot comparisons. 10769 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10770 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10771 10772 // The jump block hasn't been inserted yet; insert it here. 10773 MachineBasicBlock *JumpMBB = JT->MBB; 10774 CurMF->insert(BBI, JumpMBB); 10775 10776 auto JumpProb = I->Prob; 10777 auto FallthroughProb = UnhandledProbs; 10778 10779 // If the default statement is a target of the jump table, we evenly 10780 // distribute the default probability to successors of CurMBB. Also 10781 // update the probability on the edge from JumpMBB to Fallthrough. 10782 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10783 SE = JumpMBB->succ_end(); 10784 SI != SE; ++SI) { 10785 if (*SI == DefaultMBB) { 10786 JumpProb += DefaultProb / 2; 10787 FallthroughProb -= DefaultProb / 2; 10788 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10789 JumpMBB->normalizeSuccProbs(); 10790 break; 10791 } 10792 } 10793 10794 if (FallthroughUnreachable) 10795 JTH->FallthroughUnreachable = true; 10796 10797 if (!JTH->FallthroughUnreachable) 10798 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10799 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10800 CurMBB->normalizeSuccProbs(); 10801 10802 // The jump table header will be inserted in our current block, do the 10803 // range check, and fall through to our fallthrough block. 10804 JTH->HeaderBB = CurMBB; 10805 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10806 10807 // If we're in the right place, emit the jump table header right now. 10808 if (CurMBB == SwitchMBB) { 10809 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10810 JTH->Emitted = true; 10811 } 10812 break; 10813 } 10814 case CC_BitTests: { 10815 // FIXME: Optimize away range check based on pivot comparisons. 10816 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10817 10818 // The bit test blocks haven't been inserted yet; insert them here. 10819 for (BitTestCase &BTC : BTB->Cases) 10820 CurMF->insert(BBI, BTC.ThisBB); 10821 10822 // Fill in fields of the BitTestBlock. 10823 BTB->Parent = CurMBB; 10824 BTB->Default = Fallthrough; 10825 10826 BTB->DefaultProb = UnhandledProbs; 10827 // If the cases in bit test don't form a contiguous range, we evenly 10828 // distribute the probability on the edge to Fallthrough to two 10829 // successors of CurMBB. 10830 if (!BTB->ContiguousRange) { 10831 BTB->Prob += DefaultProb / 2; 10832 BTB->DefaultProb -= DefaultProb / 2; 10833 } 10834 10835 if (FallthroughUnreachable) 10836 BTB->FallthroughUnreachable = true; 10837 10838 // If we're in the right place, emit the bit test header right now. 10839 if (CurMBB == SwitchMBB) { 10840 visitBitTestHeader(*BTB, SwitchMBB); 10841 BTB->Emitted = true; 10842 } 10843 break; 10844 } 10845 case CC_Range: { 10846 const Value *RHS, *LHS, *MHS; 10847 ISD::CondCode CC; 10848 if (I->Low == I->High) { 10849 // Check Cond == I->Low. 10850 CC = ISD::SETEQ; 10851 LHS = Cond; 10852 RHS=I->Low; 10853 MHS = nullptr; 10854 } else { 10855 // Check I->Low <= Cond <= I->High. 10856 CC = ISD::SETLE; 10857 LHS = I->Low; 10858 MHS = Cond; 10859 RHS = I->High; 10860 } 10861 10862 // If Fallthrough is unreachable, fold away the comparison. 10863 if (FallthroughUnreachable) 10864 CC = ISD::SETTRUE; 10865 10866 // The false probability is the sum of all unhandled cases. 10867 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10868 getCurSDLoc(), I->Prob, UnhandledProbs); 10869 10870 if (CurMBB == SwitchMBB) 10871 visitSwitchCase(CB, SwitchMBB); 10872 else 10873 SL->SwitchCases.push_back(CB); 10874 10875 break; 10876 } 10877 } 10878 CurMBB = Fallthrough; 10879 } 10880 } 10881 10882 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10883 CaseClusterIt First, 10884 CaseClusterIt Last) { 10885 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10886 if (X.Prob != CC.Prob) 10887 return X.Prob > CC.Prob; 10888 10889 // Ties are broken by comparing the case value. 10890 return X.Low->getValue().slt(CC.Low->getValue()); 10891 }); 10892 } 10893 10894 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10895 const SwitchWorkListItem &W, 10896 Value *Cond, 10897 MachineBasicBlock *SwitchMBB) { 10898 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10899 "Clusters not sorted?"); 10900 10901 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10902 10903 // Balance the tree based on branch probabilities to create a near-optimal (in 10904 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10905 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10906 CaseClusterIt LastLeft = W.FirstCluster; 10907 CaseClusterIt FirstRight = W.LastCluster; 10908 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10909 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10910 10911 // Move LastLeft and FirstRight towards each other from opposite directions to 10912 // find a partitioning of the clusters which balances the probability on both 10913 // sides. If LeftProb and RightProb are equal, alternate which side is 10914 // taken to ensure 0-probability nodes are distributed evenly. 10915 unsigned I = 0; 10916 while (LastLeft + 1 < FirstRight) { 10917 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10918 LeftProb += (++LastLeft)->Prob; 10919 else 10920 RightProb += (--FirstRight)->Prob; 10921 I++; 10922 } 10923 10924 while (true) { 10925 // Our binary search tree differs from a typical BST in that ours can have up 10926 // to three values in each leaf. The pivot selection above doesn't take that 10927 // into account, which means the tree might require more nodes and be less 10928 // efficient. We compensate for this here. 10929 10930 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10931 unsigned NumRight = W.LastCluster - FirstRight + 1; 10932 10933 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10934 // If one side has less than 3 clusters, and the other has more than 3, 10935 // consider taking a cluster from the other side. 10936 10937 if (NumLeft < NumRight) { 10938 // Consider moving the first cluster on the right to the left side. 10939 CaseCluster &CC = *FirstRight; 10940 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10941 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10942 if (LeftSideRank <= RightSideRank) { 10943 // Moving the cluster to the left does not demote it. 10944 ++LastLeft; 10945 ++FirstRight; 10946 continue; 10947 } 10948 } else { 10949 assert(NumRight < NumLeft); 10950 // Consider moving the last element on the left to the right side. 10951 CaseCluster &CC = *LastLeft; 10952 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10953 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10954 if (RightSideRank <= LeftSideRank) { 10955 // Moving the cluster to the right does not demot it. 10956 --LastLeft; 10957 --FirstRight; 10958 continue; 10959 } 10960 } 10961 } 10962 break; 10963 } 10964 10965 assert(LastLeft + 1 == FirstRight); 10966 assert(LastLeft >= W.FirstCluster); 10967 assert(FirstRight <= W.LastCluster); 10968 10969 // Use the first element on the right as pivot since we will make less-than 10970 // comparisons against it. 10971 CaseClusterIt PivotCluster = FirstRight; 10972 assert(PivotCluster > W.FirstCluster); 10973 assert(PivotCluster <= W.LastCluster); 10974 10975 CaseClusterIt FirstLeft = W.FirstCluster; 10976 CaseClusterIt LastRight = W.LastCluster; 10977 10978 const ConstantInt *Pivot = PivotCluster->Low; 10979 10980 // New blocks will be inserted immediately after the current one. 10981 MachineFunction::iterator BBI(W.MBB); 10982 ++BBI; 10983 10984 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10985 // we can branch to its destination directly if it's squeezed exactly in 10986 // between the known lower bound and Pivot - 1. 10987 MachineBasicBlock *LeftMBB; 10988 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10989 FirstLeft->Low == W.GE && 10990 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10991 LeftMBB = FirstLeft->MBB; 10992 } else { 10993 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10994 FuncInfo.MF->insert(BBI, LeftMBB); 10995 WorkList.push_back( 10996 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10997 // Put Cond in a virtual register to make it available from the new blocks. 10998 ExportFromCurrentBlock(Cond); 10999 } 11000 11001 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11002 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11003 // directly if RHS.High equals the current upper bound. 11004 MachineBasicBlock *RightMBB; 11005 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11006 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11007 RightMBB = FirstRight->MBB; 11008 } else { 11009 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11010 FuncInfo.MF->insert(BBI, RightMBB); 11011 WorkList.push_back( 11012 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11013 // Put Cond in a virtual register to make it available from the new blocks. 11014 ExportFromCurrentBlock(Cond); 11015 } 11016 11017 // Create the CaseBlock record that will be used to lower the branch. 11018 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11019 getCurSDLoc(), LeftProb, RightProb); 11020 11021 if (W.MBB == SwitchMBB) 11022 visitSwitchCase(CB, SwitchMBB); 11023 else 11024 SL->SwitchCases.push_back(CB); 11025 } 11026 11027 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11028 // from the swith statement. 11029 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11030 BranchProbability PeeledCaseProb) { 11031 if (PeeledCaseProb == BranchProbability::getOne()) 11032 return BranchProbability::getZero(); 11033 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11034 11035 uint32_t Numerator = CaseProb.getNumerator(); 11036 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11037 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11038 } 11039 11040 // Try to peel the top probability case if it exceeds the threshold. 11041 // Return current MachineBasicBlock for the switch statement if the peeling 11042 // does not occur. 11043 // If the peeling is performed, return the newly created MachineBasicBlock 11044 // for the peeled switch statement. Also update Clusters to remove the peeled 11045 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11046 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11047 const SwitchInst &SI, CaseClusterVector &Clusters, 11048 BranchProbability &PeeledCaseProb) { 11049 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11050 // Don't perform if there is only one cluster or optimizing for size. 11051 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11052 TM.getOptLevel() == CodeGenOpt::None || 11053 SwitchMBB->getParent()->getFunction().hasMinSize()) 11054 return SwitchMBB; 11055 11056 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11057 unsigned PeeledCaseIndex = 0; 11058 bool SwitchPeeled = false; 11059 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11060 CaseCluster &CC = Clusters[Index]; 11061 if (CC.Prob < TopCaseProb) 11062 continue; 11063 TopCaseProb = CC.Prob; 11064 PeeledCaseIndex = Index; 11065 SwitchPeeled = true; 11066 } 11067 if (!SwitchPeeled) 11068 return SwitchMBB; 11069 11070 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11071 << TopCaseProb << "\n"); 11072 11073 // Record the MBB for the peeled switch statement. 11074 MachineFunction::iterator BBI(SwitchMBB); 11075 ++BBI; 11076 MachineBasicBlock *PeeledSwitchMBB = 11077 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11078 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11079 11080 ExportFromCurrentBlock(SI.getCondition()); 11081 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11082 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11083 nullptr, nullptr, TopCaseProb.getCompl()}; 11084 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11085 11086 Clusters.erase(PeeledCaseIt); 11087 for (CaseCluster &CC : Clusters) { 11088 LLVM_DEBUG( 11089 dbgs() << "Scale the probablity for one cluster, before scaling: " 11090 << CC.Prob << "\n"); 11091 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11092 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11093 } 11094 PeeledCaseProb = TopCaseProb; 11095 return PeeledSwitchMBB; 11096 } 11097 11098 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11099 // Extract cases from the switch. 11100 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11101 CaseClusterVector Clusters; 11102 Clusters.reserve(SI.getNumCases()); 11103 for (auto I : SI.cases()) { 11104 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11105 const ConstantInt *CaseVal = I.getCaseValue(); 11106 BranchProbability Prob = 11107 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11108 : BranchProbability(1, SI.getNumCases() + 1); 11109 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11110 } 11111 11112 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11113 11114 // Cluster adjacent cases with the same destination. We do this at all 11115 // optimization levels because it's cheap to do and will make codegen faster 11116 // if there are many clusters. 11117 sortAndRangeify(Clusters); 11118 11119 // The branch probablity of the peeled case. 11120 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11121 MachineBasicBlock *PeeledSwitchMBB = 11122 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11123 11124 // If there is only the default destination, jump there directly. 11125 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11126 if (Clusters.empty()) { 11127 assert(PeeledSwitchMBB == SwitchMBB); 11128 SwitchMBB->addSuccessor(DefaultMBB); 11129 if (DefaultMBB != NextBlock(SwitchMBB)) { 11130 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11131 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11132 } 11133 return; 11134 } 11135 11136 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11137 SL->findBitTestClusters(Clusters, &SI); 11138 11139 LLVM_DEBUG({ 11140 dbgs() << "Case clusters: "; 11141 for (const CaseCluster &C : Clusters) { 11142 if (C.Kind == CC_JumpTable) 11143 dbgs() << "JT:"; 11144 if (C.Kind == CC_BitTests) 11145 dbgs() << "BT:"; 11146 11147 C.Low->getValue().print(dbgs(), true); 11148 if (C.Low != C.High) { 11149 dbgs() << '-'; 11150 C.High->getValue().print(dbgs(), true); 11151 } 11152 dbgs() << ' '; 11153 } 11154 dbgs() << '\n'; 11155 }); 11156 11157 assert(!Clusters.empty()); 11158 SwitchWorkList WorkList; 11159 CaseClusterIt First = Clusters.begin(); 11160 CaseClusterIt Last = Clusters.end() - 1; 11161 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11162 // Scale the branchprobability for DefaultMBB if the peel occurs and 11163 // DefaultMBB is not replaced. 11164 if (PeeledCaseProb != BranchProbability::getZero() && 11165 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11166 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11167 WorkList.push_back( 11168 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11169 11170 while (!WorkList.empty()) { 11171 SwitchWorkListItem W = WorkList.pop_back_val(); 11172 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11173 11174 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11175 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11176 // For optimized builds, lower large range as a balanced binary tree. 11177 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11178 continue; 11179 } 11180 11181 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11182 } 11183 } 11184 11185 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11186 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11187 auto DL = getCurSDLoc(); 11188 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11189 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11190 } 11191 11192 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11193 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11194 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11195 11196 SDLoc DL = getCurSDLoc(); 11197 SDValue V = getValue(I.getOperand(0)); 11198 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11199 11200 if (VT.isScalableVector()) { 11201 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11202 return; 11203 } 11204 11205 // Use VECTOR_SHUFFLE for the fixed-length vector 11206 // to maintain existing behavior. 11207 SmallVector<int, 8> Mask; 11208 unsigned NumElts = VT.getVectorMinNumElements(); 11209 for (unsigned i = 0; i != NumElts; ++i) 11210 Mask.push_back(NumElts - 1 - i); 11211 11212 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11213 } 11214 11215 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11216 SmallVector<EVT, 4> ValueVTs; 11217 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11218 ValueVTs); 11219 unsigned NumValues = ValueVTs.size(); 11220 if (NumValues == 0) return; 11221 11222 SmallVector<SDValue, 4> Values(NumValues); 11223 SDValue Op = getValue(I.getOperand(0)); 11224 11225 for (unsigned i = 0; i != NumValues; ++i) 11226 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11227 SDValue(Op.getNode(), Op.getResNo() + i)); 11228 11229 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11230 DAG.getVTList(ValueVTs), Values)); 11231 } 11232 11233 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11234 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11235 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11236 11237 SDLoc DL = getCurSDLoc(); 11238 SDValue V1 = getValue(I.getOperand(0)); 11239 SDValue V2 = getValue(I.getOperand(1)); 11240 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11241 11242 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11243 if (VT.isScalableVector()) { 11244 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11245 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11246 DAG.getConstant(Imm, DL, IdxVT))); 11247 return; 11248 } 11249 11250 unsigned NumElts = VT.getVectorNumElements(); 11251 11252 uint64_t Idx = (NumElts + Imm) % NumElts; 11253 11254 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11255 SmallVector<int, 8> Mask; 11256 for (unsigned i = 0; i < NumElts; ++i) 11257 Mask.push_back(Idx + i); 11258 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11259 } 11260