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