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, /*LegalTypes*/false)); 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 DL = &DAG.getDataLayout(); 1040 Context = DAG.getContext(); 1041 LPadToCallSiteMap.clear(); 1042 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1043 } 1044 1045 void SelectionDAGBuilder::clear() { 1046 NodeMap.clear(); 1047 UnusedArgNodeMap.clear(); 1048 PendingLoads.clear(); 1049 PendingExports.clear(); 1050 PendingConstrainedFP.clear(); 1051 PendingConstrainedFPStrict.clear(); 1052 CurInst = nullptr; 1053 HasTailCall = false; 1054 SDNodeOrder = LowestSDNodeOrder; 1055 StatepointLowering.clear(); 1056 } 1057 1058 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1059 DanglingDebugInfoMap.clear(); 1060 } 1061 1062 // Update DAG root to include dependencies on Pending chains. 1063 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1064 SDValue Root = DAG.getRoot(); 1065 1066 if (Pending.empty()) 1067 return Root; 1068 1069 // Add current root to PendingChains, unless we already indirectly 1070 // depend on it. 1071 if (Root.getOpcode() != ISD::EntryToken) { 1072 unsigned i = 0, e = Pending.size(); 1073 for (; i != e; ++i) { 1074 assert(Pending[i].getNode()->getNumOperands() > 1); 1075 if (Pending[i].getNode()->getOperand(0) == Root) 1076 break; // Don't add the root if we already indirectly depend on it. 1077 } 1078 1079 if (i == e) 1080 Pending.push_back(Root); 1081 } 1082 1083 if (Pending.size() == 1) 1084 Root = Pending[0]; 1085 else 1086 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1087 1088 DAG.setRoot(Root); 1089 Pending.clear(); 1090 return Root; 1091 } 1092 1093 SDValue SelectionDAGBuilder::getMemoryRoot() { 1094 return updateRoot(PendingLoads); 1095 } 1096 1097 SDValue SelectionDAGBuilder::getRoot() { 1098 // Chain up all pending constrained intrinsics together with all 1099 // pending loads, by simply appending them to PendingLoads and 1100 // then calling getMemoryRoot(). 1101 PendingLoads.reserve(PendingLoads.size() + 1102 PendingConstrainedFP.size() + 1103 PendingConstrainedFPStrict.size()); 1104 PendingLoads.append(PendingConstrainedFP.begin(), 1105 PendingConstrainedFP.end()); 1106 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1107 PendingConstrainedFPStrict.end()); 1108 PendingConstrainedFP.clear(); 1109 PendingConstrainedFPStrict.clear(); 1110 return getMemoryRoot(); 1111 } 1112 1113 SDValue SelectionDAGBuilder::getControlRoot() { 1114 // We need to emit pending fpexcept.strict constrained intrinsics, 1115 // so append them to the PendingExports list. 1116 PendingExports.append(PendingConstrainedFPStrict.begin(), 1117 PendingConstrainedFPStrict.end()); 1118 PendingConstrainedFPStrict.clear(); 1119 return updateRoot(PendingExports); 1120 } 1121 1122 void SelectionDAGBuilder::visit(const Instruction &I) { 1123 // Set up outgoing PHI node register values before emitting the terminator. 1124 if (I.isTerminator()) { 1125 HandlePHINodesInSuccessorBlocks(I.getParent()); 1126 } 1127 1128 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1129 if (!isa<DbgInfoIntrinsic>(I)) 1130 ++SDNodeOrder; 1131 1132 CurInst = &I; 1133 1134 visit(I.getOpcode(), I); 1135 1136 if (!I.isTerminator() && !HasTailCall && 1137 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1138 CopyToExportRegsIfNeeded(&I); 1139 1140 CurInst = nullptr; 1141 } 1142 1143 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1144 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1145 } 1146 1147 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1148 // Note: this doesn't use InstVisitor, because it has to work with 1149 // ConstantExpr's in addition to instructions. 1150 switch (Opcode) { 1151 default: llvm_unreachable("Unknown instruction type encountered!"); 1152 // Build the switch statement using the Instruction.def file. 1153 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1154 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1155 #include "llvm/IR/Instruction.def" 1156 } 1157 } 1158 1159 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1160 DebugLoc DL, unsigned Order) { 1161 // We treat variadic dbg_values differently at this stage. 1162 if (DI->hasArgList()) { 1163 // For variadic dbg_values we will now insert an undef. 1164 // FIXME: We can potentially recover these! 1165 SmallVector<SDDbgOperand, 2> Locs; 1166 for (const Value *V : DI->getValues()) { 1167 auto Undef = UndefValue::get(V->getType()); 1168 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1169 } 1170 SDDbgValue *SDV = DAG.getDbgValueList( 1171 DI->getVariable(), DI->getExpression(), Locs, {}, 1172 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1173 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1174 } else { 1175 // TODO: Dangling debug info will eventually either be resolved or produce 1176 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1177 // between the original dbg.value location and its resolved DBG_VALUE, 1178 // which we should ideally fill with an extra Undef DBG_VALUE. 1179 assert(DI->getNumVariableLocationOps() == 1 && 1180 "DbgValueInst without an ArgList should have a single location " 1181 "operand."); 1182 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1183 } 1184 } 1185 1186 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1187 const DIExpression *Expr) { 1188 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1189 const DbgValueInst *DI = DDI.getDI(); 1190 DIVariable *DanglingVariable = DI->getVariable(); 1191 DIExpression *DanglingExpr = DI->getExpression(); 1192 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1193 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1194 return true; 1195 } 1196 return false; 1197 }; 1198 1199 for (auto &DDIMI : DanglingDebugInfoMap) { 1200 DanglingDebugInfoVector &DDIV = DDIMI.second; 1201 1202 // If debug info is to be dropped, run it through final checks to see 1203 // whether it can be salvaged. 1204 for (auto &DDI : DDIV) 1205 if (isMatchingDbgValue(DDI)) 1206 salvageUnresolvedDbgValue(DDI); 1207 1208 erase_if(DDIV, isMatchingDbgValue); 1209 } 1210 } 1211 1212 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1213 // generate the debug data structures now that we've seen its definition. 1214 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1215 SDValue Val) { 1216 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1217 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1218 return; 1219 1220 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1221 for (auto &DDI : DDIV) { 1222 const DbgValueInst *DI = DDI.getDI(); 1223 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1224 assert(DI && "Ill-formed DanglingDebugInfo"); 1225 DebugLoc dl = DDI.getdl(); 1226 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1227 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1228 DILocalVariable *Variable = DI->getVariable(); 1229 DIExpression *Expr = DI->getExpression(); 1230 assert(Variable->isValidLocationForIntrinsic(dl) && 1231 "Expected inlined-at fields to agree"); 1232 SDDbgValue *SDV; 1233 if (Val.getNode()) { 1234 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1235 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1236 // we couldn't resolve it directly when examining the DbgValue intrinsic 1237 // in the first place we should not be more successful here). Unless we 1238 // have some test case that prove this to be correct we should avoid 1239 // calling EmitFuncArgumentDbgValue here. 1240 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1241 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1242 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1243 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1244 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1245 // inserted after the definition of Val when emitting the instructions 1246 // after ISel. An alternative could be to teach 1247 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1248 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1249 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1250 << ValSDNodeOrder << "\n"); 1251 SDV = getDbgValue(Val, Variable, Expr, dl, 1252 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1253 DAG.AddDbgValue(SDV, false); 1254 } else 1255 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1256 << "in EmitFuncArgumentDbgValue\n"); 1257 } else { 1258 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1259 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1260 auto SDV = 1261 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1262 DAG.AddDbgValue(SDV, false); 1263 } 1264 } 1265 DDIV.clear(); 1266 } 1267 1268 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1269 // TODO: For the variadic implementation, instead of only checking the fail 1270 // state of `handleDebugValue`, we need know specifically which values were 1271 // invalid, so that we attempt to salvage only those values when processing 1272 // a DIArgList. 1273 assert(!DDI.getDI()->hasArgList() && 1274 "Not implemented for variadic dbg_values"); 1275 Value *V = DDI.getDI()->getValue(0); 1276 DILocalVariable *Var = DDI.getDI()->getVariable(); 1277 DIExpression *Expr = DDI.getDI()->getExpression(); 1278 DebugLoc DL = DDI.getdl(); 1279 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1280 unsigned SDOrder = DDI.getSDNodeOrder(); 1281 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1282 // that DW_OP_stack_value is desired. 1283 assert(isa<DbgValueInst>(DDI.getDI())); 1284 bool StackValue = true; 1285 1286 // Can this Value can be encoded without any further work? 1287 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1288 return; 1289 1290 // Attempt to salvage back through as many instructions as possible. Bail if 1291 // a non-instruction is seen, such as a constant expression or global 1292 // variable. FIXME: Further work could recover those too. 1293 while (isa<Instruction>(V)) { 1294 Instruction &VAsInst = *cast<Instruction>(V); 1295 // Temporary "0", awaiting real implementation. 1296 SmallVector<uint64_t, 16> Ops; 1297 SmallVector<Value *, 4> AdditionalValues; 1298 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1299 AdditionalValues); 1300 // If we cannot salvage any further, and haven't yet found a suitable debug 1301 // expression, bail out. 1302 if (!V) 1303 break; 1304 1305 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1306 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1307 // here for variadic dbg_values, remove that condition. 1308 if (!AdditionalValues.empty()) 1309 break; 1310 1311 // New value and expr now represent this debuginfo. 1312 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1313 1314 // Some kind of simplification occurred: check whether the operand of the 1315 // salvaged debug expression can be encoded in this DAG. 1316 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1317 /*IsVariadic=*/false)) { 1318 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1319 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1320 return; 1321 } 1322 } 1323 1324 // This was the final opportunity to salvage this debug information, and it 1325 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1326 // any earlier variable location. 1327 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1328 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1329 DAG.AddDbgValue(SDV, false); 1330 1331 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1332 << "\n"); 1333 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1334 << "\n"); 1335 } 1336 1337 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1338 DILocalVariable *Var, 1339 DIExpression *Expr, DebugLoc dl, 1340 DebugLoc InstDL, unsigned Order, 1341 bool IsVariadic) { 1342 if (Values.empty()) 1343 return true; 1344 SmallVector<SDDbgOperand> LocationOps; 1345 SmallVector<SDNode *> Dependencies; 1346 for (const Value *V : Values) { 1347 // Constant value. 1348 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1349 isa<ConstantPointerNull>(V)) { 1350 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1351 continue; 1352 } 1353 1354 // If the Value is a frame index, we can create a FrameIndex debug value 1355 // without relying on the DAG at all. 1356 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1357 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1358 if (SI != FuncInfo.StaticAllocaMap.end()) { 1359 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1360 continue; 1361 } 1362 } 1363 1364 // Do not use getValue() in here; we don't want to generate code at 1365 // this point if it hasn't been done yet. 1366 SDValue N = NodeMap[V]; 1367 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1368 N = UnusedArgNodeMap[V]; 1369 if (N.getNode()) { 1370 // Only emit func arg dbg value for non-variadic dbg.values for now. 1371 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1372 return true; 1373 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1374 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1375 // describe stack slot locations. 1376 // 1377 // Consider "int x = 0; int *px = &x;". There are two kinds of 1378 // interesting debug values here after optimization: 1379 // 1380 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1381 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1382 // 1383 // Both describe the direct values of their associated variables. 1384 Dependencies.push_back(N.getNode()); 1385 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1386 continue; 1387 } 1388 LocationOps.emplace_back( 1389 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1390 continue; 1391 } 1392 1393 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1394 // Special rules apply for the first dbg.values of parameter variables in a 1395 // function. Identify them by the fact they reference Argument Values, that 1396 // they're parameters, and they are parameters of the current function. We 1397 // need to let them dangle until they get an SDNode. 1398 bool IsParamOfFunc = 1399 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1400 if (IsParamOfFunc) 1401 return false; 1402 1403 // The value is not used in this block yet (or it would have an SDNode). 1404 // We still want the value to appear for the user if possible -- if it has 1405 // an associated VReg, we can refer to that instead. 1406 auto VMI = FuncInfo.ValueMap.find(V); 1407 if (VMI != FuncInfo.ValueMap.end()) { 1408 unsigned Reg = VMI->second; 1409 // If this is a PHI node, it may be split up into several MI PHI nodes 1410 // (in FunctionLoweringInfo::set). 1411 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1412 V->getType(), None); 1413 if (RFV.occupiesMultipleRegs()) { 1414 // FIXME: We could potentially support variadic dbg_values here. 1415 if (IsVariadic) 1416 return false; 1417 unsigned Offset = 0; 1418 unsigned BitsToDescribe = 0; 1419 if (auto VarSize = Var->getSizeInBits()) 1420 BitsToDescribe = *VarSize; 1421 if (auto Fragment = Expr->getFragmentInfo()) 1422 BitsToDescribe = Fragment->SizeInBits; 1423 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1424 // Bail out if all bits are described already. 1425 if (Offset >= BitsToDescribe) 1426 break; 1427 // TODO: handle scalable vectors. 1428 unsigned RegisterSize = RegAndSize.second; 1429 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1430 ? BitsToDescribe - Offset 1431 : RegisterSize; 1432 auto FragmentExpr = DIExpression::createFragmentExpression( 1433 Expr, Offset, FragmentSize); 1434 if (!FragmentExpr) 1435 continue; 1436 SDDbgValue *SDV = DAG.getVRegDbgValue( 1437 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1438 DAG.AddDbgValue(SDV, false); 1439 Offset += RegisterSize; 1440 } 1441 return true; 1442 } 1443 // We can use simple vreg locations for variadic dbg_values as well. 1444 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1445 continue; 1446 } 1447 // We failed to create a SDDbgOperand for V. 1448 return false; 1449 } 1450 1451 // We have created a SDDbgOperand for each Value in Values. 1452 // Should use Order instead of SDNodeOrder? 1453 assert(!LocationOps.empty()); 1454 SDDbgValue *SDV = 1455 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1456 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1457 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1458 return true; 1459 } 1460 1461 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1462 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1463 for (auto &Pair : DanglingDebugInfoMap) 1464 for (auto &DDI : Pair.second) 1465 salvageUnresolvedDbgValue(DDI); 1466 clearDanglingDebugInfo(); 1467 } 1468 1469 /// getCopyFromRegs - If there was virtual register allocated for the value V 1470 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1471 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1472 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1473 SDValue Result; 1474 1475 if (It != FuncInfo.ValueMap.end()) { 1476 Register InReg = It->second; 1477 1478 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1479 DAG.getDataLayout(), InReg, Ty, 1480 None); // This is not an ABI copy. 1481 SDValue Chain = DAG.getEntryNode(); 1482 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1483 V); 1484 resolveDanglingDebugInfo(V, Result); 1485 } 1486 1487 return Result; 1488 } 1489 1490 /// getValue - Return an SDValue for the given Value. 1491 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1492 // If we already have an SDValue for this value, use it. It's important 1493 // to do this first, so that we don't create a CopyFromReg if we already 1494 // have a regular SDValue. 1495 SDValue &N = NodeMap[V]; 1496 if (N.getNode()) return N; 1497 1498 // If there's a virtual register allocated and initialized for this 1499 // value, use it. 1500 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1501 return copyFromReg; 1502 1503 // Otherwise create a new SDValue and remember it. 1504 SDValue Val = getValueImpl(V); 1505 NodeMap[V] = Val; 1506 resolveDanglingDebugInfo(V, Val); 1507 return Val; 1508 } 1509 1510 /// getNonRegisterValue - Return an SDValue for the given Value, but 1511 /// don't look in FuncInfo.ValueMap for a virtual register. 1512 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1513 // If we already have an SDValue for this value, use it. 1514 SDValue &N = NodeMap[V]; 1515 if (N.getNode()) { 1516 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1517 // Remove the debug location from the node as the node is about to be used 1518 // in a location which may differ from the original debug location. This 1519 // is relevant to Constant and ConstantFP nodes because they can appear 1520 // as constant expressions inside PHI nodes. 1521 N->setDebugLoc(DebugLoc()); 1522 } 1523 return N; 1524 } 1525 1526 // Otherwise create a new SDValue and remember it. 1527 SDValue Val = getValueImpl(V); 1528 NodeMap[V] = Val; 1529 resolveDanglingDebugInfo(V, Val); 1530 return Val; 1531 } 1532 1533 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1534 /// Create an SDValue for the given value. 1535 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1536 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1537 1538 if (const Constant *C = dyn_cast<Constant>(V)) { 1539 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1540 1541 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1542 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1543 1544 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1545 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1546 1547 if (isa<ConstantPointerNull>(C)) { 1548 unsigned AS = V->getType()->getPointerAddressSpace(); 1549 return DAG.getConstant(0, getCurSDLoc(), 1550 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1551 } 1552 1553 if (match(C, m_VScale(DAG.getDataLayout()))) 1554 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1555 1556 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1557 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1558 1559 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1560 return DAG.getUNDEF(VT); 1561 1562 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1563 visit(CE->getOpcode(), *CE); 1564 SDValue N1 = NodeMap[V]; 1565 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1566 return N1; 1567 } 1568 1569 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1570 SmallVector<SDValue, 4> Constants; 1571 for (const Use &U : C->operands()) { 1572 SDNode *Val = getValue(U).getNode(); 1573 // If the operand is an empty aggregate, there are no values. 1574 if (!Val) continue; 1575 // Add each leaf value from the operand to the Constants list 1576 // to form a flattened list of all the values. 1577 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1578 Constants.push_back(SDValue(Val, i)); 1579 } 1580 1581 return DAG.getMergeValues(Constants, getCurSDLoc()); 1582 } 1583 1584 if (const ConstantDataSequential *CDS = 1585 dyn_cast<ConstantDataSequential>(C)) { 1586 SmallVector<SDValue, 4> Ops; 1587 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1588 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1589 // Add each leaf value from the operand to the Constants list 1590 // to form a flattened list of all the values. 1591 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1592 Ops.push_back(SDValue(Val, i)); 1593 } 1594 1595 if (isa<ArrayType>(CDS->getType())) 1596 return DAG.getMergeValues(Ops, getCurSDLoc()); 1597 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1598 } 1599 1600 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1601 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1602 "Unknown struct or array constant!"); 1603 1604 SmallVector<EVT, 4> ValueVTs; 1605 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1606 unsigned NumElts = ValueVTs.size(); 1607 if (NumElts == 0) 1608 return SDValue(); // empty struct 1609 SmallVector<SDValue, 4> Constants(NumElts); 1610 for (unsigned i = 0; i != NumElts; ++i) { 1611 EVT EltVT = ValueVTs[i]; 1612 if (isa<UndefValue>(C)) 1613 Constants[i] = DAG.getUNDEF(EltVT); 1614 else if (EltVT.isFloatingPoint()) 1615 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1616 else 1617 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1618 } 1619 1620 return DAG.getMergeValues(Constants, getCurSDLoc()); 1621 } 1622 1623 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1624 return DAG.getBlockAddress(BA, VT); 1625 1626 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1627 return getValue(Equiv->getGlobalValue()); 1628 1629 VectorType *VecTy = cast<VectorType>(V->getType()); 1630 1631 // Now that we know the number and type of the elements, get that number of 1632 // elements into the Ops array based on what kind of constant it is. 1633 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1634 SmallVector<SDValue, 16> Ops; 1635 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1636 for (unsigned i = 0; i != NumElements; ++i) 1637 Ops.push_back(getValue(CV->getOperand(i))); 1638 1639 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1640 } else if (isa<ConstantAggregateZero>(C)) { 1641 EVT EltVT = 1642 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1643 1644 SDValue Op; 1645 if (EltVT.isFloatingPoint()) 1646 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1647 else 1648 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1649 1650 if (isa<ScalableVectorType>(VecTy)) 1651 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1652 else { 1653 SmallVector<SDValue, 16> Ops; 1654 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1655 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1656 } 1657 } 1658 llvm_unreachable("Unknown vector constant"); 1659 } 1660 1661 // If this is a static alloca, generate it as the frameindex instead of 1662 // computation. 1663 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1664 DenseMap<const AllocaInst*, int>::iterator SI = 1665 FuncInfo.StaticAllocaMap.find(AI); 1666 if (SI != FuncInfo.StaticAllocaMap.end()) 1667 return DAG.getFrameIndex(SI->second, 1668 TLI.getFrameIndexTy(DAG.getDataLayout())); 1669 } 1670 1671 // If this is an instruction which fast-isel has deferred, select it now. 1672 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1673 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1674 1675 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1676 Inst->getType(), None); 1677 SDValue Chain = DAG.getEntryNode(); 1678 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1679 } 1680 1681 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1682 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1683 } 1684 llvm_unreachable("Can't get register for value!"); 1685 } 1686 1687 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1688 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1689 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1690 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1691 bool IsSEH = isAsynchronousEHPersonality(Pers); 1692 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1693 if (!IsSEH) 1694 CatchPadMBB->setIsEHScopeEntry(); 1695 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1696 if (IsMSVCCXX || IsCoreCLR) 1697 CatchPadMBB->setIsEHFuncletEntry(); 1698 } 1699 1700 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1701 // Update machine-CFG edge. 1702 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1703 FuncInfo.MBB->addSuccessor(TargetMBB); 1704 TargetMBB->setIsEHCatchretTarget(true); 1705 DAG.getMachineFunction().setHasEHCatchret(true); 1706 1707 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1708 bool IsSEH = isAsynchronousEHPersonality(Pers); 1709 if (IsSEH) { 1710 // If this is not a fall-through branch or optimizations are switched off, 1711 // emit the branch. 1712 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1713 TM.getOptLevel() == CodeGenOpt::None) 1714 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1715 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1716 return; 1717 } 1718 1719 // Figure out the funclet membership for the catchret's successor. 1720 // This will be used by the FuncletLayout pass to determine how to order the 1721 // BB's. 1722 // A 'catchret' returns to the outer scope's color. 1723 Value *ParentPad = I.getCatchSwitchParentPad(); 1724 const BasicBlock *SuccessorColor; 1725 if (isa<ConstantTokenNone>(ParentPad)) 1726 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1727 else 1728 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1729 assert(SuccessorColor && "No parent funclet for catchret!"); 1730 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1731 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1732 1733 // Create the terminator node. 1734 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1735 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1736 DAG.getBasicBlock(SuccessorColorMBB)); 1737 DAG.setRoot(Ret); 1738 } 1739 1740 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1741 // Don't emit any special code for the cleanuppad instruction. It just marks 1742 // the start of an EH scope/funclet. 1743 FuncInfo.MBB->setIsEHScopeEntry(); 1744 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1745 if (Pers != EHPersonality::Wasm_CXX) { 1746 FuncInfo.MBB->setIsEHFuncletEntry(); 1747 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1748 } 1749 } 1750 1751 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1752 // not match, it is OK to add only the first unwind destination catchpad to the 1753 // successors, because there will be at least one invoke instruction within the 1754 // catch scope that points to the next unwind destination, if one exists, so 1755 // CFGSort cannot mess up with BB sorting order. 1756 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1757 // call within them, and catchpads only consisting of 'catch (...)' have a 1758 // '__cxa_end_catch' call within them, both of which generate invokes in case 1759 // the next unwind destination exists, i.e., the next unwind destination is not 1760 // the caller.) 1761 // 1762 // Having at most one EH pad successor is also simpler and helps later 1763 // transformations. 1764 // 1765 // For example, 1766 // current: 1767 // invoke void @foo to ... unwind label %catch.dispatch 1768 // catch.dispatch: 1769 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1770 // catch.start: 1771 // ... 1772 // ... in this BB or some other child BB dominated by this BB there will be an 1773 // invoke that points to 'next' BB as an unwind destination 1774 // 1775 // next: ; We don't need to add this to 'current' BB's successor 1776 // ... 1777 static void findWasmUnwindDestinations( 1778 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1779 BranchProbability Prob, 1780 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1781 &UnwindDests) { 1782 while (EHPadBB) { 1783 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1784 if (isa<CleanupPadInst>(Pad)) { 1785 // Stop on cleanup pads. 1786 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1787 UnwindDests.back().first->setIsEHScopeEntry(); 1788 break; 1789 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1790 // Add the catchpad handlers to the possible destinations. We don't 1791 // continue to the unwind destination of the catchswitch for wasm. 1792 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1793 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1794 UnwindDests.back().first->setIsEHScopeEntry(); 1795 } 1796 break; 1797 } else { 1798 continue; 1799 } 1800 } 1801 } 1802 1803 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1804 /// many places it could ultimately go. In the IR, we have a single unwind 1805 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1806 /// This function skips over imaginary basic blocks that hold catchswitch 1807 /// instructions, and finds all the "real" machine 1808 /// basic block destinations. As those destinations may not be successors of 1809 /// EHPadBB, here we also calculate the edge probability to those destinations. 1810 /// The passed-in Prob is the edge probability to EHPadBB. 1811 static void findUnwindDestinations( 1812 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1813 BranchProbability Prob, 1814 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1815 &UnwindDests) { 1816 EHPersonality Personality = 1817 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1818 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1819 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1820 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1821 bool IsSEH = isAsynchronousEHPersonality(Personality); 1822 1823 if (IsWasmCXX) { 1824 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1825 assert(UnwindDests.size() <= 1 && 1826 "There should be at most one unwind destination for wasm"); 1827 return; 1828 } 1829 1830 while (EHPadBB) { 1831 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1832 BasicBlock *NewEHPadBB = nullptr; 1833 if (isa<LandingPadInst>(Pad)) { 1834 // Stop on landingpads. They are not funclets. 1835 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1836 break; 1837 } else if (isa<CleanupPadInst>(Pad)) { 1838 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1839 // personalities. 1840 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1841 UnwindDests.back().first->setIsEHScopeEntry(); 1842 UnwindDests.back().first->setIsEHFuncletEntry(); 1843 break; 1844 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1845 // Add the catchpad handlers to the possible destinations. 1846 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1847 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1848 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1849 if (IsMSVCCXX || IsCoreCLR) 1850 UnwindDests.back().first->setIsEHFuncletEntry(); 1851 if (!IsSEH) 1852 UnwindDests.back().first->setIsEHScopeEntry(); 1853 } 1854 NewEHPadBB = CatchSwitch->getUnwindDest(); 1855 } else { 1856 continue; 1857 } 1858 1859 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1860 if (BPI && NewEHPadBB) 1861 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1862 EHPadBB = NewEHPadBB; 1863 } 1864 } 1865 1866 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1867 // Update successor info. 1868 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1869 auto UnwindDest = I.getUnwindDest(); 1870 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1871 BranchProbability UnwindDestProb = 1872 (BPI && UnwindDest) 1873 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1874 : BranchProbability::getZero(); 1875 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1876 for (auto &UnwindDest : UnwindDests) { 1877 UnwindDest.first->setIsEHPad(); 1878 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1879 } 1880 FuncInfo.MBB->normalizeSuccProbs(); 1881 1882 // Create the terminator node. 1883 SDValue Ret = 1884 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1885 DAG.setRoot(Ret); 1886 } 1887 1888 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1889 report_fatal_error("visitCatchSwitch not yet implemented!"); 1890 } 1891 1892 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1893 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1894 auto &DL = DAG.getDataLayout(); 1895 SDValue Chain = getControlRoot(); 1896 SmallVector<ISD::OutputArg, 8> Outs; 1897 SmallVector<SDValue, 8> OutVals; 1898 1899 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1900 // lower 1901 // 1902 // %val = call <ty> @llvm.experimental.deoptimize() 1903 // ret <ty> %val 1904 // 1905 // differently. 1906 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1907 LowerDeoptimizingReturn(); 1908 return; 1909 } 1910 1911 if (!FuncInfo.CanLowerReturn) { 1912 unsigned DemoteReg = FuncInfo.DemoteRegister; 1913 const Function *F = I.getParent()->getParent(); 1914 1915 // Emit a store of the return value through the virtual register. 1916 // Leave Outs empty so that LowerReturn won't try to load return 1917 // registers the usual way. 1918 SmallVector<EVT, 1> PtrValueVTs; 1919 ComputeValueVTs(TLI, DL, 1920 F->getReturnType()->getPointerTo( 1921 DAG.getDataLayout().getAllocaAddrSpace()), 1922 PtrValueVTs); 1923 1924 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1925 DemoteReg, PtrValueVTs[0]); 1926 SDValue RetOp = getValue(I.getOperand(0)); 1927 1928 SmallVector<EVT, 4> ValueVTs, MemVTs; 1929 SmallVector<uint64_t, 4> Offsets; 1930 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1931 &Offsets); 1932 unsigned NumValues = ValueVTs.size(); 1933 1934 SmallVector<SDValue, 4> Chains(NumValues); 1935 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1936 for (unsigned i = 0; i != NumValues; ++i) { 1937 // An aggregate return value cannot wrap around the address space, so 1938 // offsets to its parts don't wrap either. 1939 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1940 TypeSize::Fixed(Offsets[i])); 1941 1942 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1943 if (MemVTs[i] != ValueVTs[i]) 1944 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1945 Chains[i] = DAG.getStore( 1946 Chain, getCurSDLoc(), Val, 1947 // FIXME: better loc info would be nice. 1948 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1949 commonAlignment(BaseAlign, Offsets[i])); 1950 } 1951 1952 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1953 MVT::Other, Chains); 1954 } else if (I.getNumOperands() != 0) { 1955 SmallVector<EVT, 4> ValueVTs; 1956 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1957 unsigned NumValues = ValueVTs.size(); 1958 if (NumValues) { 1959 SDValue RetOp = getValue(I.getOperand(0)); 1960 1961 const Function *F = I.getParent()->getParent(); 1962 1963 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1964 I.getOperand(0)->getType(), F->getCallingConv(), 1965 /*IsVarArg*/ false, DL); 1966 1967 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1968 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 1969 ExtendKind = ISD::SIGN_EXTEND; 1970 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 1971 ExtendKind = ISD::ZERO_EXTEND; 1972 1973 LLVMContext &Context = F->getContext(); 1974 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 1975 1976 for (unsigned j = 0; j != NumValues; ++j) { 1977 EVT VT = ValueVTs[j]; 1978 1979 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1980 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1981 1982 CallingConv::ID CC = F->getCallingConv(); 1983 1984 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1985 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1986 SmallVector<SDValue, 4> Parts(NumParts); 1987 getCopyToParts(DAG, getCurSDLoc(), 1988 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1989 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1990 1991 // 'inreg' on function refers to return value 1992 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1993 if (RetInReg) 1994 Flags.setInReg(); 1995 1996 if (I.getOperand(0)->getType()->isPointerTy()) { 1997 Flags.setPointer(); 1998 Flags.setPointerAddrSpace( 1999 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2000 } 2001 2002 if (NeedsRegBlock) { 2003 Flags.setInConsecutiveRegs(); 2004 if (j == NumValues - 1) 2005 Flags.setInConsecutiveRegsLast(); 2006 } 2007 2008 // Propagate extension type if any 2009 if (ExtendKind == ISD::SIGN_EXTEND) 2010 Flags.setSExt(); 2011 else if (ExtendKind == ISD::ZERO_EXTEND) 2012 Flags.setZExt(); 2013 2014 for (unsigned i = 0; i < NumParts; ++i) { 2015 Outs.push_back(ISD::OutputArg(Flags, 2016 Parts[i].getValueType().getSimpleVT(), 2017 VT, /*isfixed=*/true, 0, 0)); 2018 OutVals.push_back(Parts[i]); 2019 } 2020 } 2021 } 2022 } 2023 2024 // Push in swifterror virtual register as the last element of Outs. This makes 2025 // sure swifterror virtual register will be returned in the swifterror 2026 // physical register. 2027 const Function *F = I.getParent()->getParent(); 2028 if (TLI.supportSwiftError() && 2029 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2030 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2031 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2032 Flags.setSwiftError(); 2033 Outs.push_back(ISD::OutputArg( 2034 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2035 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2036 // Create SDNode for the swifterror virtual register. 2037 OutVals.push_back( 2038 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2039 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2040 EVT(TLI.getPointerTy(DL)))); 2041 } 2042 2043 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2044 CallingConv::ID CallConv = 2045 DAG.getMachineFunction().getFunction().getCallingConv(); 2046 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2047 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2048 2049 // Verify that the target's LowerReturn behaved as expected. 2050 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2051 "LowerReturn didn't return a valid chain!"); 2052 2053 // Update the DAG with the new chain value resulting from return lowering. 2054 DAG.setRoot(Chain); 2055 } 2056 2057 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2058 /// created for it, emit nodes to copy the value into the virtual 2059 /// registers. 2060 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2061 // Skip empty types 2062 if (V->getType()->isEmptyTy()) 2063 return; 2064 2065 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2066 if (VMI != FuncInfo.ValueMap.end()) { 2067 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2068 CopyValueToVirtualRegister(V, VMI->second); 2069 } 2070 } 2071 2072 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2073 /// the current basic block, add it to ValueMap now so that we'll get a 2074 /// CopyTo/FromReg. 2075 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2076 // No need to export constants. 2077 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2078 2079 // Already exported? 2080 if (FuncInfo.isExportedInst(V)) return; 2081 2082 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2083 CopyValueToVirtualRegister(V, Reg); 2084 } 2085 2086 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2087 const BasicBlock *FromBB) { 2088 // The operands of the setcc have to be in this block. We don't know 2089 // how to export them from some other block. 2090 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2091 // Can export from current BB. 2092 if (VI->getParent() == FromBB) 2093 return true; 2094 2095 // Is already exported, noop. 2096 return FuncInfo.isExportedInst(V); 2097 } 2098 2099 // If this is an argument, we can export it if the BB is the entry block or 2100 // if it is already exported. 2101 if (isa<Argument>(V)) { 2102 if (FromBB->isEntryBlock()) 2103 return true; 2104 2105 // Otherwise, can only export this if it is already exported. 2106 return FuncInfo.isExportedInst(V); 2107 } 2108 2109 // Otherwise, constants can always be exported. 2110 return true; 2111 } 2112 2113 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2114 BranchProbability 2115 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2116 const MachineBasicBlock *Dst) const { 2117 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2118 const BasicBlock *SrcBB = Src->getBasicBlock(); 2119 const BasicBlock *DstBB = Dst->getBasicBlock(); 2120 if (!BPI) { 2121 // If BPI is not available, set the default probability as 1 / N, where N is 2122 // the number of successors. 2123 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2124 return BranchProbability(1, SuccSize); 2125 } 2126 return BPI->getEdgeProbability(SrcBB, DstBB); 2127 } 2128 2129 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2130 MachineBasicBlock *Dst, 2131 BranchProbability Prob) { 2132 if (!FuncInfo.BPI) 2133 Src->addSuccessorWithoutProb(Dst); 2134 else { 2135 if (Prob.isUnknown()) 2136 Prob = getEdgeProbability(Src, Dst); 2137 Src->addSuccessor(Dst, Prob); 2138 } 2139 } 2140 2141 static bool InBlock(const Value *V, const BasicBlock *BB) { 2142 if (const Instruction *I = dyn_cast<Instruction>(V)) 2143 return I->getParent() == BB; 2144 return true; 2145 } 2146 2147 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2148 /// This function emits a branch and is used at the leaves of an OR or an 2149 /// AND operator tree. 2150 void 2151 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2152 MachineBasicBlock *TBB, 2153 MachineBasicBlock *FBB, 2154 MachineBasicBlock *CurBB, 2155 MachineBasicBlock *SwitchBB, 2156 BranchProbability TProb, 2157 BranchProbability FProb, 2158 bool InvertCond) { 2159 const BasicBlock *BB = CurBB->getBasicBlock(); 2160 2161 // If the leaf of the tree is a comparison, merge the condition into 2162 // the caseblock. 2163 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2164 // The operands of the cmp have to be in this block. We don't know 2165 // how to export them from some other block. If this is the first block 2166 // of the sequence, no exporting is needed. 2167 if (CurBB == SwitchBB || 2168 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2169 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2170 ISD::CondCode Condition; 2171 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2172 ICmpInst::Predicate Pred = 2173 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2174 Condition = getICmpCondCode(Pred); 2175 } else { 2176 const FCmpInst *FC = cast<FCmpInst>(Cond); 2177 FCmpInst::Predicate Pred = 2178 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2179 Condition = getFCmpCondCode(Pred); 2180 if (TM.Options.NoNaNsFPMath) 2181 Condition = getFCmpCodeWithoutNaN(Condition); 2182 } 2183 2184 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2185 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2186 SL->SwitchCases.push_back(CB); 2187 return; 2188 } 2189 } 2190 2191 // Create a CaseBlock record representing this branch. 2192 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2193 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2194 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2195 SL->SwitchCases.push_back(CB); 2196 } 2197 2198 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2199 MachineBasicBlock *TBB, 2200 MachineBasicBlock *FBB, 2201 MachineBasicBlock *CurBB, 2202 MachineBasicBlock *SwitchBB, 2203 Instruction::BinaryOps Opc, 2204 BranchProbability TProb, 2205 BranchProbability FProb, 2206 bool InvertCond) { 2207 // Skip over not part of the tree and remember to invert op and operands at 2208 // next level. 2209 Value *NotCond; 2210 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2211 InBlock(NotCond, CurBB->getBasicBlock())) { 2212 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2213 !InvertCond); 2214 return; 2215 } 2216 2217 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2218 const Value *BOpOp0, *BOpOp1; 2219 // Compute the effective opcode for Cond, taking into account whether it needs 2220 // to be inverted, e.g. 2221 // and (not (or A, B)), C 2222 // gets lowered as 2223 // and (and (not A, not B), C) 2224 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2225 if (BOp) { 2226 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2227 ? Instruction::And 2228 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2229 ? Instruction::Or 2230 : (Instruction::BinaryOps)0); 2231 if (InvertCond) { 2232 if (BOpc == Instruction::And) 2233 BOpc = Instruction::Or; 2234 else if (BOpc == Instruction::Or) 2235 BOpc = Instruction::And; 2236 } 2237 } 2238 2239 // If this node is not part of the or/and tree, emit it as a branch. 2240 // Note that all nodes in the tree should have same opcode. 2241 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2242 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2243 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2244 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2245 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2246 TProb, FProb, InvertCond); 2247 return; 2248 } 2249 2250 // Create TmpBB after CurBB. 2251 MachineFunction::iterator BBI(CurBB); 2252 MachineFunction &MF = DAG.getMachineFunction(); 2253 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2254 CurBB->getParent()->insert(++BBI, TmpBB); 2255 2256 if (Opc == Instruction::Or) { 2257 // Codegen X | Y as: 2258 // BB1: 2259 // jmp_if_X TBB 2260 // jmp TmpBB 2261 // TmpBB: 2262 // jmp_if_Y TBB 2263 // jmp FBB 2264 // 2265 2266 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2267 // The requirement is that 2268 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2269 // = TrueProb for original BB. 2270 // Assuming the original probabilities are A and B, one choice is to set 2271 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2272 // A/(1+B) and 2B/(1+B). This choice assumes that 2273 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2274 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2275 // TmpBB, but the math is more complicated. 2276 2277 auto NewTrueProb = TProb / 2; 2278 auto NewFalseProb = TProb / 2 + FProb; 2279 // Emit the LHS condition. 2280 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2281 NewFalseProb, InvertCond); 2282 2283 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2284 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2285 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2286 // Emit the RHS condition into TmpBB. 2287 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2288 Probs[1], InvertCond); 2289 } else { 2290 assert(Opc == Instruction::And && "Unknown merge op!"); 2291 // Codegen X & Y as: 2292 // BB1: 2293 // jmp_if_X TmpBB 2294 // jmp FBB 2295 // TmpBB: 2296 // jmp_if_Y TBB 2297 // jmp FBB 2298 // 2299 // This requires creation of TmpBB after CurBB. 2300 2301 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2302 // The requirement is that 2303 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2304 // = FalseProb for original BB. 2305 // Assuming the original probabilities are A and B, one choice is to set 2306 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2307 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2308 // TrueProb for BB1 * FalseProb for TmpBB. 2309 2310 auto NewTrueProb = TProb + FProb / 2; 2311 auto NewFalseProb = FProb / 2; 2312 // Emit the LHS condition. 2313 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2314 NewFalseProb, InvertCond); 2315 2316 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2317 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2318 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2319 // Emit the RHS condition into TmpBB. 2320 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2321 Probs[1], InvertCond); 2322 } 2323 } 2324 2325 /// If the set of cases should be emitted as a series of branches, return true. 2326 /// If we should emit this as a bunch of and/or'd together conditions, return 2327 /// false. 2328 bool 2329 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2330 if (Cases.size() != 2) return true; 2331 2332 // If this is two comparisons of the same values or'd or and'd together, they 2333 // will get folded into a single comparison, so don't emit two blocks. 2334 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2335 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2336 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2337 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2338 return false; 2339 } 2340 2341 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2342 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2343 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2344 Cases[0].CC == Cases[1].CC && 2345 isa<Constant>(Cases[0].CmpRHS) && 2346 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2347 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2348 return false; 2349 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2350 return false; 2351 } 2352 2353 return true; 2354 } 2355 2356 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2357 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2358 2359 // Update machine-CFG edges. 2360 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2361 2362 if (I.isUnconditional()) { 2363 // Update machine-CFG edges. 2364 BrMBB->addSuccessor(Succ0MBB); 2365 2366 // If this is not a fall-through branch or optimizations are switched off, 2367 // emit the branch. 2368 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2369 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2370 MVT::Other, getControlRoot(), 2371 DAG.getBasicBlock(Succ0MBB))); 2372 2373 return; 2374 } 2375 2376 // If this condition is one of the special cases we handle, do special stuff 2377 // now. 2378 const Value *CondVal = I.getCondition(); 2379 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2380 2381 // If this is a series of conditions that are or'd or and'd together, emit 2382 // this as a sequence of branches instead of setcc's with and/or operations. 2383 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2384 // unpredictable branches, and vector extracts because those jumps are likely 2385 // expensive for any target), this should improve performance. 2386 // For example, instead of something like: 2387 // cmp A, B 2388 // C = seteq 2389 // cmp D, E 2390 // F = setle 2391 // or C, F 2392 // jnz foo 2393 // Emit: 2394 // cmp A, B 2395 // je foo 2396 // cmp D, E 2397 // jle foo 2398 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2399 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2400 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2401 Value *Vec; 2402 const Value *BOp0, *BOp1; 2403 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2404 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2405 Opcode = Instruction::And; 2406 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2407 Opcode = Instruction::Or; 2408 2409 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2410 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2411 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2412 getEdgeProbability(BrMBB, Succ0MBB), 2413 getEdgeProbability(BrMBB, Succ1MBB), 2414 /*InvertCond=*/false); 2415 // If the compares in later blocks need to use values not currently 2416 // exported from this block, export them now. This block should always 2417 // be the first entry. 2418 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2419 2420 // Allow some cases to be rejected. 2421 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2422 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2423 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2424 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2425 } 2426 2427 // Emit the branch for this block. 2428 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2429 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2430 return; 2431 } 2432 2433 // Okay, we decided not to do this, remove any inserted MBB's and clear 2434 // SwitchCases. 2435 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2436 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2437 2438 SL->SwitchCases.clear(); 2439 } 2440 } 2441 2442 // Create a CaseBlock record representing this branch. 2443 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2444 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2445 2446 // Use visitSwitchCase to actually insert the fast branch sequence for this 2447 // cond branch. 2448 visitSwitchCase(CB, BrMBB); 2449 } 2450 2451 /// visitSwitchCase - Emits the necessary code to represent a single node in 2452 /// the binary search tree resulting from lowering a switch instruction. 2453 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2454 MachineBasicBlock *SwitchBB) { 2455 SDValue Cond; 2456 SDValue CondLHS = getValue(CB.CmpLHS); 2457 SDLoc dl = CB.DL; 2458 2459 if (CB.CC == ISD::SETTRUE) { 2460 // Branch or fall through to TrueBB. 2461 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2462 SwitchBB->normalizeSuccProbs(); 2463 if (CB.TrueBB != NextBlock(SwitchBB)) { 2464 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2465 DAG.getBasicBlock(CB.TrueBB))); 2466 } 2467 return; 2468 } 2469 2470 auto &TLI = DAG.getTargetLoweringInfo(); 2471 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2472 2473 // Build the setcc now. 2474 if (!CB.CmpMHS) { 2475 // Fold "(X == true)" to X and "(X == false)" to !X to 2476 // handle common cases produced by branch lowering. 2477 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2478 CB.CC == ISD::SETEQ) 2479 Cond = CondLHS; 2480 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2481 CB.CC == ISD::SETEQ) { 2482 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2483 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2484 } else { 2485 SDValue CondRHS = getValue(CB.CmpRHS); 2486 2487 // If a pointer's DAG type is larger than its memory type then the DAG 2488 // values are zero-extended. This breaks signed comparisons so truncate 2489 // back to the underlying type before doing the compare. 2490 if (CondLHS.getValueType() != MemVT) { 2491 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2492 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2493 } 2494 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2495 } 2496 } else { 2497 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2498 2499 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2500 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2501 2502 SDValue CmpOp = getValue(CB.CmpMHS); 2503 EVT VT = CmpOp.getValueType(); 2504 2505 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2506 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2507 ISD::SETLE); 2508 } else { 2509 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2510 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2511 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2512 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2513 } 2514 } 2515 2516 // Update successor info 2517 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2518 // TrueBB and FalseBB are always different unless the incoming IR is 2519 // degenerate. This only happens when running llc on weird IR. 2520 if (CB.TrueBB != CB.FalseBB) 2521 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2522 SwitchBB->normalizeSuccProbs(); 2523 2524 // If the lhs block is the next block, invert the condition so that we can 2525 // fall through to the lhs instead of the rhs block. 2526 if (CB.TrueBB == NextBlock(SwitchBB)) { 2527 std::swap(CB.TrueBB, CB.FalseBB); 2528 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2529 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2530 } 2531 2532 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2533 MVT::Other, getControlRoot(), Cond, 2534 DAG.getBasicBlock(CB.TrueBB)); 2535 2536 // Insert the false branch. Do this even if it's a fall through branch, 2537 // this makes it easier to do DAG optimizations which require inverting 2538 // the branch condition. 2539 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2540 DAG.getBasicBlock(CB.FalseBB)); 2541 2542 DAG.setRoot(BrCond); 2543 } 2544 2545 /// visitJumpTable - Emit JumpTable node in the current MBB 2546 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2547 // Emit the code for the jump table 2548 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2549 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2550 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2551 JT.Reg, PTy); 2552 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2553 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2554 MVT::Other, Index.getValue(1), 2555 Table, Index); 2556 DAG.setRoot(BrJumpTable); 2557 } 2558 2559 /// visitJumpTableHeader - This function emits necessary code to produce index 2560 /// in the JumpTable from switch case. 2561 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2562 JumpTableHeader &JTH, 2563 MachineBasicBlock *SwitchBB) { 2564 SDLoc dl = getCurSDLoc(); 2565 2566 // Subtract the lowest switch case value from the value being switched on. 2567 SDValue SwitchOp = getValue(JTH.SValue); 2568 EVT VT = SwitchOp.getValueType(); 2569 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2570 DAG.getConstant(JTH.First, dl, VT)); 2571 2572 // The SDNode we just created, which holds the value being switched on minus 2573 // the smallest case value, needs to be copied to a virtual register so it 2574 // can be used as an index into the jump table in a subsequent basic block. 2575 // This value may be smaller or larger than the target's pointer type, and 2576 // therefore require extension or truncating. 2577 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2578 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2579 2580 unsigned JumpTableReg = 2581 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2582 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2583 JumpTableReg, SwitchOp); 2584 JT.Reg = JumpTableReg; 2585 2586 if (!JTH.FallthroughUnreachable) { 2587 // Emit the range check for the jump table, and branch to the default block 2588 // for the switch statement if the value being switched on exceeds the 2589 // largest case in the switch. 2590 SDValue CMP = DAG.getSetCC( 2591 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2592 Sub.getValueType()), 2593 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2594 2595 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2596 MVT::Other, CopyTo, CMP, 2597 DAG.getBasicBlock(JT.Default)); 2598 2599 // Avoid emitting unnecessary branches to the next block. 2600 if (JT.MBB != NextBlock(SwitchBB)) 2601 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2602 DAG.getBasicBlock(JT.MBB)); 2603 2604 DAG.setRoot(BrCond); 2605 } else { 2606 // Avoid emitting unnecessary branches to the next block. 2607 if (JT.MBB != NextBlock(SwitchBB)) 2608 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2609 DAG.getBasicBlock(JT.MBB))); 2610 else 2611 DAG.setRoot(CopyTo); 2612 } 2613 } 2614 2615 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2616 /// variable if there exists one. 2617 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2618 SDValue &Chain) { 2619 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2620 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2621 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2622 MachineFunction &MF = DAG.getMachineFunction(); 2623 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2624 MachineSDNode *Node = 2625 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2626 if (Global) { 2627 MachinePointerInfo MPInfo(Global); 2628 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2629 MachineMemOperand::MODereferenceable; 2630 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2631 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2632 DAG.setNodeMemRefs(Node, {MemRef}); 2633 } 2634 if (PtrTy != PtrMemTy) 2635 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2636 return SDValue(Node, 0); 2637 } 2638 2639 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2640 /// tail spliced into a stack protector check success bb. 2641 /// 2642 /// For a high level explanation of how this fits into the stack protector 2643 /// generation see the comment on the declaration of class 2644 /// StackProtectorDescriptor. 2645 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2646 MachineBasicBlock *ParentBB) { 2647 2648 // First create the loads to the guard/stack slot for the comparison. 2649 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2650 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2651 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2652 2653 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2654 int FI = MFI.getStackProtectorIndex(); 2655 2656 SDValue Guard; 2657 SDLoc dl = getCurSDLoc(); 2658 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2659 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2660 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2661 2662 // Generate code to load the content of the guard slot. 2663 SDValue GuardVal = DAG.getLoad( 2664 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2665 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2666 MachineMemOperand::MOVolatile); 2667 2668 if (TLI.useStackGuardXorFP()) 2669 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2670 2671 // Retrieve guard check function, nullptr if instrumentation is inlined. 2672 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2673 // The target provides a guard check function to validate the guard value. 2674 // Generate a call to that function with the content of the guard slot as 2675 // argument. 2676 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2677 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2678 2679 TargetLowering::ArgListTy Args; 2680 TargetLowering::ArgListEntry Entry; 2681 Entry.Node = GuardVal; 2682 Entry.Ty = FnTy->getParamType(0); 2683 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2684 Entry.IsInReg = true; 2685 Args.push_back(Entry); 2686 2687 TargetLowering::CallLoweringInfo CLI(DAG); 2688 CLI.setDebugLoc(getCurSDLoc()) 2689 .setChain(DAG.getEntryNode()) 2690 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2691 getValue(GuardCheckFn), std::move(Args)); 2692 2693 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2694 DAG.setRoot(Result.second); 2695 return; 2696 } 2697 2698 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2699 // Otherwise, emit a volatile load to retrieve the stack guard value. 2700 SDValue Chain = DAG.getEntryNode(); 2701 if (TLI.useLoadStackGuardNode()) { 2702 Guard = getLoadStackGuard(DAG, dl, Chain); 2703 } else { 2704 const Value *IRGuard = TLI.getSDagStackGuard(M); 2705 SDValue GuardPtr = getValue(IRGuard); 2706 2707 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2708 MachinePointerInfo(IRGuard, 0), Align, 2709 MachineMemOperand::MOVolatile); 2710 } 2711 2712 // Perform the comparison via a getsetcc. 2713 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2714 *DAG.getContext(), 2715 Guard.getValueType()), 2716 Guard, GuardVal, ISD::SETNE); 2717 2718 // If the guard/stackslot do not equal, branch to failure MBB. 2719 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2720 MVT::Other, GuardVal.getOperand(0), 2721 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2722 // Otherwise branch to success MBB. 2723 SDValue Br = DAG.getNode(ISD::BR, dl, 2724 MVT::Other, BrCond, 2725 DAG.getBasicBlock(SPD.getSuccessMBB())); 2726 2727 DAG.setRoot(Br); 2728 } 2729 2730 /// Codegen the failure basic block for a stack protector check. 2731 /// 2732 /// A failure stack protector machine basic block consists simply of a call to 2733 /// __stack_chk_fail(). 2734 /// 2735 /// For a high level explanation of how this fits into the stack protector 2736 /// generation see the comment on the declaration of class 2737 /// StackProtectorDescriptor. 2738 void 2739 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2740 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2741 TargetLowering::MakeLibCallOptions CallOptions; 2742 CallOptions.setDiscardResult(true); 2743 SDValue Chain = 2744 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2745 None, CallOptions, getCurSDLoc()).second; 2746 // On PS4, the "return address" must still be within the calling function, 2747 // even if it's at the very end, so emit an explicit TRAP here. 2748 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2749 if (TM.getTargetTriple().isPS4CPU()) 2750 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2751 // WebAssembly needs an unreachable instruction after a non-returning call, 2752 // because the function return type can be different from __stack_chk_fail's 2753 // return type (void). 2754 if (TM.getTargetTriple().isWasm()) 2755 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2756 2757 DAG.setRoot(Chain); 2758 } 2759 2760 /// visitBitTestHeader - This function emits necessary code to produce value 2761 /// suitable for "bit tests" 2762 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2763 MachineBasicBlock *SwitchBB) { 2764 SDLoc dl = getCurSDLoc(); 2765 2766 // Subtract the minimum value. 2767 SDValue SwitchOp = getValue(B.SValue); 2768 EVT VT = SwitchOp.getValueType(); 2769 SDValue RangeSub = 2770 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2771 2772 // Determine the type of the test operands. 2773 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2774 bool UsePtrType = false; 2775 if (!TLI.isTypeLegal(VT)) { 2776 UsePtrType = true; 2777 } else { 2778 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2779 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2780 // Switch table case range are encoded into series of masks. 2781 // Just use pointer type, it's guaranteed to fit. 2782 UsePtrType = true; 2783 break; 2784 } 2785 } 2786 SDValue Sub = RangeSub; 2787 if (UsePtrType) { 2788 VT = TLI.getPointerTy(DAG.getDataLayout()); 2789 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2790 } 2791 2792 B.RegVT = VT.getSimpleVT(); 2793 B.Reg = FuncInfo.CreateReg(B.RegVT); 2794 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2795 2796 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2797 2798 if (!B.FallthroughUnreachable) 2799 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2800 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2801 SwitchBB->normalizeSuccProbs(); 2802 2803 SDValue Root = CopyTo; 2804 if (!B.FallthroughUnreachable) { 2805 // Conditional branch to the default block. 2806 SDValue RangeCmp = DAG.getSetCC(dl, 2807 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2808 RangeSub.getValueType()), 2809 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2810 ISD::SETUGT); 2811 2812 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2813 DAG.getBasicBlock(B.Default)); 2814 } 2815 2816 // Avoid emitting unnecessary branches to the next block. 2817 if (MBB != NextBlock(SwitchBB)) 2818 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2819 2820 DAG.setRoot(Root); 2821 } 2822 2823 /// visitBitTestCase - this function produces one "bit test" 2824 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2825 MachineBasicBlock* NextMBB, 2826 BranchProbability BranchProbToNext, 2827 unsigned Reg, 2828 BitTestCase &B, 2829 MachineBasicBlock *SwitchBB) { 2830 SDLoc dl = getCurSDLoc(); 2831 MVT VT = BB.RegVT; 2832 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2833 SDValue Cmp; 2834 unsigned PopCount = countPopulation(B.Mask); 2835 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2836 if (PopCount == 1) { 2837 // Testing for a single bit; just compare the shift count with what it 2838 // would need to be to shift a 1 bit in that position. 2839 Cmp = DAG.getSetCC( 2840 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2841 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2842 ISD::SETEQ); 2843 } else if (PopCount == BB.Range) { 2844 // There is only one zero bit in the range, test for it directly. 2845 Cmp = DAG.getSetCC( 2846 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2847 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2848 ISD::SETNE); 2849 } else { 2850 // Make desired shift 2851 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2852 DAG.getConstant(1, dl, VT), ShiftOp); 2853 2854 // Emit bit tests and jumps 2855 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2856 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2857 Cmp = DAG.getSetCC( 2858 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2859 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2860 } 2861 2862 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2863 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2864 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2865 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2866 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2867 // one as they are relative probabilities (and thus work more like weights), 2868 // and hence we need to normalize them to let the sum of them become one. 2869 SwitchBB->normalizeSuccProbs(); 2870 2871 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2872 MVT::Other, getControlRoot(), 2873 Cmp, DAG.getBasicBlock(B.TargetBB)); 2874 2875 // Avoid emitting unnecessary branches to the next block. 2876 if (NextMBB != NextBlock(SwitchBB)) 2877 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2878 DAG.getBasicBlock(NextMBB)); 2879 2880 DAG.setRoot(BrAnd); 2881 } 2882 2883 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2884 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2885 2886 // Retrieve successors. Look through artificial IR level blocks like 2887 // catchswitch for successors. 2888 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2889 const BasicBlock *EHPadBB = I.getSuccessor(1); 2890 2891 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2892 // have to do anything here to lower funclet bundles. 2893 assert(!I.hasOperandBundlesOtherThan( 2894 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2895 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2896 LLVMContext::OB_cfguardtarget, 2897 LLVMContext::OB_clang_arc_attachedcall}) && 2898 "Cannot lower invokes with arbitrary operand bundles yet!"); 2899 2900 const Value *Callee(I.getCalledOperand()); 2901 const Function *Fn = dyn_cast<Function>(Callee); 2902 if (isa<InlineAsm>(Callee)) 2903 visitInlineAsm(I, EHPadBB); 2904 else if (Fn && Fn->isIntrinsic()) { 2905 switch (Fn->getIntrinsicID()) { 2906 default: 2907 llvm_unreachable("Cannot invoke this intrinsic"); 2908 case Intrinsic::donothing: 2909 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2910 case Intrinsic::seh_try_begin: 2911 case Intrinsic::seh_scope_begin: 2912 case Intrinsic::seh_try_end: 2913 case Intrinsic::seh_scope_end: 2914 break; 2915 case Intrinsic::experimental_patchpoint_void: 2916 case Intrinsic::experimental_patchpoint_i64: 2917 visitPatchpoint(I, EHPadBB); 2918 break; 2919 case Intrinsic::experimental_gc_statepoint: 2920 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2921 break; 2922 case Intrinsic::wasm_rethrow: { 2923 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2924 // special because it can be invoked, so we manually lower it to a DAG 2925 // node here. 2926 SmallVector<SDValue, 8> Ops; 2927 Ops.push_back(getRoot()); // inchain 2928 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2929 Ops.push_back( 2930 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2931 TLI.getPointerTy(DAG.getDataLayout()))); 2932 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2933 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2934 break; 2935 } 2936 } 2937 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2938 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2939 // Eventually we will support lowering the @llvm.experimental.deoptimize 2940 // intrinsic, and right now there are no plans to support other intrinsics 2941 // with deopt state. 2942 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2943 } else { 2944 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2945 } 2946 2947 // If the value of the invoke is used outside of its defining block, make it 2948 // available as a virtual register. 2949 // We already took care of the exported value for the statepoint instruction 2950 // during call to the LowerStatepoint. 2951 if (!isa<GCStatepointInst>(I)) { 2952 CopyToExportRegsIfNeeded(&I); 2953 } 2954 2955 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2956 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2957 BranchProbability EHPadBBProb = 2958 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2959 : BranchProbability::getZero(); 2960 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2961 2962 // Update successor info. 2963 addSuccessorWithProb(InvokeMBB, Return); 2964 for (auto &UnwindDest : UnwindDests) { 2965 UnwindDest.first->setIsEHPad(); 2966 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2967 } 2968 InvokeMBB->normalizeSuccProbs(); 2969 2970 // Drop into normal successor. 2971 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2972 DAG.getBasicBlock(Return))); 2973 } 2974 2975 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2976 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2977 2978 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2979 // have to do anything here to lower funclet bundles. 2980 assert(!I.hasOperandBundlesOtherThan( 2981 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2982 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2983 2984 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2985 visitInlineAsm(I); 2986 CopyToExportRegsIfNeeded(&I); 2987 2988 // Retrieve successors. 2989 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2990 2991 // Update successor info. 2992 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2993 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2994 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2995 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2996 Target->setIsInlineAsmBrIndirectTarget(); 2997 } 2998 CallBrMBB->normalizeSuccProbs(); 2999 3000 // Drop into default successor. 3001 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3002 MVT::Other, getControlRoot(), 3003 DAG.getBasicBlock(Return))); 3004 } 3005 3006 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3007 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3008 } 3009 3010 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3011 assert(FuncInfo.MBB->isEHPad() && 3012 "Call to landingpad not in landing pad!"); 3013 3014 // If there aren't registers to copy the values into (e.g., during SjLj 3015 // exceptions), then don't bother to create these DAG nodes. 3016 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3017 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3018 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3019 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3020 return; 3021 3022 // If landingpad's return type is token type, we don't create DAG nodes 3023 // for its exception pointer and selector value. The extraction of exception 3024 // pointer or selector value from token type landingpads is not currently 3025 // supported. 3026 if (LP.getType()->isTokenTy()) 3027 return; 3028 3029 SmallVector<EVT, 2> ValueVTs; 3030 SDLoc dl = getCurSDLoc(); 3031 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3032 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3033 3034 // Get the two live-in registers as SDValues. The physregs have already been 3035 // copied into virtual registers. 3036 SDValue Ops[2]; 3037 if (FuncInfo.ExceptionPointerVirtReg) { 3038 Ops[0] = DAG.getZExtOrTrunc( 3039 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3040 FuncInfo.ExceptionPointerVirtReg, 3041 TLI.getPointerTy(DAG.getDataLayout())), 3042 dl, ValueVTs[0]); 3043 } else { 3044 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3045 } 3046 Ops[1] = DAG.getZExtOrTrunc( 3047 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3048 FuncInfo.ExceptionSelectorVirtReg, 3049 TLI.getPointerTy(DAG.getDataLayout())), 3050 dl, ValueVTs[1]); 3051 3052 // Merge into one. 3053 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3054 DAG.getVTList(ValueVTs), Ops); 3055 setValue(&LP, Res); 3056 } 3057 3058 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3059 MachineBasicBlock *Last) { 3060 // Update JTCases. 3061 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3062 if (SL->JTCases[i].first.HeaderBB == First) 3063 SL->JTCases[i].first.HeaderBB = Last; 3064 3065 // Update BitTestCases. 3066 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3067 if (SL->BitTestCases[i].Parent == First) 3068 SL->BitTestCases[i].Parent = Last; 3069 } 3070 3071 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3072 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3073 3074 // Update machine-CFG edges with unique successors. 3075 SmallSet<BasicBlock*, 32> Done; 3076 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3077 BasicBlock *BB = I.getSuccessor(i); 3078 bool Inserted = Done.insert(BB).second; 3079 if (!Inserted) 3080 continue; 3081 3082 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3083 addSuccessorWithProb(IndirectBrMBB, Succ); 3084 } 3085 IndirectBrMBB->normalizeSuccProbs(); 3086 3087 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3088 MVT::Other, getControlRoot(), 3089 getValue(I.getAddress()))); 3090 } 3091 3092 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3093 if (!DAG.getTarget().Options.TrapUnreachable) 3094 return; 3095 3096 // We may be able to ignore unreachable behind a noreturn call. 3097 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3098 const BasicBlock &BB = *I.getParent(); 3099 if (&I != &BB.front()) { 3100 BasicBlock::const_iterator PredI = 3101 std::prev(BasicBlock::const_iterator(&I)); 3102 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3103 if (Call->doesNotReturn()) 3104 return; 3105 } 3106 } 3107 } 3108 3109 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3110 } 3111 3112 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3113 SDNodeFlags Flags; 3114 3115 SDValue Op = getValue(I.getOperand(0)); 3116 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3117 Op, Flags); 3118 setValue(&I, UnNodeValue); 3119 } 3120 3121 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3122 SDNodeFlags Flags; 3123 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3124 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3125 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3126 } 3127 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3128 Flags.setExact(ExactOp->isExact()); 3129 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3130 Flags.copyFMF(*FPOp); 3131 3132 SDValue Op1 = getValue(I.getOperand(0)); 3133 SDValue Op2 = getValue(I.getOperand(1)); 3134 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3135 Op1, Op2, Flags); 3136 setValue(&I, BinNodeValue); 3137 } 3138 3139 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3140 SDValue Op1 = getValue(I.getOperand(0)); 3141 SDValue Op2 = getValue(I.getOperand(1)); 3142 3143 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3144 Op1.getValueType(), DAG.getDataLayout()); 3145 3146 // Coerce the shift amount to the right type if we can. 3147 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3148 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3149 unsigned Op2Size = Op2.getValueSizeInBits(); 3150 SDLoc DL = getCurSDLoc(); 3151 3152 // If the operand is smaller than the shift count type, promote it. 3153 if (ShiftSize > Op2Size) 3154 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3155 3156 // If the operand is larger than the shift count type but the shift 3157 // count type has enough bits to represent any shift value, truncate 3158 // it now. This is a common case and it exposes the truncate to 3159 // optimization early. 3160 else if (ShiftSize >= Log2_32_Ceil(Op1.getValueSizeInBits())) 3161 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3162 // Otherwise we'll need to temporarily settle for some other convenient 3163 // type. Type legalization will make adjustments once the shiftee is split. 3164 else 3165 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3166 } 3167 3168 bool nuw = false; 3169 bool nsw = false; 3170 bool exact = false; 3171 3172 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3173 3174 if (const OverflowingBinaryOperator *OFBinOp = 3175 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3176 nuw = OFBinOp->hasNoUnsignedWrap(); 3177 nsw = OFBinOp->hasNoSignedWrap(); 3178 } 3179 if (const PossiblyExactOperator *ExactOp = 3180 dyn_cast<const PossiblyExactOperator>(&I)) 3181 exact = ExactOp->isExact(); 3182 } 3183 SDNodeFlags Flags; 3184 Flags.setExact(exact); 3185 Flags.setNoSignedWrap(nsw); 3186 Flags.setNoUnsignedWrap(nuw); 3187 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3188 Flags); 3189 setValue(&I, Res); 3190 } 3191 3192 void SelectionDAGBuilder::visitSDiv(const User &I) { 3193 SDValue Op1 = getValue(I.getOperand(0)); 3194 SDValue Op2 = getValue(I.getOperand(1)); 3195 3196 SDNodeFlags Flags; 3197 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3198 cast<PossiblyExactOperator>(&I)->isExact()); 3199 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3200 Op2, Flags)); 3201 } 3202 3203 void SelectionDAGBuilder::visitICmp(const User &I) { 3204 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3205 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3206 predicate = IC->getPredicate(); 3207 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3208 predicate = ICmpInst::Predicate(IC->getPredicate()); 3209 SDValue Op1 = getValue(I.getOperand(0)); 3210 SDValue Op2 = getValue(I.getOperand(1)); 3211 ISD::CondCode Opcode = getICmpCondCode(predicate); 3212 3213 auto &TLI = DAG.getTargetLoweringInfo(); 3214 EVT MemVT = 3215 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3216 3217 // If a pointer's DAG type is larger than its memory type then the DAG values 3218 // are zero-extended. This breaks signed comparisons so truncate back to the 3219 // underlying type before doing the compare. 3220 if (Op1.getValueType() != MemVT) { 3221 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3222 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3223 } 3224 3225 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3226 I.getType()); 3227 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3228 } 3229 3230 void SelectionDAGBuilder::visitFCmp(const User &I) { 3231 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3232 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3233 predicate = FC->getPredicate(); 3234 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3235 predicate = FCmpInst::Predicate(FC->getPredicate()); 3236 SDValue Op1 = getValue(I.getOperand(0)); 3237 SDValue Op2 = getValue(I.getOperand(1)); 3238 3239 ISD::CondCode Condition = getFCmpCondCode(predicate); 3240 auto *FPMO = cast<FPMathOperator>(&I); 3241 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3242 Condition = getFCmpCodeWithoutNaN(Condition); 3243 3244 SDNodeFlags Flags; 3245 Flags.copyFMF(*FPMO); 3246 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3247 3248 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3249 I.getType()); 3250 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3251 } 3252 3253 // Check if the condition of the select has one use or two users that are both 3254 // selects with the same condition. 3255 static bool hasOnlySelectUsers(const Value *Cond) { 3256 return llvm::all_of(Cond->users(), [](const Value *V) { 3257 return isa<SelectInst>(V); 3258 }); 3259 } 3260 3261 void SelectionDAGBuilder::visitSelect(const User &I) { 3262 SmallVector<EVT, 4> ValueVTs; 3263 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3264 ValueVTs); 3265 unsigned NumValues = ValueVTs.size(); 3266 if (NumValues == 0) return; 3267 3268 SmallVector<SDValue, 4> Values(NumValues); 3269 SDValue Cond = getValue(I.getOperand(0)); 3270 SDValue LHSVal = getValue(I.getOperand(1)); 3271 SDValue RHSVal = getValue(I.getOperand(2)); 3272 SmallVector<SDValue, 1> BaseOps(1, Cond); 3273 ISD::NodeType OpCode = 3274 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3275 3276 bool IsUnaryAbs = false; 3277 bool Negate = false; 3278 3279 SDNodeFlags Flags; 3280 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3281 Flags.copyFMF(*FPOp); 3282 3283 // Min/max matching is only viable if all output VTs are the same. 3284 if (is_splat(ValueVTs)) { 3285 EVT VT = ValueVTs[0]; 3286 LLVMContext &Ctx = *DAG.getContext(); 3287 auto &TLI = DAG.getTargetLoweringInfo(); 3288 3289 // We care about the legality of the operation after it has been type 3290 // legalized. 3291 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3292 VT = TLI.getTypeToTransformTo(Ctx, VT); 3293 3294 // If the vselect is legal, assume we want to leave this as a vector setcc + 3295 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3296 // min/max is legal on the scalar type. 3297 bool UseScalarMinMax = VT.isVector() && 3298 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3299 3300 Value *LHS, *RHS; 3301 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3302 ISD::NodeType Opc = ISD::DELETED_NODE; 3303 switch (SPR.Flavor) { 3304 case SPF_UMAX: Opc = ISD::UMAX; break; 3305 case SPF_UMIN: Opc = ISD::UMIN; break; 3306 case SPF_SMAX: Opc = ISD::SMAX; break; 3307 case SPF_SMIN: Opc = ISD::SMIN; break; 3308 case SPF_FMINNUM: 3309 switch (SPR.NaNBehavior) { 3310 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3311 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3312 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3313 case SPNB_RETURNS_ANY: { 3314 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3315 Opc = ISD::FMINNUM; 3316 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3317 Opc = ISD::FMINIMUM; 3318 else if (UseScalarMinMax) 3319 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3320 ISD::FMINNUM : ISD::FMINIMUM; 3321 break; 3322 } 3323 } 3324 break; 3325 case SPF_FMAXNUM: 3326 switch (SPR.NaNBehavior) { 3327 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3328 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3329 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3330 case SPNB_RETURNS_ANY: 3331 3332 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3333 Opc = ISD::FMAXNUM; 3334 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3335 Opc = ISD::FMAXIMUM; 3336 else if (UseScalarMinMax) 3337 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3338 ISD::FMAXNUM : ISD::FMAXIMUM; 3339 break; 3340 } 3341 break; 3342 case SPF_NABS: 3343 Negate = true; 3344 LLVM_FALLTHROUGH; 3345 case SPF_ABS: 3346 IsUnaryAbs = true; 3347 Opc = ISD::ABS; 3348 break; 3349 default: break; 3350 } 3351 3352 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3353 (TLI.isOperationLegalOrCustom(Opc, VT) || 3354 (UseScalarMinMax && 3355 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3356 // If the underlying comparison instruction is used by any other 3357 // instruction, the consumed instructions won't be destroyed, so it is 3358 // not profitable to convert to a min/max. 3359 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3360 OpCode = Opc; 3361 LHSVal = getValue(LHS); 3362 RHSVal = getValue(RHS); 3363 BaseOps.clear(); 3364 } 3365 3366 if (IsUnaryAbs) { 3367 OpCode = Opc; 3368 LHSVal = getValue(LHS); 3369 BaseOps.clear(); 3370 } 3371 } 3372 3373 if (IsUnaryAbs) { 3374 for (unsigned i = 0; i != NumValues; ++i) { 3375 SDLoc dl = getCurSDLoc(); 3376 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3377 Values[i] = 3378 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3379 if (Negate) 3380 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3381 Values[i]); 3382 } 3383 } else { 3384 for (unsigned i = 0; i != NumValues; ++i) { 3385 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3386 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3387 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3388 Values[i] = DAG.getNode( 3389 OpCode, getCurSDLoc(), 3390 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3391 } 3392 } 3393 3394 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3395 DAG.getVTList(ValueVTs), Values)); 3396 } 3397 3398 void SelectionDAGBuilder::visitTrunc(const User &I) { 3399 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3400 SDValue N = getValue(I.getOperand(0)); 3401 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3402 I.getType()); 3403 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3404 } 3405 3406 void SelectionDAGBuilder::visitZExt(const User &I) { 3407 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3408 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3409 SDValue N = getValue(I.getOperand(0)); 3410 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3411 I.getType()); 3412 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3413 } 3414 3415 void SelectionDAGBuilder::visitSExt(const User &I) { 3416 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3417 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3418 SDValue N = getValue(I.getOperand(0)); 3419 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3420 I.getType()); 3421 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3422 } 3423 3424 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3425 // FPTrunc is never a no-op cast, no need to check 3426 SDValue N = getValue(I.getOperand(0)); 3427 SDLoc dl = getCurSDLoc(); 3428 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3429 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3430 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3431 DAG.getTargetConstant( 3432 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3433 } 3434 3435 void SelectionDAGBuilder::visitFPExt(const User &I) { 3436 // FPExt is never a no-op cast, no need to check 3437 SDValue N = getValue(I.getOperand(0)); 3438 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3439 I.getType()); 3440 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3441 } 3442 3443 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3444 // FPToUI is never a no-op cast, no need to check 3445 SDValue N = getValue(I.getOperand(0)); 3446 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3447 I.getType()); 3448 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3449 } 3450 3451 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3452 // FPToSI is never a no-op cast, no need to check 3453 SDValue N = getValue(I.getOperand(0)); 3454 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3455 I.getType()); 3456 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3457 } 3458 3459 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3460 // UIToFP is never a no-op cast, no need to check 3461 SDValue N = getValue(I.getOperand(0)); 3462 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3463 I.getType()); 3464 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3465 } 3466 3467 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3468 // SIToFP is never a no-op cast, no need to check 3469 SDValue N = getValue(I.getOperand(0)); 3470 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3471 I.getType()); 3472 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3473 } 3474 3475 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3476 // What to do depends on the size of the integer and the size of the pointer. 3477 // We can either truncate, zero extend, or no-op, accordingly. 3478 SDValue N = getValue(I.getOperand(0)); 3479 auto &TLI = DAG.getTargetLoweringInfo(); 3480 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3481 I.getType()); 3482 EVT PtrMemVT = 3483 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3484 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3485 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3486 setValue(&I, N); 3487 } 3488 3489 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3490 // What to do depends on the size of the integer and the size of the pointer. 3491 // We can either truncate, zero extend, or no-op, accordingly. 3492 SDValue N = getValue(I.getOperand(0)); 3493 auto &TLI = DAG.getTargetLoweringInfo(); 3494 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3495 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3496 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3497 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3498 setValue(&I, N); 3499 } 3500 3501 void SelectionDAGBuilder::visitBitCast(const User &I) { 3502 SDValue N = getValue(I.getOperand(0)); 3503 SDLoc dl = getCurSDLoc(); 3504 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3505 I.getType()); 3506 3507 // BitCast assures us that source and destination are the same size so this is 3508 // either a BITCAST or a no-op. 3509 if (DestVT != N.getValueType()) 3510 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3511 DestVT, N)); // convert types. 3512 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3513 // might fold any kind of constant expression to an integer constant and that 3514 // is not what we are looking for. Only recognize a bitcast of a genuine 3515 // constant integer as an opaque constant. 3516 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3517 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3518 /*isOpaque*/true)); 3519 else 3520 setValue(&I, N); // noop cast. 3521 } 3522 3523 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3524 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3525 const Value *SV = I.getOperand(0); 3526 SDValue N = getValue(SV); 3527 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3528 3529 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3530 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3531 3532 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3533 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3534 3535 setValue(&I, N); 3536 } 3537 3538 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3539 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3540 SDValue InVec = getValue(I.getOperand(0)); 3541 SDValue InVal = getValue(I.getOperand(1)); 3542 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3543 TLI.getVectorIdxTy(DAG.getDataLayout())); 3544 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3545 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3546 InVec, InVal, InIdx)); 3547 } 3548 3549 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3551 SDValue InVec = getValue(I.getOperand(0)); 3552 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3553 TLI.getVectorIdxTy(DAG.getDataLayout())); 3554 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3555 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3556 InVec, InIdx)); 3557 } 3558 3559 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3560 SDValue Src1 = getValue(I.getOperand(0)); 3561 SDValue Src2 = getValue(I.getOperand(1)); 3562 ArrayRef<int> Mask; 3563 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3564 Mask = SVI->getShuffleMask(); 3565 else 3566 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3567 SDLoc DL = getCurSDLoc(); 3568 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3569 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3570 EVT SrcVT = Src1.getValueType(); 3571 3572 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3573 VT.isScalableVector()) { 3574 // Canonical splat form of first element of first input vector. 3575 SDValue FirstElt = 3576 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3577 DAG.getVectorIdxConstant(0, DL)); 3578 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3579 return; 3580 } 3581 3582 // For now, we only handle splats for scalable vectors. 3583 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3584 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3585 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3586 3587 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3588 unsigned MaskNumElts = Mask.size(); 3589 3590 if (SrcNumElts == MaskNumElts) { 3591 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3592 return; 3593 } 3594 3595 // Normalize the shuffle vector since mask and vector length don't match. 3596 if (SrcNumElts < MaskNumElts) { 3597 // Mask is longer than the source vectors. We can use concatenate vector to 3598 // make the mask and vectors lengths match. 3599 3600 if (MaskNumElts % SrcNumElts == 0) { 3601 // Mask length is a multiple of the source vector length. 3602 // Check if the shuffle is some kind of concatenation of the input 3603 // vectors. 3604 unsigned NumConcat = MaskNumElts / SrcNumElts; 3605 bool IsConcat = true; 3606 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3607 for (unsigned i = 0; i != MaskNumElts; ++i) { 3608 int Idx = Mask[i]; 3609 if (Idx < 0) 3610 continue; 3611 // Ensure the indices in each SrcVT sized piece are sequential and that 3612 // the same source is used for the whole piece. 3613 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3614 (ConcatSrcs[i / SrcNumElts] >= 0 && 3615 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3616 IsConcat = false; 3617 break; 3618 } 3619 // Remember which source this index came from. 3620 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3621 } 3622 3623 // The shuffle is concatenating multiple vectors together. Just emit 3624 // a CONCAT_VECTORS operation. 3625 if (IsConcat) { 3626 SmallVector<SDValue, 8> ConcatOps; 3627 for (auto Src : ConcatSrcs) { 3628 if (Src < 0) 3629 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3630 else if (Src == 0) 3631 ConcatOps.push_back(Src1); 3632 else 3633 ConcatOps.push_back(Src2); 3634 } 3635 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3636 return; 3637 } 3638 } 3639 3640 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3641 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3642 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3643 PaddedMaskNumElts); 3644 3645 // Pad both vectors with undefs to make them the same length as the mask. 3646 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3647 3648 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3649 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3650 MOps1[0] = Src1; 3651 MOps2[0] = Src2; 3652 3653 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3654 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3655 3656 // Readjust mask for new input vector length. 3657 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3658 for (unsigned i = 0; i != MaskNumElts; ++i) { 3659 int Idx = Mask[i]; 3660 if (Idx >= (int)SrcNumElts) 3661 Idx -= SrcNumElts - PaddedMaskNumElts; 3662 MappedOps[i] = Idx; 3663 } 3664 3665 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3666 3667 // If the concatenated vector was padded, extract a subvector with the 3668 // correct number of elements. 3669 if (MaskNumElts != PaddedMaskNumElts) 3670 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3671 DAG.getVectorIdxConstant(0, DL)); 3672 3673 setValue(&I, Result); 3674 return; 3675 } 3676 3677 if (SrcNumElts > MaskNumElts) { 3678 // Analyze the access pattern of the vector to see if we can extract 3679 // two subvectors and do the shuffle. 3680 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3681 bool CanExtract = true; 3682 for (int Idx : Mask) { 3683 unsigned Input = 0; 3684 if (Idx < 0) 3685 continue; 3686 3687 if (Idx >= (int)SrcNumElts) { 3688 Input = 1; 3689 Idx -= SrcNumElts; 3690 } 3691 3692 // If all the indices come from the same MaskNumElts sized portion of 3693 // the sources we can use extract. Also make sure the extract wouldn't 3694 // extract past the end of the source. 3695 int NewStartIdx = alignDown(Idx, MaskNumElts); 3696 if (NewStartIdx + MaskNumElts > SrcNumElts || 3697 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3698 CanExtract = false; 3699 // Make sure we always update StartIdx as we use it to track if all 3700 // elements are undef. 3701 StartIdx[Input] = NewStartIdx; 3702 } 3703 3704 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3705 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3706 return; 3707 } 3708 if (CanExtract) { 3709 // Extract appropriate subvector and generate a vector shuffle 3710 for (unsigned Input = 0; Input < 2; ++Input) { 3711 SDValue &Src = Input == 0 ? Src1 : Src2; 3712 if (StartIdx[Input] < 0) 3713 Src = DAG.getUNDEF(VT); 3714 else { 3715 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3716 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3717 } 3718 } 3719 3720 // Calculate new mask. 3721 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3722 for (int &Idx : MappedOps) { 3723 if (Idx >= (int)SrcNumElts) 3724 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3725 else if (Idx >= 0) 3726 Idx -= StartIdx[0]; 3727 } 3728 3729 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3730 return; 3731 } 3732 } 3733 3734 // We can't use either concat vectors or extract subvectors so fall back to 3735 // replacing the shuffle with extract and build vector. 3736 // to insert and build vector. 3737 EVT EltVT = VT.getVectorElementType(); 3738 SmallVector<SDValue,8> Ops; 3739 for (int Idx : Mask) { 3740 SDValue Res; 3741 3742 if (Idx < 0) { 3743 Res = DAG.getUNDEF(EltVT); 3744 } else { 3745 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3746 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3747 3748 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3749 DAG.getVectorIdxConstant(Idx, DL)); 3750 } 3751 3752 Ops.push_back(Res); 3753 } 3754 3755 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3756 } 3757 3758 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3759 ArrayRef<unsigned> Indices; 3760 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3761 Indices = IV->getIndices(); 3762 else 3763 Indices = cast<ConstantExpr>(&I)->getIndices(); 3764 3765 const Value *Op0 = I.getOperand(0); 3766 const Value *Op1 = I.getOperand(1); 3767 Type *AggTy = I.getType(); 3768 Type *ValTy = Op1->getType(); 3769 bool IntoUndef = isa<UndefValue>(Op0); 3770 bool FromUndef = isa<UndefValue>(Op1); 3771 3772 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3773 3774 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3775 SmallVector<EVT, 4> AggValueVTs; 3776 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3777 SmallVector<EVT, 4> ValValueVTs; 3778 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3779 3780 unsigned NumAggValues = AggValueVTs.size(); 3781 unsigned NumValValues = ValValueVTs.size(); 3782 SmallVector<SDValue, 4> Values(NumAggValues); 3783 3784 // Ignore an insertvalue that produces an empty object 3785 if (!NumAggValues) { 3786 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3787 return; 3788 } 3789 3790 SDValue Agg = getValue(Op0); 3791 unsigned i = 0; 3792 // Copy the beginning value(s) from the original aggregate. 3793 for (; i != LinearIndex; ++i) 3794 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3795 SDValue(Agg.getNode(), Agg.getResNo() + i); 3796 // Copy values from the inserted value(s). 3797 if (NumValValues) { 3798 SDValue Val = getValue(Op1); 3799 for (; i != LinearIndex + NumValValues; ++i) 3800 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3801 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3802 } 3803 // Copy remaining value(s) from the original aggregate. 3804 for (; i != NumAggValues; ++i) 3805 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3806 SDValue(Agg.getNode(), Agg.getResNo() + i); 3807 3808 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3809 DAG.getVTList(AggValueVTs), Values)); 3810 } 3811 3812 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3813 ArrayRef<unsigned> Indices; 3814 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3815 Indices = EV->getIndices(); 3816 else 3817 Indices = cast<ConstantExpr>(&I)->getIndices(); 3818 3819 const Value *Op0 = I.getOperand(0); 3820 Type *AggTy = Op0->getType(); 3821 Type *ValTy = I.getType(); 3822 bool OutOfUndef = isa<UndefValue>(Op0); 3823 3824 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3825 3826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3827 SmallVector<EVT, 4> ValValueVTs; 3828 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3829 3830 unsigned NumValValues = ValValueVTs.size(); 3831 3832 // Ignore a extractvalue that produces an empty object 3833 if (!NumValValues) { 3834 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3835 return; 3836 } 3837 3838 SmallVector<SDValue, 4> Values(NumValValues); 3839 3840 SDValue Agg = getValue(Op0); 3841 // Copy out the selected value(s). 3842 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3843 Values[i - LinearIndex] = 3844 OutOfUndef ? 3845 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3846 SDValue(Agg.getNode(), Agg.getResNo() + i); 3847 3848 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3849 DAG.getVTList(ValValueVTs), Values)); 3850 } 3851 3852 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3853 Value *Op0 = I.getOperand(0); 3854 // Note that the pointer operand may be a vector of pointers. Take the scalar 3855 // element which holds a pointer. 3856 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3857 SDValue N = getValue(Op0); 3858 SDLoc dl = getCurSDLoc(); 3859 auto &TLI = DAG.getTargetLoweringInfo(); 3860 3861 // Normalize Vector GEP - all scalar operands should be converted to the 3862 // splat vector. 3863 bool IsVectorGEP = I.getType()->isVectorTy(); 3864 ElementCount VectorElementCount = 3865 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3866 : ElementCount::getFixed(0); 3867 3868 if (IsVectorGEP && !N.getValueType().isVector()) { 3869 LLVMContext &Context = *DAG.getContext(); 3870 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3871 if (VectorElementCount.isScalable()) 3872 N = DAG.getSplatVector(VT, dl, N); 3873 else 3874 N = DAG.getSplatBuildVector(VT, dl, N); 3875 } 3876 3877 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3878 GTI != E; ++GTI) { 3879 const Value *Idx = GTI.getOperand(); 3880 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3881 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3882 if (Field) { 3883 // N = N + Offset 3884 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3885 3886 // In an inbounds GEP with an offset that is nonnegative even when 3887 // interpreted as signed, assume there is no unsigned overflow. 3888 SDNodeFlags Flags; 3889 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3890 Flags.setNoUnsignedWrap(true); 3891 3892 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3893 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3894 } 3895 } else { 3896 // IdxSize is the width of the arithmetic according to IR semantics. 3897 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3898 // (and fix up the result later). 3899 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3900 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3901 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3902 // We intentionally mask away the high bits here; ElementSize may not 3903 // fit in IdxTy. 3904 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3905 bool ElementScalable = ElementSize.isScalable(); 3906 3907 // If this is a scalar constant or a splat vector of constants, 3908 // handle it quickly. 3909 const auto *C = dyn_cast<Constant>(Idx); 3910 if (C && isa<VectorType>(C->getType())) 3911 C = C->getSplatValue(); 3912 3913 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3914 if (CI && CI->isZero()) 3915 continue; 3916 if (CI && !ElementScalable) { 3917 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3918 LLVMContext &Context = *DAG.getContext(); 3919 SDValue OffsVal; 3920 if (IsVectorGEP) 3921 OffsVal = DAG.getConstant( 3922 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3923 else 3924 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3925 3926 // In an inbounds GEP with an offset that is nonnegative even when 3927 // interpreted as signed, assume there is no unsigned overflow. 3928 SDNodeFlags Flags; 3929 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3930 Flags.setNoUnsignedWrap(true); 3931 3932 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3933 3934 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3935 continue; 3936 } 3937 3938 // N = N + Idx * ElementMul; 3939 SDValue IdxN = getValue(Idx); 3940 3941 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3942 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3943 VectorElementCount); 3944 if (VectorElementCount.isScalable()) 3945 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3946 else 3947 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3948 } 3949 3950 // If the index is smaller or larger than intptr_t, truncate or extend 3951 // it. 3952 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3953 3954 if (ElementScalable) { 3955 EVT VScaleTy = N.getValueType().getScalarType(); 3956 SDValue VScale = DAG.getNode( 3957 ISD::VSCALE, dl, VScaleTy, 3958 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3959 if (IsVectorGEP) 3960 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3961 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3962 } else { 3963 // If this is a multiply by a power of two, turn it into a shl 3964 // immediately. This is a very common case. 3965 if (ElementMul != 1) { 3966 if (ElementMul.isPowerOf2()) { 3967 unsigned Amt = ElementMul.logBase2(); 3968 IdxN = DAG.getNode(ISD::SHL, dl, 3969 N.getValueType(), IdxN, 3970 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3971 } else { 3972 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3973 IdxN.getValueType()); 3974 IdxN = DAG.getNode(ISD::MUL, dl, 3975 N.getValueType(), IdxN, Scale); 3976 } 3977 } 3978 } 3979 3980 N = DAG.getNode(ISD::ADD, dl, 3981 N.getValueType(), N, IdxN); 3982 } 3983 } 3984 3985 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3986 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3987 if (IsVectorGEP) { 3988 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3989 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3990 } 3991 3992 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3993 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3994 3995 setValue(&I, N); 3996 } 3997 3998 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3999 // If this is a fixed sized alloca in the entry block of the function, 4000 // allocate it statically on the stack. 4001 if (FuncInfo.StaticAllocaMap.count(&I)) 4002 return; // getValue will auto-populate this. 4003 4004 SDLoc dl = getCurSDLoc(); 4005 Type *Ty = I.getAllocatedType(); 4006 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4007 auto &DL = DAG.getDataLayout(); 4008 uint64_t TySize = DL.getTypeAllocSize(Ty); 4009 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4010 4011 SDValue AllocSize = getValue(I.getArraySize()); 4012 4013 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4014 if (AllocSize.getValueType() != IntPtr) 4015 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4016 4017 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 4018 AllocSize, 4019 DAG.getConstant(TySize, dl, IntPtr)); 4020 4021 // Handle alignment. If the requested alignment is less than or equal to 4022 // the stack alignment, ignore it. If the size is greater than or equal to 4023 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4024 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4025 if (*Alignment <= StackAlign) 4026 Alignment = None; 4027 4028 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4029 // Round the size of the allocation up to the stack alignment size 4030 // by add SA-1 to the size. This doesn't overflow because we're computing 4031 // an address inside an alloca. 4032 SDNodeFlags Flags; 4033 Flags.setNoUnsignedWrap(true); 4034 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4035 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4036 4037 // Mask out the low bits for alignment purposes. 4038 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4039 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4040 4041 SDValue Ops[] = { 4042 getRoot(), AllocSize, 4043 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4044 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4045 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4046 setValue(&I, DSA); 4047 DAG.setRoot(DSA.getValue(1)); 4048 4049 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4050 } 4051 4052 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4053 if (I.isAtomic()) 4054 return visitAtomicLoad(I); 4055 4056 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4057 const Value *SV = I.getOperand(0); 4058 if (TLI.supportSwiftError()) { 4059 // Swifterror values can come from either a function parameter with 4060 // swifterror attribute or an alloca with swifterror attribute. 4061 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4062 if (Arg->hasSwiftErrorAttr()) 4063 return visitLoadFromSwiftError(I); 4064 } 4065 4066 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4067 if (Alloca->isSwiftError()) 4068 return visitLoadFromSwiftError(I); 4069 } 4070 } 4071 4072 SDValue Ptr = getValue(SV); 4073 4074 Type *Ty = I.getType(); 4075 Align Alignment = I.getAlign(); 4076 4077 AAMDNodes AAInfo = I.getAAMetadata(); 4078 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4079 4080 SmallVector<EVT, 4> ValueVTs, MemVTs; 4081 SmallVector<uint64_t, 4> Offsets; 4082 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4083 unsigned NumValues = ValueVTs.size(); 4084 if (NumValues == 0) 4085 return; 4086 4087 bool isVolatile = I.isVolatile(); 4088 4089 SDValue Root; 4090 bool ConstantMemory = false; 4091 if (isVolatile) 4092 // Serialize volatile loads with other side effects. 4093 Root = getRoot(); 4094 else if (NumValues > MaxParallelChains) 4095 Root = getMemoryRoot(); 4096 else if (AA && 4097 AA->pointsToConstantMemory(MemoryLocation( 4098 SV, 4099 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4100 AAInfo))) { 4101 // Do not serialize (non-volatile) loads of constant memory with anything. 4102 Root = DAG.getEntryNode(); 4103 ConstantMemory = true; 4104 } else { 4105 // Do not serialize non-volatile loads against each other. 4106 Root = DAG.getRoot(); 4107 } 4108 4109 SDLoc dl = getCurSDLoc(); 4110 4111 if (isVolatile) 4112 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4113 4114 // An aggregate load cannot wrap around the address space, so offsets to its 4115 // parts don't wrap either. 4116 SDNodeFlags Flags; 4117 Flags.setNoUnsignedWrap(true); 4118 4119 SmallVector<SDValue, 4> Values(NumValues); 4120 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4121 EVT PtrVT = Ptr.getValueType(); 4122 4123 MachineMemOperand::Flags MMOFlags 4124 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4125 4126 unsigned ChainI = 0; 4127 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4128 // Serializing loads here may result in excessive register pressure, and 4129 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4130 // could recover a bit by hoisting nodes upward in the chain by recognizing 4131 // they are side-effect free or do not alias. The optimizer should really 4132 // avoid this case by converting large object/array copies to llvm.memcpy 4133 // (MaxParallelChains should always remain as failsafe). 4134 if (ChainI == MaxParallelChains) { 4135 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4136 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4137 makeArrayRef(Chains.data(), ChainI)); 4138 Root = Chain; 4139 ChainI = 0; 4140 } 4141 SDValue A = DAG.getNode(ISD::ADD, dl, 4142 PtrVT, Ptr, 4143 DAG.getConstant(Offsets[i], dl, PtrVT), 4144 Flags); 4145 4146 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4147 MachinePointerInfo(SV, Offsets[i]), Alignment, 4148 MMOFlags, AAInfo, Ranges); 4149 Chains[ChainI] = L.getValue(1); 4150 4151 if (MemVTs[i] != ValueVTs[i]) 4152 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4153 4154 Values[i] = L; 4155 } 4156 4157 if (!ConstantMemory) { 4158 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4159 makeArrayRef(Chains.data(), ChainI)); 4160 if (isVolatile) 4161 DAG.setRoot(Chain); 4162 else 4163 PendingLoads.push_back(Chain); 4164 } 4165 4166 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4167 DAG.getVTList(ValueVTs), Values)); 4168 } 4169 4170 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4171 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4172 "call visitStoreToSwiftError when backend supports swifterror"); 4173 4174 SmallVector<EVT, 4> ValueVTs; 4175 SmallVector<uint64_t, 4> Offsets; 4176 const Value *SrcV = I.getOperand(0); 4177 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4178 SrcV->getType(), ValueVTs, &Offsets); 4179 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4180 "expect a single EVT for swifterror"); 4181 4182 SDValue Src = getValue(SrcV); 4183 // Create a virtual register, then update the virtual register. 4184 Register VReg = 4185 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4186 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4187 // Chain can be getRoot or getControlRoot. 4188 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4189 SDValue(Src.getNode(), Src.getResNo())); 4190 DAG.setRoot(CopyNode); 4191 } 4192 4193 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4194 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4195 "call visitLoadFromSwiftError when backend supports swifterror"); 4196 4197 assert(!I.isVolatile() && 4198 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4199 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4200 "Support volatile, non temporal, invariant for load_from_swift_error"); 4201 4202 const Value *SV = I.getOperand(0); 4203 Type *Ty = I.getType(); 4204 assert( 4205 (!AA || 4206 !AA->pointsToConstantMemory(MemoryLocation( 4207 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4208 I.getAAMetadata()))) && 4209 "load_from_swift_error should not be constant memory"); 4210 4211 SmallVector<EVT, 4> ValueVTs; 4212 SmallVector<uint64_t, 4> Offsets; 4213 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4214 ValueVTs, &Offsets); 4215 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4216 "expect a single EVT for swifterror"); 4217 4218 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4219 SDValue L = DAG.getCopyFromReg( 4220 getRoot(), getCurSDLoc(), 4221 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4222 4223 setValue(&I, L); 4224 } 4225 4226 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4227 if (I.isAtomic()) 4228 return visitAtomicStore(I); 4229 4230 const Value *SrcV = I.getOperand(0); 4231 const Value *PtrV = I.getOperand(1); 4232 4233 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4234 if (TLI.supportSwiftError()) { 4235 // Swifterror values can come from either a function parameter with 4236 // swifterror attribute or an alloca with swifterror attribute. 4237 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4238 if (Arg->hasSwiftErrorAttr()) 4239 return visitStoreToSwiftError(I); 4240 } 4241 4242 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4243 if (Alloca->isSwiftError()) 4244 return visitStoreToSwiftError(I); 4245 } 4246 } 4247 4248 SmallVector<EVT, 4> ValueVTs, MemVTs; 4249 SmallVector<uint64_t, 4> Offsets; 4250 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4251 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4252 unsigned NumValues = ValueVTs.size(); 4253 if (NumValues == 0) 4254 return; 4255 4256 // Get the lowered operands. Note that we do this after 4257 // checking if NumResults is zero, because with zero results 4258 // the operands won't have values in the map. 4259 SDValue Src = getValue(SrcV); 4260 SDValue Ptr = getValue(PtrV); 4261 4262 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4263 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4264 SDLoc dl = getCurSDLoc(); 4265 Align Alignment = I.getAlign(); 4266 AAMDNodes AAInfo = I.getAAMetadata(); 4267 4268 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4269 4270 // An aggregate load cannot wrap around the address space, so offsets to its 4271 // parts don't wrap either. 4272 SDNodeFlags Flags; 4273 Flags.setNoUnsignedWrap(true); 4274 4275 unsigned ChainI = 0; 4276 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4277 // See visitLoad comments. 4278 if (ChainI == MaxParallelChains) { 4279 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4280 makeArrayRef(Chains.data(), ChainI)); 4281 Root = Chain; 4282 ChainI = 0; 4283 } 4284 SDValue Add = 4285 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4286 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4287 if (MemVTs[i] != ValueVTs[i]) 4288 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4289 SDValue St = 4290 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4291 Alignment, MMOFlags, AAInfo); 4292 Chains[ChainI] = St; 4293 } 4294 4295 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4296 makeArrayRef(Chains.data(), ChainI)); 4297 DAG.setRoot(StoreNode); 4298 } 4299 4300 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4301 bool IsCompressing) { 4302 SDLoc sdl = getCurSDLoc(); 4303 4304 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4305 MaybeAlign &Alignment) { 4306 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4307 Src0 = I.getArgOperand(0); 4308 Ptr = I.getArgOperand(1); 4309 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4310 Mask = I.getArgOperand(3); 4311 }; 4312 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4313 MaybeAlign &Alignment) { 4314 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4315 Src0 = I.getArgOperand(0); 4316 Ptr = I.getArgOperand(1); 4317 Mask = I.getArgOperand(2); 4318 Alignment = None; 4319 }; 4320 4321 Value *PtrOperand, *MaskOperand, *Src0Operand; 4322 MaybeAlign Alignment; 4323 if (IsCompressing) 4324 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4325 else 4326 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4327 4328 SDValue Ptr = getValue(PtrOperand); 4329 SDValue Src0 = getValue(Src0Operand); 4330 SDValue Mask = getValue(MaskOperand); 4331 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4332 4333 EVT VT = Src0.getValueType(); 4334 if (!Alignment) 4335 Alignment = DAG.getEVTAlign(VT); 4336 4337 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4338 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4339 // TODO: Make MachineMemOperands aware of scalable 4340 // vectors. 4341 VT.getStoreSize().getKnownMinSize(), *Alignment, I.getAAMetadata()); 4342 SDValue StoreNode = 4343 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4344 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4345 DAG.setRoot(StoreNode); 4346 setValue(&I, StoreNode); 4347 } 4348 4349 // Get a uniform base for the Gather/Scatter intrinsic. 4350 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4351 // We try to represent it as a base pointer + vector of indices. 4352 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4353 // The first operand of the GEP may be a single pointer or a vector of pointers 4354 // Example: 4355 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4356 // or 4357 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4358 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4359 // 4360 // When the first GEP operand is a single pointer - it is the uniform base we 4361 // are looking for. If first operand of the GEP is a splat vector - we 4362 // extract the splat value and use it as a uniform base. 4363 // In all other cases the function returns 'false'. 4364 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4365 ISD::MemIndexType &IndexType, SDValue &Scale, 4366 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4367 SelectionDAG& DAG = SDB->DAG; 4368 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4369 const DataLayout &DL = DAG.getDataLayout(); 4370 4371 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4372 4373 // Handle splat constant pointer. 4374 if (auto *C = dyn_cast<Constant>(Ptr)) { 4375 C = C->getSplatValue(); 4376 if (!C) 4377 return false; 4378 4379 Base = SDB->getValue(C); 4380 4381 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4382 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4383 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4384 IndexType = ISD::SIGNED_SCALED; 4385 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4386 return true; 4387 } 4388 4389 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4390 if (!GEP || GEP->getParent() != CurBB) 4391 return false; 4392 4393 if (GEP->getNumOperands() != 2) 4394 return false; 4395 4396 const Value *BasePtr = GEP->getPointerOperand(); 4397 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4398 4399 // Make sure the base is scalar and the index is a vector. 4400 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4401 return false; 4402 4403 Base = SDB->getValue(BasePtr); 4404 Index = SDB->getValue(IndexVal); 4405 IndexType = ISD::SIGNED_SCALED; 4406 Scale = DAG.getTargetConstant( 4407 DL.getTypeAllocSize(GEP->getResultElementType()), 4408 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4409 return true; 4410 } 4411 4412 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4413 SDLoc sdl = getCurSDLoc(); 4414 4415 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4416 const Value *Ptr = I.getArgOperand(1); 4417 SDValue Src0 = getValue(I.getArgOperand(0)); 4418 SDValue Mask = getValue(I.getArgOperand(3)); 4419 EVT VT = Src0.getValueType(); 4420 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4421 ->getMaybeAlignValue() 4422 .getValueOr(DAG.getEVTAlign(VT.getScalarType())); 4423 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4424 4425 SDValue Base; 4426 SDValue Index; 4427 ISD::MemIndexType IndexType; 4428 SDValue Scale; 4429 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4430 I.getParent()); 4431 4432 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4433 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4434 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4435 // TODO: Make MachineMemOperands aware of scalable 4436 // vectors. 4437 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4438 if (!UniformBase) { 4439 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4440 Index = getValue(Ptr); 4441 IndexType = ISD::SIGNED_UNSCALED; 4442 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4443 } 4444 4445 EVT IdxVT = Index.getValueType(); 4446 EVT EltTy = IdxVT.getVectorElementType(); 4447 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4448 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4449 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4450 } 4451 4452 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4453 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4454 Ops, MMO, IndexType, false); 4455 DAG.setRoot(Scatter); 4456 setValue(&I, Scatter); 4457 } 4458 4459 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4460 SDLoc sdl = getCurSDLoc(); 4461 4462 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4463 MaybeAlign &Alignment) { 4464 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4465 Ptr = I.getArgOperand(0); 4466 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4467 Mask = I.getArgOperand(2); 4468 Src0 = I.getArgOperand(3); 4469 }; 4470 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4471 MaybeAlign &Alignment) { 4472 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4473 Ptr = I.getArgOperand(0); 4474 Alignment = None; 4475 Mask = I.getArgOperand(1); 4476 Src0 = I.getArgOperand(2); 4477 }; 4478 4479 Value *PtrOperand, *MaskOperand, *Src0Operand; 4480 MaybeAlign Alignment; 4481 if (IsExpanding) 4482 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4483 else 4484 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4485 4486 SDValue Ptr = getValue(PtrOperand); 4487 SDValue Src0 = getValue(Src0Operand); 4488 SDValue Mask = getValue(MaskOperand); 4489 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4490 4491 EVT VT = Src0.getValueType(); 4492 if (!Alignment) 4493 Alignment = DAG.getEVTAlign(VT); 4494 4495 AAMDNodes AAInfo = I.getAAMetadata(); 4496 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4497 4498 // Do not serialize masked loads of constant memory with anything. 4499 MemoryLocation ML; 4500 if (VT.isScalableVector()) 4501 ML = MemoryLocation::getAfter(PtrOperand); 4502 else 4503 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4504 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4505 AAInfo); 4506 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4507 4508 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4509 4510 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4511 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4512 // TODO: Make MachineMemOperands aware of scalable 4513 // vectors. 4514 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4515 4516 SDValue Load = 4517 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4518 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4519 if (AddToChain) 4520 PendingLoads.push_back(Load.getValue(1)); 4521 setValue(&I, Load); 4522 } 4523 4524 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4525 SDLoc sdl = getCurSDLoc(); 4526 4527 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4528 const Value *Ptr = I.getArgOperand(0); 4529 SDValue Src0 = getValue(I.getArgOperand(3)); 4530 SDValue Mask = getValue(I.getArgOperand(2)); 4531 4532 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4533 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4534 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4535 ->getMaybeAlignValue() 4536 .getValueOr(DAG.getEVTAlign(VT.getScalarType())); 4537 4538 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4539 4540 SDValue Root = DAG.getRoot(); 4541 SDValue Base; 4542 SDValue Index; 4543 ISD::MemIndexType IndexType; 4544 SDValue Scale; 4545 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4546 I.getParent()); 4547 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4548 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4549 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4550 // TODO: Make MachineMemOperands aware of scalable 4551 // vectors. 4552 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4553 4554 if (!UniformBase) { 4555 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4556 Index = getValue(Ptr); 4557 IndexType = ISD::SIGNED_UNSCALED; 4558 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4559 } 4560 4561 EVT IdxVT = Index.getValueType(); 4562 EVT EltTy = IdxVT.getVectorElementType(); 4563 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4564 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4565 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4566 } 4567 4568 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4569 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4570 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4571 4572 PendingLoads.push_back(Gather.getValue(1)); 4573 setValue(&I, Gather); 4574 } 4575 4576 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4577 SDLoc dl = getCurSDLoc(); 4578 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4579 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4580 SyncScope::ID SSID = I.getSyncScopeID(); 4581 4582 SDValue InChain = getRoot(); 4583 4584 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4585 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4586 4587 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4588 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4589 4590 MachineFunction &MF = DAG.getMachineFunction(); 4591 MachineMemOperand *MMO = MF.getMachineMemOperand( 4592 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4593 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4594 FailureOrdering); 4595 4596 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4597 dl, MemVT, VTs, InChain, 4598 getValue(I.getPointerOperand()), 4599 getValue(I.getCompareOperand()), 4600 getValue(I.getNewValOperand()), MMO); 4601 4602 SDValue OutChain = L.getValue(2); 4603 4604 setValue(&I, L); 4605 DAG.setRoot(OutChain); 4606 } 4607 4608 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4609 SDLoc dl = getCurSDLoc(); 4610 ISD::NodeType NT; 4611 switch (I.getOperation()) { 4612 default: llvm_unreachable("Unknown atomicrmw operation"); 4613 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4614 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4615 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4616 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4617 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4618 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4619 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4620 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4621 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4622 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4623 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4624 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4625 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4626 } 4627 AtomicOrdering Ordering = I.getOrdering(); 4628 SyncScope::ID SSID = I.getSyncScopeID(); 4629 4630 SDValue InChain = getRoot(); 4631 4632 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4633 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4634 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4635 4636 MachineFunction &MF = DAG.getMachineFunction(); 4637 MachineMemOperand *MMO = MF.getMachineMemOperand( 4638 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4639 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4640 4641 SDValue L = 4642 DAG.getAtomic(NT, dl, MemVT, InChain, 4643 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4644 MMO); 4645 4646 SDValue OutChain = L.getValue(1); 4647 4648 setValue(&I, L); 4649 DAG.setRoot(OutChain); 4650 } 4651 4652 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4653 SDLoc dl = getCurSDLoc(); 4654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4655 SDValue Ops[3]; 4656 Ops[0] = getRoot(); 4657 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4658 TLI.getFenceOperandTy(DAG.getDataLayout())); 4659 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4660 TLI.getFenceOperandTy(DAG.getDataLayout())); 4661 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4662 } 4663 4664 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4665 SDLoc dl = getCurSDLoc(); 4666 AtomicOrdering Order = I.getOrdering(); 4667 SyncScope::ID SSID = I.getSyncScopeID(); 4668 4669 SDValue InChain = getRoot(); 4670 4671 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4672 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4673 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4674 4675 if (!TLI.supportsUnalignedAtomics() && 4676 I.getAlignment() < MemVT.getSizeInBits() / 8) 4677 report_fatal_error("Cannot generate unaligned atomic load"); 4678 4679 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4680 4681 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4682 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4683 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4684 4685 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4686 4687 SDValue Ptr = getValue(I.getPointerOperand()); 4688 4689 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4690 // TODO: Once this is better exercised by tests, it should be merged with 4691 // the normal path for loads to prevent future divergence. 4692 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4693 if (MemVT != VT) 4694 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4695 4696 setValue(&I, L); 4697 SDValue OutChain = L.getValue(1); 4698 if (!I.isUnordered()) 4699 DAG.setRoot(OutChain); 4700 else 4701 PendingLoads.push_back(OutChain); 4702 return; 4703 } 4704 4705 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4706 Ptr, MMO); 4707 4708 SDValue OutChain = L.getValue(1); 4709 if (MemVT != VT) 4710 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4711 4712 setValue(&I, L); 4713 DAG.setRoot(OutChain); 4714 } 4715 4716 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4717 SDLoc dl = getCurSDLoc(); 4718 4719 AtomicOrdering Ordering = I.getOrdering(); 4720 SyncScope::ID SSID = I.getSyncScopeID(); 4721 4722 SDValue InChain = getRoot(); 4723 4724 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4725 EVT MemVT = 4726 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4727 4728 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4729 report_fatal_error("Cannot generate unaligned atomic store"); 4730 4731 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4732 4733 MachineFunction &MF = DAG.getMachineFunction(); 4734 MachineMemOperand *MMO = MF.getMachineMemOperand( 4735 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4736 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4737 4738 SDValue Val = getValue(I.getValueOperand()); 4739 if (Val.getValueType() != MemVT) 4740 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4741 SDValue Ptr = getValue(I.getPointerOperand()); 4742 4743 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4744 // TODO: Once this is better exercised by tests, it should be merged with 4745 // the normal path for stores to prevent future divergence. 4746 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4747 DAG.setRoot(S); 4748 return; 4749 } 4750 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4751 Ptr, Val, MMO); 4752 4753 4754 DAG.setRoot(OutChain); 4755 } 4756 4757 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4758 /// node. 4759 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4760 unsigned Intrinsic) { 4761 // Ignore the callsite's attributes. A specific call site may be marked with 4762 // readnone, but the lowering code will expect the chain based on the 4763 // definition. 4764 const Function *F = I.getCalledFunction(); 4765 bool HasChain = !F->doesNotAccessMemory(); 4766 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4767 4768 // Build the operand list. 4769 SmallVector<SDValue, 8> Ops; 4770 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4771 if (OnlyLoad) { 4772 // We don't need to serialize loads against other loads. 4773 Ops.push_back(DAG.getRoot()); 4774 } else { 4775 Ops.push_back(getRoot()); 4776 } 4777 } 4778 4779 // Info is set by getTgtMemInstrinsic 4780 TargetLowering::IntrinsicInfo Info; 4781 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4782 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4783 DAG.getMachineFunction(), 4784 Intrinsic); 4785 4786 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4787 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4788 Info.opc == ISD::INTRINSIC_W_CHAIN) 4789 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4790 TLI.getPointerTy(DAG.getDataLayout()))); 4791 4792 // Add all operands of the call to the operand list. 4793 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4794 const Value *Arg = I.getArgOperand(i); 4795 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4796 Ops.push_back(getValue(Arg)); 4797 continue; 4798 } 4799 4800 // Use TargetConstant instead of a regular constant for immarg. 4801 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4802 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4803 assert(CI->getBitWidth() <= 64 && 4804 "large intrinsic immediates not handled"); 4805 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4806 } else { 4807 Ops.push_back( 4808 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4809 } 4810 } 4811 4812 SmallVector<EVT, 4> ValueVTs; 4813 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4814 4815 if (HasChain) 4816 ValueVTs.push_back(MVT::Other); 4817 4818 SDVTList VTs = DAG.getVTList(ValueVTs); 4819 4820 // Propagate fast-math-flags from IR to node(s). 4821 SDNodeFlags Flags; 4822 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4823 Flags.copyFMF(*FPMO); 4824 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4825 4826 // Create the node. 4827 SDValue Result; 4828 if (IsTgtIntrinsic) { 4829 // This is target intrinsic that touches memory 4830 Result = 4831 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4832 MachinePointerInfo(Info.ptrVal, Info.offset), 4833 Info.align, Info.flags, Info.size, 4834 I.getAAMetadata()); 4835 } else if (!HasChain) { 4836 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4837 } else if (!I.getType()->isVoidTy()) { 4838 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4839 } else { 4840 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4841 } 4842 4843 if (HasChain) { 4844 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4845 if (OnlyLoad) 4846 PendingLoads.push_back(Chain); 4847 else 4848 DAG.setRoot(Chain); 4849 } 4850 4851 if (!I.getType()->isVoidTy()) { 4852 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4853 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4854 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4855 } else 4856 Result = lowerRangeToAssertZExt(DAG, I, Result); 4857 4858 MaybeAlign Alignment = I.getRetAlign(); 4859 if (!Alignment) 4860 Alignment = F->getAttributes().getRetAlignment(); 4861 // Insert `assertalign` node if there's an alignment. 4862 if (InsertAssertAlign && Alignment) { 4863 Result = 4864 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4865 } 4866 4867 setValue(&I, Result); 4868 } 4869 } 4870 4871 /// GetSignificand - Get the significand and build it into a floating-point 4872 /// number with exponent of 1: 4873 /// 4874 /// Op = (Op & 0x007fffff) | 0x3f800000; 4875 /// 4876 /// where Op is the hexadecimal representation of floating point value. 4877 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4878 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4879 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4880 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4881 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4882 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4883 } 4884 4885 /// GetExponent - Get the exponent: 4886 /// 4887 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4888 /// 4889 /// where Op is the hexadecimal representation of floating point value. 4890 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4891 const TargetLowering &TLI, const SDLoc &dl) { 4892 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4893 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4894 SDValue t1 = DAG.getNode( 4895 ISD::SRL, dl, MVT::i32, t0, 4896 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4897 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4898 DAG.getConstant(127, dl, MVT::i32)); 4899 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4900 } 4901 4902 /// getF32Constant - Get 32-bit floating point constant. 4903 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4904 const SDLoc &dl) { 4905 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4906 MVT::f32); 4907 } 4908 4909 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4910 SelectionDAG &DAG) { 4911 // TODO: What fast-math-flags should be set on the floating-point nodes? 4912 4913 // IntegerPartOfX = ((int32_t)(t0); 4914 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4915 4916 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4917 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4918 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4919 4920 // IntegerPartOfX <<= 23; 4921 IntegerPartOfX = DAG.getNode( 4922 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4923 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4924 DAG.getDataLayout()))); 4925 4926 SDValue TwoToFractionalPartOfX; 4927 if (LimitFloatPrecision <= 6) { 4928 // For floating-point precision of 6: 4929 // 4930 // TwoToFractionalPartOfX = 4931 // 0.997535578f + 4932 // (0.735607626f + 0.252464424f * x) * x; 4933 // 4934 // error 0.0144103317, which is 6 bits 4935 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4936 getF32Constant(DAG, 0x3e814304, dl)); 4937 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4938 getF32Constant(DAG, 0x3f3c50c8, dl)); 4939 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4940 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4941 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4942 } else if (LimitFloatPrecision <= 12) { 4943 // For floating-point precision of 12: 4944 // 4945 // TwoToFractionalPartOfX = 4946 // 0.999892986f + 4947 // (0.696457318f + 4948 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4949 // 4950 // error 0.000107046256, which is 13 to 14 bits 4951 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4952 getF32Constant(DAG, 0x3da235e3, dl)); 4953 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4954 getF32Constant(DAG, 0x3e65b8f3, dl)); 4955 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4956 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4957 getF32Constant(DAG, 0x3f324b07, dl)); 4958 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4959 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4960 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4961 } else { // LimitFloatPrecision <= 18 4962 // For floating-point precision of 18: 4963 // 4964 // TwoToFractionalPartOfX = 4965 // 0.999999982f + 4966 // (0.693148872f + 4967 // (0.240227044f + 4968 // (0.554906021e-1f + 4969 // (0.961591928e-2f + 4970 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4971 // error 2.47208000*10^(-7), which is better than 18 bits 4972 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4973 getF32Constant(DAG, 0x3924b03e, dl)); 4974 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4975 getF32Constant(DAG, 0x3ab24b87, dl)); 4976 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4977 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4978 getF32Constant(DAG, 0x3c1d8c17, dl)); 4979 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4980 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4981 getF32Constant(DAG, 0x3d634a1d, dl)); 4982 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4983 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4984 getF32Constant(DAG, 0x3e75fe14, dl)); 4985 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4986 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4987 getF32Constant(DAG, 0x3f317234, dl)); 4988 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4989 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4990 getF32Constant(DAG, 0x3f800000, dl)); 4991 } 4992 4993 // Add the exponent into the result in integer domain. 4994 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4995 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4996 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4997 } 4998 4999 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5000 /// limited-precision mode. 5001 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5002 const TargetLowering &TLI, SDNodeFlags Flags) { 5003 if (Op.getValueType() == MVT::f32 && 5004 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5005 5006 // Put the exponent in the right bit position for later addition to the 5007 // final result: 5008 // 5009 // t0 = Op * log2(e) 5010 5011 // TODO: What fast-math-flags should be set here? 5012 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5013 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5014 return getLimitedPrecisionExp2(t0, dl, DAG); 5015 } 5016 5017 // No special expansion. 5018 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5019 } 5020 5021 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5022 /// limited-precision mode. 5023 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5024 const TargetLowering &TLI, SDNodeFlags Flags) { 5025 // TODO: What fast-math-flags should be set on the floating-point nodes? 5026 5027 if (Op.getValueType() == MVT::f32 && 5028 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5029 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5030 5031 // Scale the exponent by log(2). 5032 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5033 SDValue LogOfExponent = 5034 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5035 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5036 5037 // Get the significand and build it into a floating-point number with 5038 // exponent of 1. 5039 SDValue X = GetSignificand(DAG, Op1, dl); 5040 5041 SDValue LogOfMantissa; 5042 if (LimitFloatPrecision <= 6) { 5043 // For floating-point precision of 6: 5044 // 5045 // LogofMantissa = 5046 // -1.1609546f + 5047 // (1.4034025f - 0.23903021f * x) * x; 5048 // 5049 // error 0.0034276066, which is better than 8 bits 5050 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5051 getF32Constant(DAG, 0xbe74c456, dl)); 5052 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5053 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5054 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5055 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5056 getF32Constant(DAG, 0x3f949a29, dl)); 5057 } else if (LimitFloatPrecision <= 12) { 5058 // For floating-point precision of 12: 5059 // 5060 // LogOfMantissa = 5061 // -1.7417939f + 5062 // (2.8212026f + 5063 // (-1.4699568f + 5064 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5065 // 5066 // error 0.000061011436, which is 14 bits 5067 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5068 getF32Constant(DAG, 0xbd67b6d6, dl)); 5069 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5070 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5071 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5072 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5073 getF32Constant(DAG, 0x3fbc278b, dl)); 5074 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5075 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5076 getF32Constant(DAG, 0x40348e95, dl)); 5077 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5078 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5079 getF32Constant(DAG, 0x3fdef31a, dl)); 5080 } else { // LimitFloatPrecision <= 18 5081 // For floating-point precision of 18: 5082 // 5083 // LogOfMantissa = 5084 // -2.1072184f + 5085 // (4.2372794f + 5086 // (-3.7029485f + 5087 // (2.2781945f + 5088 // (-0.87823314f + 5089 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5090 // 5091 // error 0.0000023660568, which is better than 18 bits 5092 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5093 getF32Constant(DAG, 0xbc91e5ac, dl)); 5094 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5095 getF32Constant(DAG, 0x3e4350aa, dl)); 5096 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5097 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5098 getF32Constant(DAG, 0x3f60d3e3, dl)); 5099 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5100 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5101 getF32Constant(DAG, 0x4011cdf0, dl)); 5102 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5103 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5104 getF32Constant(DAG, 0x406cfd1c, dl)); 5105 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5106 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5107 getF32Constant(DAG, 0x408797cb, dl)); 5108 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5109 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5110 getF32Constant(DAG, 0x4006dcab, dl)); 5111 } 5112 5113 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5114 } 5115 5116 // No special expansion. 5117 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5118 } 5119 5120 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5121 /// limited-precision mode. 5122 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5123 const TargetLowering &TLI, SDNodeFlags Flags) { 5124 // TODO: What fast-math-flags should be set on the floating-point nodes? 5125 5126 if (Op.getValueType() == MVT::f32 && 5127 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5128 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5129 5130 // Get the exponent. 5131 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5132 5133 // Get the significand and build it into a floating-point number with 5134 // exponent of 1. 5135 SDValue X = GetSignificand(DAG, Op1, dl); 5136 5137 // Different possible minimax approximations of significand in 5138 // floating-point for various degrees of accuracy over [1,2]. 5139 SDValue Log2ofMantissa; 5140 if (LimitFloatPrecision <= 6) { 5141 // For floating-point precision of 6: 5142 // 5143 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5144 // 5145 // error 0.0049451742, which is more than 7 bits 5146 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5147 getF32Constant(DAG, 0xbeb08fe0, dl)); 5148 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5149 getF32Constant(DAG, 0x40019463, dl)); 5150 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5151 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5152 getF32Constant(DAG, 0x3fd6633d, dl)); 5153 } else if (LimitFloatPrecision <= 12) { 5154 // For floating-point precision of 12: 5155 // 5156 // Log2ofMantissa = 5157 // -2.51285454f + 5158 // (4.07009056f + 5159 // (-2.12067489f + 5160 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5161 // 5162 // error 0.0000876136000, which is better than 13 bits 5163 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5164 getF32Constant(DAG, 0xbda7262e, dl)); 5165 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5166 getF32Constant(DAG, 0x3f25280b, dl)); 5167 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5168 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5169 getF32Constant(DAG, 0x4007b923, dl)); 5170 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5171 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5172 getF32Constant(DAG, 0x40823e2f, dl)); 5173 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5174 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5175 getF32Constant(DAG, 0x4020d29c, dl)); 5176 } else { // LimitFloatPrecision <= 18 5177 // For floating-point precision of 18: 5178 // 5179 // Log2ofMantissa = 5180 // -3.0400495f + 5181 // (6.1129976f + 5182 // (-5.3420409f + 5183 // (3.2865683f + 5184 // (-1.2669343f + 5185 // (0.27515199f - 5186 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5187 // 5188 // error 0.0000018516, which is better than 18 bits 5189 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5190 getF32Constant(DAG, 0xbcd2769e, dl)); 5191 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5192 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5193 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5194 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5195 getF32Constant(DAG, 0x3fa22ae7, dl)); 5196 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5197 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5198 getF32Constant(DAG, 0x40525723, dl)); 5199 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5200 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5201 getF32Constant(DAG, 0x40aaf200, dl)); 5202 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5203 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5204 getF32Constant(DAG, 0x40c39dad, dl)); 5205 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5206 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5207 getF32Constant(DAG, 0x4042902c, dl)); 5208 } 5209 5210 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5211 } 5212 5213 // No special expansion. 5214 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5215 } 5216 5217 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5218 /// limited-precision mode. 5219 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5220 const TargetLowering &TLI, SDNodeFlags Flags) { 5221 // TODO: What fast-math-flags should be set on the floating-point nodes? 5222 5223 if (Op.getValueType() == MVT::f32 && 5224 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5225 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5226 5227 // Scale the exponent by log10(2) [0.30102999f]. 5228 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5229 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5230 getF32Constant(DAG, 0x3e9a209a, dl)); 5231 5232 // Get the significand and build it into a floating-point number with 5233 // exponent of 1. 5234 SDValue X = GetSignificand(DAG, Op1, dl); 5235 5236 SDValue Log10ofMantissa; 5237 if (LimitFloatPrecision <= 6) { 5238 // For floating-point precision of 6: 5239 // 5240 // Log10ofMantissa = 5241 // -0.50419619f + 5242 // (0.60948995f - 0.10380950f * x) * x; 5243 // 5244 // error 0.0014886165, which is 6 bits 5245 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5246 getF32Constant(DAG, 0xbdd49a13, dl)); 5247 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5248 getF32Constant(DAG, 0x3f1c0789, dl)); 5249 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5250 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5251 getF32Constant(DAG, 0x3f011300, dl)); 5252 } else if (LimitFloatPrecision <= 12) { 5253 // For floating-point precision of 12: 5254 // 5255 // Log10ofMantissa = 5256 // -0.64831180f + 5257 // (0.91751397f + 5258 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5259 // 5260 // error 0.00019228036, which is better than 12 bits 5261 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5262 getF32Constant(DAG, 0x3d431f31, dl)); 5263 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5264 getF32Constant(DAG, 0x3ea21fb2, dl)); 5265 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5266 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5267 getF32Constant(DAG, 0x3f6ae232, dl)); 5268 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5269 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5270 getF32Constant(DAG, 0x3f25f7c3, dl)); 5271 } else { // LimitFloatPrecision <= 18 5272 // For floating-point precision of 18: 5273 // 5274 // Log10ofMantissa = 5275 // -0.84299375f + 5276 // (1.5327582f + 5277 // (-1.0688956f + 5278 // (0.49102474f + 5279 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5280 // 5281 // error 0.0000037995730, which is better than 18 bits 5282 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5283 getF32Constant(DAG, 0x3c5d51ce, dl)); 5284 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5285 getF32Constant(DAG, 0x3e00685a, dl)); 5286 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5287 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5288 getF32Constant(DAG, 0x3efb6798, dl)); 5289 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5290 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5291 getF32Constant(DAG, 0x3f88d192, dl)); 5292 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5293 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5294 getF32Constant(DAG, 0x3fc4316c, dl)); 5295 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5296 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5297 getF32Constant(DAG, 0x3f57ce70, dl)); 5298 } 5299 5300 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5301 } 5302 5303 // No special expansion. 5304 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5305 } 5306 5307 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5308 /// limited-precision mode. 5309 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5310 const TargetLowering &TLI, SDNodeFlags Flags) { 5311 if (Op.getValueType() == MVT::f32 && 5312 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5313 return getLimitedPrecisionExp2(Op, dl, DAG); 5314 5315 // No special expansion. 5316 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5317 } 5318 5319 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5320 /// limited-precision mode with x == 10.0f. 5321 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5322 SelectionDAG &DAG, const TargetLowering &TLI, 5323 SDNodeFlags Flags) { 5324 bool IsExp10 = false; 5325 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5326 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5327 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5328 APFloat Ten(10.0f); 5329 IsExp10 = LHSC->isExactlyValue(Ten); 5330 } 5331 } 5332 5333 // TODO: What fast-math-flags should be set on the FMUL node? 5334 if (IsExp10) { 5335 // Put the exponent in the right bit position for later addition to the 5336 // final result: 5337 // 5338 // #define LOG2OF10 3.3219281f 5339 // t0 = Op * LOG2OF10; 5340 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5341 getF32Constant(DAG, 0x40549a78, dl)); 5342 return getLimitedPrecisionExp2(t0, dl, DAG); 5343 } 5344 5345 // No special expansion. 5346 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5347 } 5348 5349 /// ExpandPowI - Expand a llvm.powi intrinsic. 5350 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5351 SelectionDAG &DAG) { 5352 // If RHS is a constant, we can expand this out to a multiplication tree, 5353 // otherwise we end up lowering to a call to __powidf2 (for example). When 5354 // optimizing for size, we only want to do this if the expansion would produce 5355 // a small number of multiplies, otherwise we do the full expansion. 5356 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5357 // Get the exponent as a positive value. 5358 unsigned Val = RHSC->getSExtValue(); 5359 if ((int)Val < 0) Val = -Val; 5360 5361 // powi(x, 0) -> 1.0 5362 if (Val == 0) 5363 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5364 5365 bool OptForSize = DAG.shouldOptForSize(); 5366 if (!OptForSize || 5367 // If optimizing for size, don't insert too many multiplies. 5368 // This inserts up to 5 multiplies. 5369 countPopulation(Val) + Log2_32(Val) < 7) { 5370 // We use the simple binary decomposition method to generate the multiply 5371 // sequence. There are more optimal ways to do this (for example, 5372 // powi(x,15) generates one more multiply than it should), but this has 5373 // the benefit of being both really simple and much better than a libcall. 5374 SDValue Res; // Logically starts equal to 1.0 5375 SDValue CurSquare = LHS; 5376 // TODO: Intrinsics should have fast-math-flags that propagate to these 5377 // nodes. 5378 while (Val) { 5379 if (Val & 1) { 5380 if (Res.getNode()) 5381 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5382 else 5383 Res = CurSquare; // 1.0*CurSquare. 5384 } 5385 5386 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5387 CurSquare, CurSquare); 5388 Val >>= 1; 5389 } 5390 5391 // If the original was negative, invert the result, producing 1/(x*x*x). 5392 if (RHSC->getSExtValue() < 0) 5393 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5394 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5395 return Res; 5396 } 5397 } 5398 5399 // Otherwise, expand to a libcall. 5400 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5401 } 5402 5403 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5404 SDValue LHS, SDValue RHS, SDValue Scale, 5405 SelectionDAG &DAG, const TargetLowering &TLI) { 5406 EVT VT = LHS.getValueType(); 5407 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5408 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5409 LLVMContext &Ctx = *DAG.getContext(); 5410 5411 // If the type is legal but the operation isn't, this node might survive all 5412 // the way to operation legalization. If we end up there and we do not have 5413 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5414 // node. 5415 5416 // Coax the legalizer into expanding the node during type legalization instead 5417 // by bumping the size by one bit. This will force it to Promote, enabling the 5418 // early expansion and avoiding the need to expand later. 5419 5420 // We don't have to do this if Scale is 0; that can always be expanded, unless 5421 // it's a saturating signed operation. Those can experience true integer 5422 // division overflow, a case which we must avoid. 5423 5424 // FIXME: We wouldn't have to do this (or any of the early 5425 // expansion/promotion) if it was possible to expand a libcall of an 5426 // illegal type during operation legalization. But it's not, so things 5427 // get a bit hacky. 5428 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5429 if ((ScaleInt > 0 || (Saturating && Signed)) && 5430 (TLI.isTypeLegal(VT) || 5431 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5432 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5433 Opcode, VT, ScaleInt); 5434 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5435 EVT PromVT; 5436 if (VT.isScalarInteger()) 5437 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5438 else if (VT.isVector()) { 5439 PromVT = VT.getVectorElementType(); 5440 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5441 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5442 } else 5443 llvm_unreachable("Wrong VT for DIVFIX?"); 5444 if (Signed) { 5445 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5446 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5447 } else { 5448 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5449 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5450 } 5451 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5452 // For saturating operations, we need to shift up the LHS to get the 5453 // proper saturation width, and then shift down again afterwards. 5454 if (Saturating) 5455 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5456 DAG.getConstant(1, DL, ShiftTy)); 5457 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5458 if (Saturating) 5459 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5460 DAG.getConstant(1, DL, ShiftTy)); 5461 return DAG.getZExtOrTrunc(Res, DL, VT); 5462 } 5463 } 5464 5465 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5466 } 5467 5468 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5469 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5470 static void 5471 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5472 const SDValue &N) { 5473 switch (N.getOpcode()) { 5474 case ISD::CopyFromReg: { 5475 SDValue Op = N.getOperand(1); 5476 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5477 Op.getValueType().getSizeInBits()); 5478 return; 5479 } 5480 case ISD::BITCAST: 5481 case ISD::AssertZext: 5482 case ISD::AssertSext: 5483 case ISD::TRUNCATE: 5484 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5485 return; 5486 case ISD::BUILD_PAIR: 5487 case ISD::BUILD_VECTOR: 5488 case ISD::CONCAT_VECTORS: 5489 for (SDValue Op : N->op_values()) 5490 getUnderlyingArgRegs(Regs, Op); 5491 return; 5492 default: 5493 return; 5494 } 5495 } 5496 5497 /// If the DbgValueInst is a dbg_value of a function argument, create the 5498 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5499 /// instruction selection, they will be inserted to the entry BB. 5500 /// We don't currently support this for variadic dbg_values, as they shouldn't 5501 /// appear for function arguments or in the prologue. 5502 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5503 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5504 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5505 const Argument *Arg = dyn_cast<Argument>(V); 5506 if (!Arg) 5507 return false; 5508 5509 MachineFunction &MF = DAG.getMachineFunction(); 5510 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5511 5512 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5513 // we've been asked to pursue. 5514 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5515 bool Indirect) { 5516 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5517 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5518 // pointing at the VReg, which will be patched up later. 5519 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5520 auto MIB = BuildMI(MF, DL, Inst); 5521 MIB.addReg(Reg); 5522 MIB.addImm(0); 5523 MIB.addMetadata(Variable); 5524 auto *NewDIExpr = FragExpr; 5525 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5526 // the DIExpression. 5527 if (Indirect) 5528 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5529 MIB.addMetadata(NewDIExpr); 5530 return MIB; 5531 } else { 5532 // Create a completely standard DBG_VALUE. 5533 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5534 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5535 } 5536 }; 5537 5538 if (!IsDbgDeclare) { 5539 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5540 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5541 // the entry block. 5542 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5543 if (!IsInEntryBlock) 5544 return false; 5545 5546 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5547 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5548 // variable that also is a param. 5549 // 5550 // Although, if we are at the top of the entry block already, we can still 5551 // emit using ArgDbgValue. This might catch some situations when the 5552 // dbg.value refers to an argument that isn't used in the entry block, so 5553 // any CopyToReg node would be optimized out and the only way to express 5554 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5555 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5556 // we should only emit as ArgDbgValue if the Variable is an argument to the 5557 // current function, and the dbg.value intrinsic is found in the entry 5558 // block. 5559 bool VariableIsFunctionInputArg = Variable->isParameter() && 5560 !DL->getInlinedAt(); 5561 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5562 if (!IsInPrologue && !VariableIsFunctionInputArg) 5563 return false; 5564 5565 // Here we assume that a function argument on IR level only can be used to 5566 // describe one input parameter on source level. If we for example have 5567 // source code like this 5568 // 5569 // struct A { long x, y; }; 5570 // void foo(struct A a, long b) { 5571 // ... 5572 // b = a.x; 5573 // ... 5574 // } 5575 // 5576 // and IR like this 5577 // 5578 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5579 // entry: 5580 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5581 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5582 // call void @llvm.dbg.value(metadata i32 %b, "b", 5583 // ... 5584 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5585 // ... 5586 // 5587 // then the last dbg.value is describing a parameter "b" using a value that 5588 // is an argument. But since we already has used %a1 to describe a parameter 5589 // we should not handle that last dbg.value here (that would result in an 5590 // incorrect hoisting of the DBG_VALUE to the function entry). 5591 // Notice that we allow one dbg.value per IR level argument, to accommodate 5592 // for the situation with fragments above. 5593 if (VariableIsFunctionInputArg) { 5594 unsigned ArgNo = Arg->getArgNo(); 5595 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5596 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5597 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5598 return false; 5599 FuncInfo.DescribedArgs.set(ArgNo); 5600 } 5601 } 5602 5603 bool IsIndirect = false; 5604 Optional<MachineOperand> Op; 5605 // Some arguments' frame index is recorded during argument lowering. 5606 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5607 if (FI != std::numeric_limits<int>::max()) 5608 Op = MachineOperand::CreateFI(FI); 5609 5610 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5611 if (!Op && N.getNode()) { 5612 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5613 Register Reg; 5614 if (ArgRegsAndSizes.size() == 1) 5615 Reg = ArgRegsAndSizes.front().first; 5616 5617 if (Reg && Reg.isVirtual()) { 5618 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5619 Register PR = RegInfo.getLiveInPhysReg(Reg); 5620 if (PR) 5621 Reg = PR; 5622 } 5623 if (Reg) { 5624 Op = MachineOperand::CreateReg(Reg, false); 5625 IsIndirect = IsDbgDeclare; 5626 } 5627 } 5628 5629 if (!Op && N.getNode()) { 5630 // Check if frame index is available. 5631 SDValue LCandidate = peekThroughBitcasts(N); 5632 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5633 if (FrameIndexSDNode *FINode = 5634 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5635 Op = MachineOperand::CreateFI(FINode->getIndex()); 5636 } 5637 5638 if (!Op) { 5639 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5640 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5641 SplitRegs) { 5642 unsigned Offset = 0; 5643 for (const auto &RegAndSize : SplitRegs) { 5644 // If the expression is already a fragment, the current register 5645 // offset+size might extend beyond the fragment. In this case, only 5646 // the register bits that are inside the fragment are relevant. 5647 int RegFragmentSizeInBits = RegAndSize.second; 5648 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5649 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5650 // The register is entirely outside the expression fragment, 5651 // so is irrelevant for debug info. 5652 if (Offset >= ExprFragmentSizeInBits) 5653 break; 5654 // The register is partially outside the expression fragment, only 5655 // the low bits within the fragment are relevant for debug info. 5656 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5657 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5658 } 5659 } 5660 5661 auto FragmentExpr = DIExpression::createFragmentExpression( 5662 Expr, Offset, RegFragmentSizeInBits); 5663 Offset += RegAndSize.second; 5664 // If a valid fragment expression cannot be created, the variable's 5665 // correct value cannot be determined and so it is set as Undef. 5666 if (!FragmentExpr) { 5667 SDDbgValue *SDV = DAG.getConstantDbgValue( 5668 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5669 DAG.AddDbgValue(SDV, false); 5670 continue; 5671 } 5672 MachineInstr *NewMI = 5673 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare); 5674 FuncInfo.ArgDbgValues.push_back(NewMI); 5675 } 5676 }; 5677 5678 // Check if ValueMap has reg number. 5679 DenseMap<const Value *, Register>::const_iterator 5680 VMI = FuncInfo.ValueMap.find(V); 5681 if (VMI != FuncInfo.ValueMap.end()) { 5682 const auto &TLI = DAG.getTargetLoweringInfo(); 5683 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5684 V->getType(), None); 5685 if (RFV.occupiesMultipleRegs()) { 5686 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5687 return true; 5688 } 5689 5690 Op = MachineOperand::CreateReg(VMI->second, false); 5691 IsIndirect = IsDbgDeclare; 5692 } else if (ArgRegsAndSizes.size() > 1) { 5693 // This was split due to the calling convention, and no virtual register 5694 // mapping exists for the value. 5695 splitMultiRegDbgValue(ArgRegsAndSizes); 5696 return true; 5697 } 5698 } 5699 5700 if (!Op) 5701 return false; 5702 5703 assert(Variable->isValidLocationForIntrinsic(DL) && 5704 "Expected inlined-at fields to agree"); 5705 MachineInstr *NewMI = nullptr; 5706 5707 if (Op->isReg()) 5708 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5709 else 5710 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5711 Variable, Expr); 5712 5713 FuncInfo.ArgDbgValues.push_back(NewMI); 5714 return true; 5715 } 5716 5717 /// Return the appropriate SDDbgValue based on N. 5718 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5719 DILocalVariable *Variable, 5720 DIExpression *Expr, 5721 const DebugLoc &dl, 5722 unsigned DbgSDNodeOrder) { 5723 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5724 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5725 // stack slot locations. 5726 // 5727 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5728 // debug values here after optimization: 5729 // 5730 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5731 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5732 // 5733 // Both describe the direct values of their associated variables. 5734 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5735 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5736 } 5737 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5738 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5739 } 5740 5741 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5742 switch (Intrinsic) { 5743 case Intrinsic::smul_fix: 5744 return ISD::SMULFIX; 5745 case Intrinsic::umul_fix: 5746 return ISD::UMULFIX; 5747 case Intrinsic::smul_fix_sat: 5748 return ISD::SMULFIXSAT; 5749 case Intrinsic::umul_fix_sat: 5750 return ISD::UMULFIXSAT; 5751 case Intrinsic::sdiv_fix: 5752 return ISD::SDIVFIX; 5753 case Intrinsic::udiv_fix: 5754 return ISD::UDIVFIX; 5755 case Intrinsic::sdiv_fix_sat: 5756 return ISD::SDIVFIXSAT; 5757 case Intrinsic::udiv_fix_sat: 5758 return ISD::UDIVFIXSAT; 5759 default: 5760 llvm_unreachable("Unhandled fixed point intrinsic"); 5761 } 5762 } 5763 5764 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5765 const char *FunctionName) { 5766 assert(FunctionName && "FunctionName must not be nullptr"); 5767 SDValue Callee = DAG.getExternalSymbol( 5768 FunctionName, 5769 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5770 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5771 } 5772 5773 /// Given a @llvm.call.preallocated.setup, return the corresponding 5774 /// preallocated call. 5775 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5776 assert(cast<CallBase>(PreallocatedSetup) 5777 ->getCalledFunction() 5778 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5779 "expected call_preallocated_setup Value"); 5780 for (auto *U : PreallocatedSetup->users()) { 5781 auto *UseCall = cast<CallBase>(U); 5782 const Function *Fn = UseCall->getCalledFunction(); 5783 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5784 return UseCall; 5785 } 5786 } 5787 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5788 } 5789 5790 /// Lower the call to the specified intrinsic function. 5791 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5792 unsigned Intrinsic) { 5793 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5794 SDLoc sdl = getCurSDLoc(); 5795 DebugLoc dl = getCurDebugLoc(); 5796 SDValue Res; 5797 5798 SDNodeFlags Flags; 5799 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5800 Flags.copyFMF(*FPOp); 5801 5802 switch (Intrinsic) { 5803 default: 5804 // By default, turn this into a target intrinsic node. 5805 visitTargetIntrinsic(I, Intrinsic); 5806 return; 5807 case Intrinsic::vscale: { 5808 match(&I, m_VScale(DAG.getDataLayout())); 5809 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5810 setValue(&I, 5811 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5812 return; 5813 } 5814 case Intrinsic::vastart: visitVAStart(I); return; 5815 case Intrinsic::vaend: visitVAEnd(I); return; 5816 case Intrinsic::vacopy: visitVACopy(I); return; 5817 case Intrinsic::returnaddress: 5818 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5819 TLI.getPointerTy(DAG.getDataLayout()), 5820 getValue(I.getArgOperand(0)))); 5821 return; 5822 case Intrinsic::addressofreturnaddress: 5823 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5824 TLI.getPointerTy(DAG.getDataLayout()))); 5825 return; 5826 case Intrinsic::sponentry: 5827 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5828 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5829 return; 5830 case Intrinsic::frameaddress: 5831 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5832 TLI.getFrameIndexTy(DAG.getDataLayout()), 5833 getValue(I.getArgOperand(0)))); 5834 return; 5835 case Intrinsic::read_volatile_register: 5836 case Intrinsic::read_register: { 5837 Value *Reg = I.getArgOperand(0); 5838 SDValue Chain = getRoot(); 5839 SDValue RegName = 5840 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5841 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5842 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5843 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5844 setValue(&I, Res); 5845 DAG.setRoot(Res.getValue(1)); 5846 return; 5847 } 5848 case Intrinsic::write_register: { 5849 Value *Reg = I.getArgOperand(0); 5850 Value *RegValue = I.getArgOperand(1); 5851 SDValue Chain = getRoot(); 5852 SDValue RegName = 5853 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5854 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5855 RegName, getValue(RegValue))); 5856 return; 5857 } 5858 case Intrinsic::memcpy: { 5859 const auto &MCI = cast<MemCpyInst>(I); 5860 SDValue Op1 = getValue(I.getArgOperand(0)); 5861 SDValue Op2 = getValue(I.getArgOperand(1)); 5862 SDValue Op3 = getValue(I.getArgOperand(2)); 5863 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5864 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5865 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5866 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5867 bool isVol = MCI.isVolatile(); 5868 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5869 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5870 // node. 5871 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5872 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5873 /* AlwaysInline */ false, isTC, 5874 MachinePointerInfo(I.getArgOperand(0)), 5875 MachinePointerInfo(I.getArgOperand(1)), 5876 I.getAAMetadata()); 5877 updateDAGForMaybeTailCall(MC); 5878 return; 5879 } 5880 case Intrinsic::memcpy_inline: { 5881 const auto &MCI = cast<MemCpyInlineInst>(I); 5882 SDValue Dst = getValue(I.getArgOperand(0)); 5883 SDValue Src = getValue(I.getArgOperand(1)); 5884 SDValue Size = getValue(I.getArgOperand(2)); 5885 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5886 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5887 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5888 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5889 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5890 bool isVol = MCI.isVolatile(); 5891 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5892 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5893 // node. 5894 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5895 /* AlwaysInline */ true, isTC, 5896 MachinePointerInfo(I.getArgOperand(0)), 5897 MachinePointerInfo(I.getArgOperand(1)), 5898 I.getAAMetadata()); 5899 updateDAGForMaybeTailCall(MC); 5900 return; 5901 } 5902 case Intrinsic::memset: { 5903 const auto &MSI = cast<MemSetInst>(I); 5904 SDValue Op1 = getValue(I.getArgOperand(0)); 5905 SDValue Op2 = getValue(I.getArgOperand(1)); 5906 SDValue Op3 = getValue(I.getArgOperand(2)); 5907 // @llvm.memset defines 0 and 1 to both mean no alignment. 5908 Align Alignment = MSI.getDestAlign().valueOrOne(); 5909 bool isVol = MSI.isVolatile(); 5910 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5911 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5912 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5913 MachinePointerInfo(I.getArgOperand(0)), 5914 I.getAAMetadata()); 5915 updateDAGForMaybeTailCall(MS); 5916 return; 5917 } 5918 case Intrinsic::memmove: { 5919 const auto &MMI = cast<MemMoveInst>(I); 5920 SDValue Op1 = getValue(I.getArgOperand(0)); 5921 SDValue Op2 = getValue(I.getArgOperand(1)); 5922 SDValue Op3 = getValue(I.getArgOperand(2)); 5923 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5924 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5925 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5926 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5927 bool isVol = MMI.isVolatile(); 5928 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5929 // FIXME: Support passing different dest/src alignments to the memmove DAG 5930 // node. 5931 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5932 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5933 isTC, MachinePointerInfo(I.getArgOperand(0)), 5934 MachinePointerInfo(I.getArgOperand(1)), 5935 I.getAAMetadata()); 5936 updateDAGForMaybeTailCall(MM); 5937 return; 5938 } 5939 case Intrinsic::memcpy_element_unordered_atomic: { 5940 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5941 SDValue Dst = getValue(MI.getRawDest()); 5942 SDValue Src = getValue(MI.getRawSource()); 5943 SDValue Length = getValue(MI.getLength()); 5944 5945 unsigned DstAlign = MI.getDestAlignment(); 5946 unsigned SrcAlign = MI.getSourceAlignment(); 5947 Type *LengthTy = MI.getLength()->getType(); 5948 unsigned ElemSz = MI.getElementSizeInBytes(); 5949 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5950 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5951 SrcAlign, Length, LengthTy, ElemSz, isTC, 5952 MachinePointerInfo(MI.getRawDest()), 5953 MachinePointerInfo(MI.getRawSource())); 5954 updateDAGForMaybeTailCall(MC); 5955 return; 5956 } 5957 case Intrinsic::memmove_element_unordered_atomic: { 5958 auto &MI = cast<AtomicMemMoveInst>(I); 5959 SDValue Dst = getValue(MI.getRawDest()); 5960 SDValue Src = getValue(MI.getRawSource()); 5961 SDValue Length = getValue(MI.getLength()); 5962 5963 unsigned DstAlign = MI.getDestAlignment(); 5964 unsigned SrcAlign = MI.getSourceAlignment(); 5965 Type *LengthTy = MI.getLength()->getType(); 5966 unsigned ElemSz = MI.getElementSizeInBytes(); 5967 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5968 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5969 SrcAlign, Length, LengthTy, ElemSz, isTC, 5970 MachinePointerInfo(MI.getRawDest()), 5971 MachinePointerInfo(MI.getRawSource())); 5972 updateDAGForMaybeTailCall(MC); 5973 return; 5974 } 5975 case Intrinsic::memset_element_unordered_atomic: { 5976 auto &MI = cast<AtomicMemSetInst>(I); 5977 SDValue Dst = getValue(MI.getRawDest()); 5978 SDValue Val = getValue(MI.getValue()); 5979 SDValue Length = getValue(MI.getLength()); 5980 5981 unsigned DstAlign = MI.getDestAlignment(); 5982 Type *LengthTy = MI.getLength()->getType(); 5983 unsigned ElemSz = MI.getElementSizeInBytes(); 5984 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5985 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5986 LengthTy, ElemSz, isTC, 5987 MachinePointerInfo(MI.getRawDest())); 5988 updateDAGForMaybeTailCall(MC); 5989 return; 5990 } 5991 case Intrinsic::call_preallocated_setup: { 5992 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5993 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5994 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5995 getRoot(), SrcValue); 5996 setValue(&I, Res); 5997 DAG.setRoot(Res); 5998 return; 5999 } 6000 case Intrinsic::call_preallocated_arg: { 6001 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6002 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6003 SDValue Ops[3]; 6004 Ops[0] = getRoot(); 6005 Ops[1] = SrcValue; 6006 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6007 MVT::i32); // arg index 6008 SDValue Res = DAG.getNode( 6009 ISD::PREALLOCATED_ARG, sdl, 6010 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6011 setValue(&I, Res); 6012 DAG.setRoot(Res.getValue(1)); 6013 return; 6014 } 6015 case Intrinsic::dbg_addr: 6016 case Intrinsic::dbg_declare: { 6017 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6018 // they are non-variadic. 6019 const auto &DI = cast<DbgVariableIntrinsic>(I); 6020 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6021 DILocalVariable *Variable = DI.getVariable(); 6022 DIExpression *Expression = DI.getExpression(); 6023 dropDanglingDebugInfo(Variable, Expression); 6024 assert(Variable && "Missing variable"); 6025 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6026 << "\n"); 6027 // Check if address has undef value. 6028 const Value *Address = DI.getVariableLocationOp(0); 6029 if (!Address || isa<UndefValue>(Address) || 6030 (Address->use_empty() && !isa<Argument>(Address))) { 6031 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6032 << " (bad/undef/unused-arg address)\n"); 6033 return; 6034 } 6035 6036 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6037 6038 // Check if this variable can be described by a frame index, typically 6039 // either as a static alloca or a byval parameter. 6040 int FI = std::numeric_limits<int>::max(); 6041 if (const auto *AI = 6042 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6043 if (AI->isStaticAlloca()) { 6044 auto I = FuncInfo.StaticAllocaMap.find(AI); 6045 if (I != FuncInfo.StaticAllocaMap.end()) 6046 FI = I->second; 6047 } 6048 } else if (const auto *Arg = dyn_cast<Argument>( 6049 Address->stripInBoundsConstantOffsets())) { 6050 FI = FuncInfo.getArgumentFrameIndex(Arg); 6051 } 6052 6053 // llvm.dbg.addr is control dependent and always generates indirect 6054 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6055 // the MachineFunction variable table. 6056 if (FI != std::numeric_limits<int>::max()) { 6057 if (Intrinsic == Intrinsic::dbg_addr) { 6058 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6059 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6060 dl, SDNodeOrder); 6061 DAG.AddDbgValue(SDV, isParameter); 6062 } else { 6063 LLVM_DEBUG(dbgs() << "Skipping " << DI 6064 << " (variable info stashed in MF side table)\n"); 6065 } 6066 return; 6067 } 6068 6069 SDValue &N = NodeMap[Address]; 6070 if (!N.getNode() && isa<Argument>(Address)) 6071 // Check unused arguments map. 6072 N = UnusedArgNodeMap[Address]; 6073 SDDbgValue *SDV; 6074 if (N.getNode()) { 6075 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6076 Address = BCI->getOperand(0); 6077 // Parameters are handled specially. 6078 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6079 if (isParameter && FINode) { 6080 // Byval parameter. We have a frame index at this point. 6081 SDV = 6082 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6083 /*IsIndirect*/ true, dl, SDNodeOrder); 6084 } else if (isa<Argument>(Address)) { 6085 // Address is an argument, so try to emit its dbg value using 6086 // virtual register info from the FuncInfo.ValueMap. 6087 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6088 return; 6089 } else { 6090 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6091 true, dl, SDNodeOrder); 6092 } 6093 DAG.AddDbgValue(SDV, isParameter); 6094 } else { 6095 // If Address is an argument then try to emit its dbg value using 6096 // virtual register info from the FuncInfo.ValueMap. 6097 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6098 N)) { 6099 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6100 << " (could not emit func-arg dbg_value)\n"); 6101 } 6102 } 6103 return; 6104 } 6105 case Intrinsic::dbg_label: { 6106 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6107 DILabel *Label = DI.getLabel(); 6108 assert(Label && "Missing label"); 6109 6110 SDDbgLabel *SDV; 6111 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6112 DAG.AddDbgLabel(SDV); 6113 return; 6114 } 6115 case Intrinsic::dbg_value: { 6116 const DbgValueInst &DI = cast<DbgValueInst>(I); 6117 assert(DI.getVariable() && "Missing variable"); 6118 6119 DILocalVariable *Variable = DI.getVariable(); 6120 DIExpression *Expression = DI.getExpression(); 6121 dropDanglingDebugInfo(Variable, Expression); 6122 SmallVector<Value *, 4> Values(DI.getValues()); 6123 if (Values.empty()) 6124 return; 6125 6126 if (llvm::is_contained(Values, nullptr)) 6127 return; 6128 6129 bool IsVariadic = DI.hasArgList(); 6130 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6131 SDNodeOrder, IsVariadic)) 6132 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6133 return; 6134 } 6135 6136 case Intrinsic::eh_typeid_for: { 6137 // Find the type id for the given typeinfo. 6138 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6139 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6140 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6141 setValue(&I, Res); 6142 return; 6143 } 6144 6145 case Intrinsic::eh_return_i32: 6146 case Intrinsic::eh_return_i64: 6147 DAG.getMachineFunction().setCallsEHReturn(true); 6148 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6149 MVT::Other, 6150 getControlRoot(), 6151 getValue(I.getArgOperand(0)), 6152 getValue(I.getArgOperand(1)))); 6153 return; 6154 case Intrinsic::eh_unwind_init: 6155 DAG.getMachineFunction().setCallsUnwindInit(true); 6156 return; 6157 case Intrinsic::eh_dwarf_cfa: 6158 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6159 TLI.getPointerTy(DAG.getDataLayout()), 6160 getValue(I.getArgOperand(0)))); 6161 return; 6162 case Intrinsic::eh_sjlj_callsite: { 6163 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6164 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6165 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6166 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6167 6168 MMI.setCurrentCallSite(CI->getZExtValue()); 6169 return; 6170 } 6171 case Intrinsic::eh_sjlj_functioncontext: { 6172 // Get and store the index of the function context. 6173 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6174 AllocaInst *FnCtx = 6175 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6176 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6177 MFI.setFunctionContextIndex(FI); 6178 return; 6179 } 6180 case Intrinsic::eh_sjlj_setjmp: { 6181 SDValue Ops[2]; 6182 Ops[0] = getRoot(); 6183 Ops[1] = getValue(I.getArgOperand(0)); 6184 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6185 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6186 setValue(&I, Op.getValue(0)); 6187 DAG.setRoot(Op.getValue(1)); 6188 return; 6189 } 6190 case Intrinsic::eh_sjlj_longjmp: 6191 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6192 getRoot(), getValue(I.getArgOperand(0)))); 6193 return; 6194 case Intrinsic::eh_sjlj_setup_dispatch: 6195 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6196 getRoot())); 6197 return; 6198 case Intrinsic::masked_gather: 6199 visitMaskedGather(I); 6200 return; 6201 case Intrinsic::masked_load: 6202 visitMaskedLoad(I); 6203 return; 6204 case Intrinsic::masked_scatter: 6205 visitMaskedScatter(I); 6206 return; 6207 case Intrinsic::masked_store: 6208 visitMaskedStore(I); 6209 return; 6210 case Intrinsic::masked_expandload: 6211 visitMaskedLoad(I, true /* IsExpanding */); 6212 return; 6213 case Intrinsic::masked_compressstore: 6214 visitMaskedStore(I, true /* IsCompressing */); 6215 return; 6216 case Intrinsic::powi: 6217 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6218 getValue(I.getArgOperand(1)), DAG)); 6219 return; 6220 case Intrinsic::log: 6221 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6222 return; 6223 case Intrinsic::log2: 6224 setValue(&I, 6225 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6226 return; 6227 case Intrinsic::log10: 6228 setValue(&I, 6229 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6230 return; 6231 case Intrinsic::exp: 6232 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6233 return; 6234 case Intrinsic::exp2: 6235 setValue(&I, 6236 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6237 return; 6238 case Intrinsic::pow: 6239 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6240 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6241 return; 6242 case Intrinsic::sqrt: 6243 case Intrinsic::fabs: 6244 case Intrinsic::sin: 6245 case Intrinsic::cos: 6246 case Intrinsic::floor: 6247 case Intrinsic::ceil: 6248 case Intrinsic::trunc: 6249 case Intrinsic::rint: 6250 case Intrinsic::nearbyint: 6251 case Intrinsic::round: 6252 case Intrinsic::roundeven: 6253 case Intrinsic::canonicalize: { 6254 unsigned Opcode; 6255 switch (Intrinsic) { 6256 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6257 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6258 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6259 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6260 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6261 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6262 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6263 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6264 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6265 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6266 case Intrinsic::round: Opcode = ISD::FROUND; break; 6267 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6268 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6269 } 6270 6271 setValue(&I, DAG.getNode(Opcode, sdl, 6272 getValue(I.getArgOperand(0)).getValueType(), 6273 getValue(I.getArgOperand(0)), Flags)); 6274 return; 6275 } 6276 case Intrinsic::lround: 6277 case Intrinsic::llround: 6278 case Intrinsic::lrint: 6279 case Intrinsic::llrint: { 6280 unsigned Opcode; 6281 switch (Intrinsic) { 6282 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6283 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6284 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6285 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6286 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6287 } 6288 6289 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6290 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6291 getValue(I.getArgOperand(0)))); 6292 return; 6293 } 6294 case Intrinsic::minnum: 6295 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6296 getValue(I.getArgOperand(0)).getValueType(), 6297 getValue(I.getArgOperand(0)), 6298 getValue(I.getArgOperand(1)), Flags)); 6299 return; 6300 case Intrinsic::maxnum: 6301 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6302 getValue(I.getArgOperand(0)).getValueType(), 6303 getValue(I.getArgOperand(0)), 6304 getValue(I.getArgOperand(1)), Flags)); 6305 return; 6306 case Intrinsic::minimum: 6307 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6308 getValue(I.getArgOperand(0)).getValueType(), 6309 getValue(I.getArgOperand(0)), 6310 getValue(I.getArgOperand(1)), Flags)); 6311 return; 6312 case Intrinsic::maximum: 6313 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6314 getValue(I.getArgOperand(0)).getValueType(), 6315 getValue(I.getArgOperand(0)), 6316 getValue(I.getArgOperand(1)), Flags)); 6317 return; 6318 case Intrinsic::copysign: 6319 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6320 getValue(I.getArgOperand(0)).getValueType(), 6321 getValue(I.getArgOperand(0)), 6322 getValue(I.getArgOperand(1)), Flags)); 6323 return; 6324 case Intrinsic::arithmetic_fence: { 6325 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6326 getValue(I.getArgOperand(0)).getValueType(), 6327 getValue(I.getArgOperand(0)), Flags)); 6328 return; 6329 } 6330 case Intrinsic::fma: 6331 setValue(&I, DAG.getNode( 6332 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6333 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6334 getValue(I.getArgOperand(2)), Flags)); 6335 return; 6336 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6337 case Intrinsic::INTRINSIC: 6338 #include "llvm/IR/ConstrainedOps.def" 6339 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6340 return; 6341 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6342 #include "llvm/IR/VPIntrinsics.def" 6343 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6344 return; 6345 case Intrinsic::fmuladd: { 6346 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6347 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6348 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6349 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6350 getValue(I.getArgOperand(0)).getValueType(), 6351 getValue(I.getArgOperand(0)), 6352 getValue(I.getArgOperand(1)), 6353 getValue(I.getArgOperand(2)), Flags)); 6354 } else { 6355 // TODO: Intrinsic calls should have fast-math-flags. 6356 SDValue Mul = DAG.getNode( 6357 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6358 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6359 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6360 getValue(I.getArgOperand(0)).getValueType(), 6361 Mul, getValue(I.getArgOperand(2)), Flags); 6362 setValue(&I, Add); 6363 } 6364 return; 6365 } 6366 case Intrinsic::convert_to_fp16: 6367 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6368 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6369 getValue(I.getArgOperand(0)), 6370 DAG.getTargetConstant(0, sdl, 6371 MVT::i32)))); 6372 return; 6373 case Intrinsic::convert_from_fp16: 6374 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6375 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6376 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6377 getValue(I.getArgOperand(0))))); 6378 return; 6379 case Intrinsic::fptosi_sat: { 6380 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6381 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6382 getValue(I.getArgOperand(0)), 6383 DAG.getValueType(VT.getScalarType()))); 6384 return; 6385 } 6386 case Intrinsic::fptoui_sat: { 6387 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6388 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6389 getValue(I.getArgOperand(0)), 6390 DAG.getValueType(VT.getScalarType()))); 6391 return; 6392 } 6393 case Intrinsic::set_rounding: 6394 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6395 {getRoot(), getValue(I.getArgOperand(0))}); 6396 setValue(&I, Res); 6397 DAG.setRoot(Res.getValue(0)); 6398 return; 6399 case Intrinsic::pcmarker: { 6400 SDValue Tmp = getValue(I.getArgOperand(0)); 6401 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6402 return; 6403 } 6404 case Intrinsic::readcyclecounter: { 6405 SDValue Op = getRoot(); 6406 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6407 DAG.getVTList(MVT::i64, MVT::Other), Op); 6408 setValue(&I, Res); 6409 DAG.setRoot(Res.getValue(1)); 6410 return; 6411 } 6412 case Intrinsic::bitreverse: 6413 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6414 getValue(I.getArgOperand(0)).getValueType(), 6415 getValue(I.getArgOperand(0)))); 6416 return; 6417 case Intrinsic::bswap: 6418 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6419 getValue(I.getArgOperand(0)).getValueType(), 6420 getValue(I.getArgOperand(0)))); 6421 return; 6422 case Intrinsic::cttz: { 6423 SDValue Arg = getValue(I.getArgOperand(0)); 6424 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6425 EVT Ty = Arg.getValueType(); 6426 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6427 sdl, Ty, Arg)); 6428 return; 6429 } 6430 case Intrinsic::ctlz: { 6431 SDValue Arg = getValue(I.getArgOperand(0)); 6432 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6433 EVT Ty = Arg.getValueType(); 6434 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6435 sdl, Ty, Arg)); 6436 return; 6437 } 6438 case Intrinsic::ctpop: { 6439 SDValue Arg = getValue(I.getArgOperand(0)); 6440 EVT Ty = Arg.getValueType(); 6441 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6442 return; 6443 } 6444 case Intrinsic::fshl: 6445 case Intrinsic::fshr: { 6446 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6447 SDValue X = getValue(I.getArgOperand(0)); 6448 SDValue Y = getValue(I.getArgOperand(1)); 6449 SDValue Z = getValue(I.getArgOperand(2)); 6450 EVT VT = X.getValueType(); 6451 6452 if (X == Y) { 6453 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6454 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6455 } else { 6456 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6457 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6458 } 6459 return; 6460 } 6461 case Intrinsic::sadd_sat: { 6462 SDValue Op1 = getValue(I.getArgOperand(0)); 6463 SDValue Op2 = getValue(I.getArgOperand(1)); 6464 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6465 return; 6466 } 6467 case Intrinsic::uadd_sat: { 6468 SDValue Op1 = getValue(I.getArgOperand(0)); 6469 SDValue Op2 = getValue(I.getArgOperand(1)); 6470 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6471 return; 6472 } 6473 case Intrinsic::ssub_sat: { 6474 SDValue Op1 = getValue(I.getArgOperand(0)); 6475 SDValue Op2 = getValue(I.getArgOperand(1)); 6476 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6477 return; 6478 } 6479 case Intrinsic::usub_sat: { 6480 SDValue Op1 = getValue(I.getArgOperand(0)); 6481 SDValue Op2 = getValue(I.getArgOperand(1)); 6482 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6483 return; 6484 } 6485 case Intrinsic::sshl_sat: { 6486 SDValue Op1 = getValue(I.getArgOperand(0)); 6487 SDValue Op2 = getValue(I.getArgOperand(1)); 6488 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6489 return; 6490 } 6491 case Intrinsic::ushl_sat: { 6492 SDValue Op1 = getValue(I.getArgOperand(0)); 6493 SDValue Op2 = getValue(I.getArgOperand(1)); 6494 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6495 return; 6496 } 6497 case Intrinsic::smul_fix: 6498 case Intrinsic::umul_fix: 6499 case Intrinsic::smul_fix_sat: 6500 case Intrinsic::umul_fix_sat: { 6501 SDValue Op1 = getValue(I.getArgOperand(0)); 6502 SDValue Op2 = getValue(I.getArgOperand(1)); 6503 SDValue Op3 = getValue(I.getArgOperand(2)); 6504 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6505 Op1.getValueType(), Op1, Op2, Op3)); 6506 return; 6507 } 6508 case Intrinsic::sdiv_fix: 6509 case Intrinsic::udiv_fix: 6510 case Intrinsic::sdiv_fix_sat: 6511 case Intrinsic::udiv_fix_sat: { 6512 SDValue Op1 = getValue(I.getArgOperand(0)); 6513 SDValue Op2 = getValue(I.getArgOperand(1)); 6514 SDValue Op3 = getValue(I.getArgOperand(2)); 6515 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6516 Op1, Op2, Op3, DAG, TLI)); 6517 return; 6518 } 6519 case Intrinsic::smax: { 6520 SDValue Op1 = getValue(I.getArgOperand(0)); 6521 SDValue Op2 = getValue(I.getArgOperand(1)); 6522 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6523 return; 6524 } 6525 case Intrinsic::smin: { 6526 SDValue Op1 = getValue(I.getArgOperand(0)); 6527 SDValue Op2 = getValue(I.getArgOperand(1)); 6528 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6529 return; 6530 } 6531 case Intrinsic::umax: { 6532 SDValue Op1 = getValue(I.getArgOperand(0)); 6533 SDValue Op2 = getValue(I.getArgOperand(1)); 6534 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6535 return; 6536 } 6537 case Intrinsic::umin: { 6538 SDValue Op1 = getValue(I.getArgOperand(0)); 6539 SDValue Op2 = getValue(I.getArgOperand(1)); 6540 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6541 return; 6542 } 6543 case Intrinsic::abs: { 6544 // TODO: Preserve "int min is poison" arg in SDAG? 6545 SDValue Op1 = getValue(I.getArgOperand(0)); 6546 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6547 return; 6548 } 6549 case Intrinsic::stacksave: { 6550 SDValue Op = getRoot(); 6551 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6552 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6553 setValue(&I, Res); 6554 DAG.setRoot(Res.getValue(1)); 6555 return; 6556 } 6557 case Intrinsic::stackrestore: 6558 Res = getValue(I.getArgOperand(0)); 6559 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6560 return; 6561 case Intrinsic::get_dynamic_area_offset: { 6562 SDValue Op = getRoot(); 6563 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6564 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6565 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6566 // target. 6567 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6568 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6569 " intrinsic!"); 6570 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6571 Op); 6572 DAG.setRoot(Op); 6573 setValue(&I, Res); 6574 return; 6575 } 6576 case Intrinsic::stackguard: { 6577 MachineFunction &MF = DAG.getMachineFunction(); 6578 const Module &M = *MF.getFunction().getParent(); 6579 SDValue Chain = getRoot(); 6580 if (TLI.useLoadStackGuardNode()) { 6581 Res = getLoadStackGuard(DAG, sdl, Chain); 6582 } else { 6583 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6584 const Value *Global = TLI.getSDagStackGuard(M); 6585 Align Align = DL->getPrefTypeAlign(Global->getType()); 6586 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6587 MachinePointerInfo(Global, 0), Align, 6588 MachineMemOperand::MOVolatile); 6589 } 6590 if (TLI.useStackGuardXorFP()) 6591 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6592 DAG.setRoot(Chain); 6593 setValue(&I, Res); 6594 return; 6595 } 6596 case Intrinsic::stackprotector: { 6597 // Emit code into the DAG to store the stack guard onto the stack. 6598 MachineFunction &MF = DAG.getMachineFunction(); 6599 MachineFrameInfo &MFI = MF.getFrameInfo(); 6600 SDValue Src, Chain = getRoot(); 6601 6602 if (TLI.useLoadStackGuardNode()) 6603 Src = getLoadStackGuard(DAG, sdl, Chain); 6604 else 6605 Src = getValue(I.getArgOperand(0)); // The guard's value. 6606 6607 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6608 6609 int FI = FuncInfo.StaticAllocaMap[Slot]; 6610 MFI.setStackProtectorIndex(FI); 6611 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6612 6613 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6614 6615 // Store the stack protector onto the stack. 6616 Res = DAG.getStore( 6617 Chain, sdl, Src, FIN, 6618 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6619 MaybeAlign(), MachineMemOperand::MOVolatile); 6620 setValue(&I, Res); 6621 DAG.setRoot(Res); 6622 return; 6623 } 6624 case Intrinsic::objectsize: 6625 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6626 6627 case Intrinsic::is_constant: 6628 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6629 6630 case Intrinsic::annotation: 6631 case Intrinsic::ptr_annotation: 6632 case Intrinsic::launder_invariant_group: 6633 case Intrinsic::strip_invariant_group: 6634 // Drop the intrinsic, but forward the value 6635 setValue(&I, getValue(I.getOperand(0))); 6636 return; 6637 6638 case Intrinsic::assume: 6639 case Intrinsic::experimental_noalias_scope_decl: 6640 case Intrinsic::var_annotation: 6641 case Intrinsic::sideeffect: 6642 // Discard annotate attributes, noalias scope declarations, assumptions, and 6643 // artificial side-effects. 6644 return; 6645 6646 case Intrinsic::codeview_annotation: { 6647 // Emit a label associated with this metadata. 6648 MachineFunction &MF = DAG.getMachineFunction(); 6649 MCSymbol *Label = 6650 MF.getMMI().getContext().createTempSymbol("annotation", true); 6651 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6652 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6653 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6654 DAG.setRoot(Res); 6655 return; 6656 } 6657 6658 case Intrinsic::init_trampoline: { 6659 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6660 6661 SDValue Ops[6]; 6662 Ops[0] = getRoot(); 6663 Ops[1] = getValue(I.getArgOperand(0)); 6664 Ops[2] = getValue(I.getArgOperand(1)); 6665 Ops[3] = getValue(I.getArgOperand(2)); 6666 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6667 Ops[5] = DAG.getSrcValue(F); 6668 6669 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6670 6671 DAG.setRoot(Res); 6672 return; 6673 } 6674 case Intrinsic::adjust_trampoline: 6675 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6676 TLI.getPointerTy(DAG.getDataLayout()), 6677 getValue(I.getArgOperand(0)))); 6678 return; 6679 case Intrinsic::gcroot: { 6680 assert(DAG.getMachineFunction().getFunction().hasGC() && 6681 "only valid in functions with gc specified, enforced by Verifier"); 6682 assert(GFI && "implied by previous"); 6683 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6684 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6685 6686 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6687 GFI->addStackRoot(FI->getIndex(), TypeMap); 6688 return; 6689 } 6690 case Intrinsic::gcread: 6691 case Intrinsic::gcwrite: 6692 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6693 case Intrinsic::flt_rounds: 6694 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6695 setValue(&I, Res); 6696 DAG.setRoot(Res.getValue(1)); 6697 return; 6698 6699 case Intrinsic::expect: 6700 // Just replace __builtin_expect(exp, c) with EXP. 6701 setValue(&I, getValue(I.getArgOperand(0))); 6702 return; 6703 6704 case Intrinsic::ubsantrap: 6705 case Intrinsic::debugtrap: 6706 case Intrinsic::trap: { 6707 StringRef TrapFuncName = 6708 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6709 if (TrapFuncName.empty()) { 6710 switch (Intrinsic) { 6711 case Intrinsic::trap: 6712 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6713 break; 6714 case Intrinsic::debugtrap: 6715 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6716 break; 6717 case Intrinsic::ubsantrap: 6718 DAG.setRoot(DAG.getNode( 6719 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6720 DAG.getTargetConstant( 6721 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6722 MVT::i32))); 6723 break; 6724 default: llvm_unreachable("unknown trap intrinsic"); 6725 } 6726 return; 6727 } 6728 TargetLowering::ArgListTy Args; 6729 if (Intrinsic == Intrinsic::ubsantrap) { 6730 Args.push_back(TargetLoweringBase::ArgListEntry()); 6731 Args[0].Val = I.getArgOperand(0); 6732 Args[0].Node = getValue(Args[0].Val); 6733 Args[0].Ty = Args[0].Val->getType(); 6734 } 6735 6736 TargetLowering::CallLoweringInfo CLI(DAG); 6737 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6738 CallingConv::C, I.getType(), 6739 DAG.getExternalSymbol(TrapFuncName.data(), 6740 TLI.getPointerTy(DAG.getDataLayout())), 6741 std::move(Args)); 6742 6743 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6744 DAG.setRoot(Result.second); 6745 return; 6746 } 6747 6748 case Intrinsic::uadd_with_overflow: 6749 case Intrinsic::sadd_with_overflow: 6750 case Intrinsic::usub_with_overflow: 6751 case Intrinsic::ssub_with_overflow: 6752 case Intrinsic::umul_with_overflow: 6753 case Intrinsic::smul_with_overflow: { 6754 ISD::NodeType Op; 6755 switch (Intrinsic) { 6756 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6757 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6758 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6759 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6760 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6761 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6762 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6763 } 6764 SDValue Op1 = getValue(I.getArgOperand(0)); 6765 SDValue Op2 = getValue(I.getArgOperand(1)); 6766 6767 EVT ResultVT = Op1.getValueType(); 6768 EVT OverflowVT = MVT::i1; 6769 if (ResultVT.isVector()) 6770 OverflowVT = EVT::getVectorVT( 6771 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6772 6773 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6774 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6775 return; 6776 } 6777 case Intrinsic::prefetch: { 6778 SDValue Ops[5]; 6779 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6780 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6781 Ops[0] = DAG.getRoot(); 6782 Ops[1] = getValue(I.getArgOperand(0)); 6783 Ops[2] = getValue(I.getArgOperand(1)); 6784 Ops[3] = getValue(I.getArgOperand(2)); 6785 Ops[4] = getValue(I.getArgOperand(3)); 6786 SDValue Result = DAG.getMemIntrinsicNode( 6787 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6788 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6789 /* align */ None, Flags); 6790 6791 // Chain the prefetch in parallell with any pending loads, to stay out of 6792 // the way of later optimizations. 6793 PendingLoads.push_back(Result); 6794 Result = getRoot(); 6795 DAG.setRoot(Result); 6796 return; 6797 } 6798 case Intrinsic::lifetime_start: 6799 case Intrinsic::lifetime_end: { 6800 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6801 // Stack coloring is not enabled in O0, discard region information. 6802 if (TM.getOptLevel() == CodeGenOpt::None) 6803 return; 6804 6805 const int64_t ObjectSize = 6806 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6807 Value *const ObjectPtr = I.getArgOperand(1); 6808 SmallVector<const Value *, 4> Allocas; 6809 getUnderlyingObjects(ObjectPtr, Allocas); 6810 6811 for (const Value *Alloca : Allocas) { 6812 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6813 6814 // Could not find an Alloca. 6815 if (!LifetimeObject) 6816 continue; 6817 6818 // First check that the Alloca is static, otherwise it won't have a 6819 // valid frame index. 6820 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6821 if (SI == FuncInfo.StaticAllocaMap.end()) 6822 return; 6823 6824 const int FrameIndex = SI->second; 6825 int64_t Offset; 6826 if (GetPointerBaseWithConstantOffset( 6827 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6828 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6829 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6830 Offset); 6831 DAG.setRoot(Res); 6832 } 6833 return; 6834 } 6835 case Intrinsic::pseudoprobe: { 6836 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6837 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6838 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6839 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6840 DAG.setRoot(Res); 6841 return; 6842 } 6843 case Intrinsic::invariant_start: 6844 // Discard region information. 6845 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6846 return; 6847 case Intrinsic::invariant_end: 6848 // Discard region information. 6849 return; 6850 case Intrinsic::clear_cache: 6851 /// FunctionName may be null. 6852 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6853 lowerCallToExternalSymbol(I, FunctionName); 6854 return; 6855 case Intrinsic::donothing: 6856 case Intrinsic::seh_try_begin: 6857 case Intrinsic::seh_scope_begin: 6858 case Intrinsic::seh_try_end: 6859 case Intrinsic::seh_scope_end: 6860 // ignore 6861 return; 6862 case Intrinsic::experimental_stackmap: 6863 visitStackmap(I); 6864 return; 6865 case Intrinsic::experimental_patchpoint_void: 6866 case Intrinsic::experimental_patchpoint_i64: 6867 visitPatchpoint(I); 6868 return; 6869 case Intrinsic::experimental_gc_statepoint: 6870 LowerStatepoint(cast<GCStatepointInst>(I)); 6871 return; 6872 case Intrinsic::experimental_gc_result: 6873 visitGCResult(cast<GCResultInst>(I)); 6874 return; 6875 case Intrinsic::experimental_gc_relocate: 6876 visitGCRelocate(cast<GCRelocateInst>(I)); 6877 return; 6878 case Intrinsic::instrprof_increment: 6879 llvm_unreachable("instrprof failed to lower an increment"); 6880 case Intrinsic::instrprof_value_profile: 6881 llvm_unreachable("instrprof failed to lower a value profiling call"); 6882 case Intrinsic::localescape: { 6883 MachineFunction &MF = DAG.getMachineFunction(); 6884 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6885 6886 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6887 // is the same on all targets. 6888 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 6889 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6890 if (isa<ConstantPointerNull>(Arg)) 6891 continue; // Skip null pointers. They represent a hole in index space. 6892 AllocaInst *Slot = cast<AllocaInst>(Arg); 6893 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6894 "can only escape static allocas"); 6895 int FI = FuncInfo.StaticAllocaMap[Slot]; 6896 MCSymbol *FrameAllocSym = 6897 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6898 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6899 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6900 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6901 .addSym(FrameAllocSym) 6902 .addFrameIndex(FI); 6903 } 6904 6905 return; 6906 } 6907 6908 case Intrinsic::localrecover: { 6909 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6910 MachineFunction &MF = DAG.getMachineFunction(); 6911 6912 // Get the symbol that defines the frame offset. 6913 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6914 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6915 unsigned IdxVal = 6916 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6917 MCSymbol *FrameAllocSym = 6918 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6919 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6920 6921 Value *FP = I.getArgOperand(1); 6922 SDValue FPVal = getValue(FP); 6923 EVT PtrVT = FPVal.getValueType(); 6924 6925 // Create a MCSymbol for the label to avoid any target lowering 6926 // that would make this PC relative. 6927 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6928 SDValue OffsetVal = 6929 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6930 6931 // Add the offset to the FP. 6932 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6933 setValue(&I, Add); 6934 6935 return; 6936 } 6937 6938 case Intrinsic::eh_exceptionpointer: 6939 case Intrinsic::eh_exceptioncode: { 6940 // Get the exception pointer vreg, copy from it, and resize it to fit. 6941 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6942 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6943 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6944 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6945 SDValue N = 6946 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6947 if (Intrinsic == Intrinsic::eh_exceptioncode) 6948 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6949 setValue(&I, N); 6950 return; 6951 } 6952 case Intrinsic::xray_customevent: { 6953 // Here we want to make sure that the intrinsic behaves as if it has a 6954 // specific calling convention, and only for x86_64. 6955 // FIXME: Support other platforms later. 6956 const auto &Triple = DAG.getTarget().getTargetTriple(); 6957 if (Triple.getArch() != Triple::x86_64) 6958 return; 6959 6960 SDLoc DL = getCurSDLoc(); 6961 SmallVector<SDValue, 8> Ops; 6962 6963 // We want to say that we always want the arguments in registers. 6964 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6965 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6966 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6967 SDValue Chain = getRoot(); 6968 Ops.push_back(LogEntryVal); 6969 Ops.push_back(StrSizeVal); 6970 Ops.push_back(Chain); 6971 6972 // We need to enforce the calling convention for the callsite, so that 6973 // argument ordering is enforced correctly, and that register allocation can 6974 // see that some registers may be assumed clobbered and have to preserve 6975 // them across calls to the intrinsic. 6976 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6977 DL, NodeTys, Ops); 6978 SDValue patchableNode = SDValue(MN, 0); 6979 DAG.setRoot(patchableNode); 6980 setValue(&I, patchableNode); 6981 return; 6982 } 6983 case Intrinsic::xray_typedevent: { 6984 // Here we want to make sure that the intrinsic behaves as if it has a 6985 // specific calling convention, and only for x86_64. 6986 // FIXME: Support other platforms later. 6987 const auto &Triple = DAG.getTarget().getTargetTriple(); 6988 if (Triple.getArch() != Triple::x86_64) 6989 return; 6990 6991 SDLoc DL = getCurSDLoc(); 6992 SmallVector<SDValue, 8> Ops; 6993 6994 // We want to say that we always want the arguments in registers. 6995 // It's unclear to me how manipulating the selection DAG here forces callers 6996 // to provide arguments in registers instead of on the stack. 6997 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6998 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6999 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7000 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7001 SDValue Chain = getRoot(); 7002 Ops.push_back(LogTypeId); 7003 Ops.push_back(LogEntryVal); 7004 Ops.push_back(StrSizeVal); 7005 Ops.push_back(Chain); 7006 7007 // We need to enforce the calling convention for the callsite, so that 7008 // argument ordering is enforced correctly, and that register allocation can 7009 // see that some registers may be assumed clobbered and have to preserve 7010 // them across calls to the intrinsic. 7011 MachineSDNode *MN = DAG.getMachineNode( 7012 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 7013 SDValue patchableNode = SDValue(MN, 0); 7014 DAG.setRoot(patchableNode); 7015 setValue(&I, patchableNode); 7016 return; 7017 } 7018 case Intrinsic::experimental_deoptimize: 7019 LowerDeoptimizeCall(&I); 7020 return; 7021 case Intrinsic::experimental_stepvector: 7022 visitStepVector(I); 7023 return; 7024 case Intrinsic::vector_reduce_fadd: 7025 case Intrinsic::vector_reduce_fmul: 7026 case Intrinsic::vector_reduce_add: 7027 case Intrinsic::vector_reduce_mul: 7028 case Intrinsic::vector_reduce_and: 7029 case Intrinsic::vector_reduce_or: 7030 case Intrinsic::vector_reduce_xor: 7031 case Intrinsic::vector_reduce_smax: 7032 case Intrinsic::vector_reduce_smin: 7033 case Intrinsic::vector_reduce_umax: 7034 case Intrinsic::vector_reduce_umin: 7035 case Intrinsic::vector_reduce_fmax: 7036 case Intrinsic::vector_reduce_fmin: 7037 visitVectorReduce(I, Intrinsic); 7038 return; 7039 7040 case Intrinsic::icall_branch_funnel: { 7041 SmallVector<SDValue, 16> Ops; 7042 Ops.push_back(getValue(I.getArgOperand(0))); 7043 7044 int64_t Offset; 7045 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7046 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7047 if (!Base) 7048 report_fatal_error( 7049 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7050 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 7051 7052 struct BranchFunnelTarget { 7053 int64_t Offset; 7054 SDValue Target; 7055 }; 7056 SmallVector<BranchFunnelTarget, 8> Targets; 7057 7058 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7059 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7060 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7061 if (ElemBase != Base) 7062 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7063 "to the same GlobalValue"); 7064 7065 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7066 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7067 if (!GA) 7068 report_fatal_error( 7069 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7070 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7071 GA->getGlobal(), getCurSDLoc(), 7072 Val.getValueType(), GA->getOffset())}); 7073 } 7074 llvm::sort(Targets, 7075 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7076 return T1.Offset < T2.Offset; 7077 }); 7078 7079 for (auto &T : Targets) { 7080 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 7081 Ops.push_back(T.Target); 7082 } 7083 7084 Ops.push_back(DAG.getRoot()); // Chain 7085 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7086 getCurSDLoc(), MVT::Other, Ops), 7087 0); 7088 DAG.setRoot(N); 7089 setValue(&I, N); 7090 HasTailCall = true; 7091 return; 7092 } 7093 7094 case Intrinsic::wasm_landingpad_index: 7095 // Information this intrinsic contained has been transferred to 7096 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7097 // delete it now. 7098 return; 7099 7100 case Intrinsic::aarch64_settag: 7101 case Intrinsic::aarch64_settag_zero: { 7102 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7103 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7104 SDValue Val = TSI.EmitTargetCodeForSetTag( 7105 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7106 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7107 ZeroMemory); 7108 DAG.setRoot(Val); 7109 setValue(&I, Val); 7110 return; 7111 } 7112 case Intrinsic::ptrmask: { 7113 SDValue Ptr = getValue(I.getOperand(0)); 7114 SDValue Const = getValue(I.getOperand(1)); 7115 7116 EVT PtrVT = Ptr.getValueType(); 7117 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7118 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7119 return; 7120 } 7121 case Intrinsic::get_active_lane_mask: { 7122 auto DL = getCurSDLoc(); 7123 SDValue Index = getValue(I.getOperand(0)); 7124 SDValue TripCount = getValue(I.getOperand(1)); 7125 Type *ElementTy = I.getOperand(0)->getType(); 7126 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7127 unsigned VecWidth = VT.getVectorNumElements(); 7128 7129 SmallVector<SDValue, 16> OpsTripCount; 7130 SmallVector<SDValue, 16> OpsIndex; 7131 SmallVector<SDValue, 16> OpsStepConstants; 7132 for (unsigned i = 0; i < VecWidth; i++) { 7133 OpsTripCount.push_back(TripCount); 7134 OpsIndex.push_back(Index); 7135 OpsStepConstants.push_back( 7136 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7137 } 7138 7139 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7140 7141 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7142 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7143 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7144 SDValue VectorInduction = DAG.getNode( 7145 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7146 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7147 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7148 VectorTripCount, ISD::CondCode::SETULT); 7149 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7150 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7151 SetCC)); 7152 return; 7153 } 7154 case Intrinsic::experimental_vector_insert: { 7155 auto DL = getCurSDLoc(); 7156 7157 SDValue Vec = getValue(I.getOperand(0)); 7158 SDValue SubVec = getValue(I.getOperand(1)); 7159 SDValue Index = getValue(I.getOperand(2)); 7160 7161 // The intrinsic's index type is i64, but the SDNode requires an index type 7162 // suitable for the target. Convert the index as required. 7163 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7164 if (Index.getValueType() != VectorIdxTy) 7165 Index = DAG.getVectorIdxConstant( 7166 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7167 7168 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7169 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7170 Index)); 7171 return; 7172 } 7173 case Intrinsic::experimental_vector_extract: { 7174 auto DL = getCurSDLoc(); 7175 7176 SDValue Vec = getValue(I.getOperand(0)); 7177 SDValue Index = getValue(I.getOperand(1)); 7178 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7179 7180 // The intrinsic's index type is i64, but the SDNode requires an index type 7181 // suitable for the target. Convert the index as required. 7182 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7183 if (Index.getValueType() != VectorIdxTy) 7184 Index = DAG.getVectorIdxConstant( 7185 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7186 7187 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7188 return; 7189 } 7190 case Intrinsic::experimental_vector_reverse: 7191 visitVectorReverse(I); 7192 return; 7193 case Intrinsic::experimental_vector_splice: 7194 visitVectorSplice(I); 7195 return; 7196 } 7197 } 7198 7199 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7200 const ConstrainedFPIntrinsic &FPI) { 7201 SDLoc sdl = getCurSDLoc(); 7202 7203 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7204 SmallVector<EVT, 4> ValueVTs; 7205 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7206 ValueVTs.push_back(MVT::Other); // Out chain 7207 7208 // We do not need to serialize constrained FP intrinsics against 7209 // each other or against (nonvolatile) loads, so they can be 7210 // chained like loads. 7211 SDValue Chain = DAG.getRoot(); 7212 SmallVector<SDValue, 4> Opers; 7213 Opers.push_back(Chain); 7214 if (FPI.isUnaryOp()) { 7215 Opers.push_back(getValue(FPI.getArgOperand(0))); 7216 } else if (FPI.isTernaryOp()) { 7217 Opers.push_back(getValue(FPI.getArgOperand(0))); 7218 Opers.push_back(getValue(FPI.getArgOperand(1))); 7219 Opers.push_back(getValue(FPI.getArgOperand(2))); 7220 } else { 7221 Opers.push_back(getValue(FPI.getArgOperand(0))); 7222 Opers.push_back(getValue(FPI.getArgOperand(1))); 7223 } 7224 7225 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7226 assert(Result.getNode()->getNumValues() == 2); 7227 7228 // Push node to the appropriate list so that future instructions can be 7229 // chained up correctly. 7230 SDValue OutChain = Result.getValue(1); 7231 switch (EB) { 7232 case fp::ExceptionBehavior::ebIgnore: 7233 // The only reason why ebIgnore nodes still need to be chained is that 7234 // they might depend on the current rounding mode, and therefore must 7235 // not be moved across instruction that may change that mode. 7236 LLVM_FALLTHROUGH; 7237 case fp::ExceptionBehavior::ebMayTrap: 7238 // These must not be moved across calls or instructions that may change 7239 // floating-point exception masks. 7240 PendingConstrainedFP.push_back(OutChain); 7241 break; 7242 case fp::ExceptionBehavior::ebStrict: 7243 // These must not be moved across calls or instructions that may change 7244 // floating-point exception masks or read floating-point exception flags. 7245 // In addition, they cannot be optimized out even if unused. 7246 PendingConstrainedFPStrict.push_back(OutChain); 7247 break; 7248 } 7249 }; 7250 7251 SDVTList VTs = DAG.getVTList(ValueVTs); 7252 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7253 7254 SDNodeFlags Flags; 7255 if (EB == fp::ExceptionBehavior::ebIgnore) 7256 Flags.setNoFPExcept(true); 7257 7258 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7259 Flags.copyFMF(*FPOp); 7260 7261 unsigned Opcode; 7262 switch (FPI.getIntrinsicID()) { 7263 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7264 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7265 case Intrinsic::INTRINSIC: \ 7266 Opcode = ISD::STRICT_##DAGN; \ 7267 break; 7268 #include "llvm/IR/ConstrainedOps.def" 7269 case Intrinsic::experimental_constrained_fmuladd: { 7270 Opcode = ISD::STRICT_FMA; 7271 // Break fmuladd into fmul and fadd. 7272 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7273 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7274 ValueVTs[0])) { 7275 Opers.pop_back(); 7276 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7277 pushOutChain(Mul, EB); 7278 Opcode = ISD::STRICT_FADD; 7279 Opers.clear(); 7280 Opers.push_back(Mul.getValue(1)); 7281 Opers.push_back(Mul.getValue(0)); 7282 Opers.push_back(getValue(FPI.getArgOperand(2))); 7283 } 7284 break; 7285 } 7286 } 7287 7288 // A few strict DAG nodes carry additional operands that are not 7289 // set up by the default code above. 7290 switch (Opcode) { 7291 default: break; 7292 case ISD::STRICT_FP_ROUND: 7293 Opers.push_back( 7294 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7295 break; 7296 case ISD::STRICT_FSETCC: 7297 case ISD::STRICT_FSETCCS: { 7298 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7299 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7300 if (TM.Options.NoNaNsFPMath) 7301 Condition = getFCmpCodeWithoutNaN(Condition); 7302 Opers.push_back(DAG.getCondCode(Condition)); 7303 break; 7304 } 7305 } 7306 7307 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7308 pushOutChain(Result, EB); 7309 7310 SDValue FPResult = Result.getValue(0); 7311 setValue(&FPI, FPResult); 7312 } 7313 7314 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7315 Optional<unsigned> ResOPC; 7316 switch (VPIntrin.getIntrinsicID()) { 7317 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7318 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7319 #define END_REGISTER_VP_INTRINSIC(...) break; 7320 #include "llvm/IR/VPIntrinsics.def" 7321 } 7322 7323 if (!ResOPC.hasValue()) 7324 llvm_unreachable( 7325 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7326 7327 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7328 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7329 if (VPIntrin.getFastMathFlags().allowReassoc()) 7330 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7331 : ISD::VP_REDUCE_FMUL; 7332 } 7333 7334 return ResOPC.getValue(); 7335 } 7336 7337 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT, 7338 SmallVector<SDValue, 7> &OpValues, 7339 bool isGather) { 7340 SDLoc DL = getCurSDLoc(); 7341 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7342 Value *PtrOperand = VPIntrin.getArgOperand(0); 7343 MaybeAlign Alignment = DAG.getEVTAlign(VT); 7344 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7345 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7346 SDValue LD; 7347 bool AddToChain = true; 7348 if (!isGather) { 7349 // Do not serialize variable-length loads of constant memory with 7350 // anything. 7351 MemoryLocation ML; 7352 if (VT.isScalableVector()) 7353 ML = MemoryLocation::getAfter(PtrOperand); 7354 else 7355 ML = MemoryLocation( 7356 PtrOperand, 7357 LocationSize::precise( 7358 DAG.getDataLayout().getTypeStoreSize(VPIntrin.getType())), 7359 AAInfo); 7360 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7361 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7362 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7363 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7364 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 7365 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7366 MMO, false /*IsExpanding */); 7367 } else { 7368 unsigned AS = 7369 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7370 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7371 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7372 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7373 SDValue Base, Index, Scale; 7374 ISD::MemIndexType IndexType; 7375 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7376 this, VPIntrin.getParent()); 7377 if (!UniformBase) { 7378 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7379 Index = getValue(PtrOperand); 7380 IndexType = ISD::SIGNED_UNSCALED; 7381 Scale = 7382 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7383 } 7384 EVT IdxVT = Index.getValueType(); 7385 EVT EltTy = IdxVT.getVectorElementType(); 7386 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7387 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7388 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7389 } 7390 LD = DAG.getGatherVP( 7391 DAG.getVTList(VT, MVT::Other), VT, DL, 7392 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7393 IndexType); 7394 } 7395 if (AddToChain) 7396 PendingLoads.push_back(LD.getValue(1)); 7397 setValue(&VPIntrin, LD); 7398 } 7399 7400 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin, 7401 SmallVector<SDValue, 7> &OpValues, 7402 bool isScatter) { 7403 SDLoc DL = getCurSDLoc(); 7404 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7405 Value *PtrOperand = VPIntrin.getArgOperand(1); 7406 EVT VT = OpValues[0].getValueType(); 7407 MaybeAlign Alignment = DAG.getEVTAlign(VT); 7408 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7409 SDValue ST; 7410 if (!isScatter) { 7411 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7412 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7413 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 7414 ST = 7415 DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], OpValues[1], 7416 OpValues[2], OpValues[3], MMO, false /* IsTruncating */); 7417 } else { 7418 unsigned AS = 7419 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7420 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7421 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7422 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7423 SDValue Base, Index, Scale; 7424 ISD::MemIndexType IndexType; 7425 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7426 this, VPIntrin.getParent()); 7427 if (!UniformBase) { 7428 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7429 Index = getValue(PtrOperand); 7430 IndexType = ISD::SIGNED_UNSCALED; 7431 Scale = 7432 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7433 } 7434 EVT IdxVT = Index.getValueType(); 7435 EVT EltTy = IdxVT.getVectorElementType(); 7436 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7437 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7438 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7439 } 7440 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7441 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7442 OpValues[2], OpValues[3]}, 7443 MMO, IndexType); 7444 } 7445 DAG.setRoot(ST); 7446 setValue(&VPIntrin, ST); 7447 } 7448 7449 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7450 const VPIntrinsic &VPIntrin) { 7451 SDLoc DL = getCurSDLoc(); 7452 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7453 7454 SmallVector<EVT, 4> ValueVTs; 7455 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7456 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7457 SDVTList VTs = DAG.getVTList(ValueVTs); 7458 7459 auto EVLParamPos = 7460 VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID()); 7461 7462 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7463 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7464 "Unexpected target EVL type"); 7465 7466 // Request operands. 7467 SmallVector<SDValue, 7> OpValues; 7468 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7469 auto Op = getValue(VPIntrin.getArgOperand(I)); 7470 if (I == EVLParamPos) 7471 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7472 OpValues.push_back(Op); 7473 } 7474 7475 switch (Opcode) { 7476 default: { 7477 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7478 setValue(&VPIntrin, Result); 7479 break; 7480 } 7481 case ISD::VP_LOAD: 7482 case ISD::VP_GATHER: 7483 visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues, 7484 Opcode == ISD::VP_GATHER); 7485 break; 7486 case ISD::VP_STORE: 7487 case ISD::VP_SCATTER: 7488 visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER); 7489 break; 7490 } 7491 } 7492 7493 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7494 const BasicBlock *EHPadBB, 7495 MCSymbol *&BeginLabel) { 7496 MachineFunction &MF = DAG.getMachineFunction(); 7497 MachineModuleInfo &MMI = MF.getMMI(); 7498 7499 // Insert a label before the invoke call to mark the try range. This can be 7500 // used to detect deletion of the invoke via the MachineModuleInfo. 7501 BeginLabel = MMI.getContext().createTempSymbol(); 7502 7503 // For SjLj, keep track of which landing pads go with which invokes 7504 // so as to maintain the ordering of pads in the LSDA. 7505 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7506 if (CallSiteIndex) { 7507 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7508 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7509 7510 // Now that the call site is handled, stop tracking it. 7511 MMI.setCurrentCallSite(0); 7512 } 7513 7514 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7515 } 7516 7517 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7518 const BasicBlock *EHPadBB, 7519 MCSymbol *BeginLabel) { 7520 assert(BeginLabel && "BeginLabel should've been set"); 7521 7522 MachineFunction &MF = DAG.getMachineFunction(); 7523 MachineModuleInfo &MMI = MF.getMMI(); 7524 7525 // Insert a label at the end of the invoke call to mark the try range. This 7526 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7527 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7528 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7529 7530 // Inform MachineModuleInfo of range. 7531 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7532 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7533 // actually use outlined funclets and their LSDA info style. 7534 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7535 assert(II && "II should've been set"); 7536 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7537 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7538 } else if (!isScopedEHPersonality(Pers)) { 7539 assert(EHPadBB); 7540 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7541 } 7542 7543 return Chain; 7544 } 7545 7546 std::pair<SDValue, SDValue> 7547 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7548 const BasicBlock *EHPadBB) { 7549 MCSymbol *BeginLabel = nullptr; 7550 7551 if (EHPadBB) { 7552 // Both PendingLoads and PendingExports must be flushed here; 7553 // this call might not return. 7554 (void)getRoot(); 7555 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7556 CLI.setChain(getRoot()); 7557 } 7558 7559 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7560 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7561 7562 assert((CLI.IsTailCall || Result.second.getNode()) && 7563 "Non-null chain expected with non-tail call!"); 7564 assert((Result.second.getNode() || !Result.first.getNode()) && 7565 "Null value expected with tail call!"); 7566 7567 if (!Result.second.getNode()) { 7568 // As a special case, a null chain means that a tail call has been emitted 7569 // and the DAG root is already updated. 7570 HasTailCall = true; 7571 7572 // Since there's no actual continuation from this block, nothing can be 7573 // relying on us setting vregs for them. 7574 PendingExports.clear(); 7575 } else { 7576 DAG.setRoot(Result.second); 7577 } 7578 7579 if (EHPadBB) { 7580 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7581 BeginLabel)); 7582 } 7583 7584 return Result; 7585 } 7586 7587 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7588 bool isTailCall, 7589 bool isMustTailCall, 7590 const BasicBlock *EHPadBB) { 7591 auto &DL = DAG.getDataLayout(); 7592 FunctionType *FTy = CB.getFunctionType(); 7593 Type *RetTy = CB.getType(); 7594 7595 TargetLowering::ArgListTy Args; 7596 Args.reserve(CB.arg_size()); 7597 7598 const Value *SwiftErrorVal = nullptr; 7599 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7600 7601 if (isTailCall) { 7602 // Avoid emitting tail calls in functions with the disable-tail-calls 7603 // attribute. 7604 auto *Caller = CB.getParent()->getParent(); 7605 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7606 "true" && !isMustTailCall) 7607 isTailCall = false; 7608 7609 // We can't tail call inside a function with a swifterror argument. Lowering 7610 // does not support this yet. It would have to move into the swifterror 7611 // register before the call. 7612 if (TLI.supportSwiftError() && 7613 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7614 isTailCall = false; 7615 } 7616 7617 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7618 TargetLowering::ArgListEntry Entry; 7619 const Value *V = *I; 7620 7621 // Skip empty types 7622 if (V->getType()->isEmptyTy()) 7623 continue; 7624 7625 SDValue ArgNode = getValue(V); 7626 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7627 7628 Entry.setAttributes(&CB, I - CB.arg_begin()); 7629 7630 // Use swifterror virtual register as input to the call. 7631 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7632 SwiftErrorVal = V; 7633 // We find the virtual register for the actual swifterror argument. 7634 // Instead of using the Value, we use the virtual register instead. 7635 Entry.Node = 7636 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7637 EVT(TLI.getPointerTy(DL))); 7638 } 7639 7640 Args.push_back(Entry); 7641 7642 // If we have an explicit sret argument that is an Instruction, (i.e., it 7643 // might point to function-local memory), we can't meaningfully tail-call. 7644 if (Entry.IsSRet && isa<Instruction>(V)) 7645 isTailCall = false; 7646 } 7647 7648 // If call site has a cfguardtarget operand bundle, create and add an 7649 // additional ArgListEntry. 7650 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7651 TargetLowering::ArgListEntry Entry; 7652 Value *V = Bundle->Inputs[0]; 7653 SDValue ArgNode = getValue(V); 7654 Entry.Node = ArgNode; 7655 Entry.Ty = V->getType(); 7656 Entry.IsCFGuardTarget = true; 7657 Args.push_back(Entry); 7658 } 7659 7660 // Check if target-independent constraints permit a tail call here. 7661 // Target-dependent constraints are checked within TLI->LowerCallTo. 7662 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7663 isTailCall = false; 7664 7665 // Disable tail calls if there is an swifterror argument. Targets have not 7666 // been updated to support tail calls. 7667 if (TLI.supportSwiftError() && SwiftErrorVal) 7668 isTailCall = false; 7669 7670 TargetLowering::CallLoweringInfo CLI(DAG); 7671 CLI.setDebugLoc(getCurSDLoc()) 7672 .setChain(getRoot()) 7673 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7674 .setTailCall(isTailCall) 7675 .setConvergent(CB.isConvergent()) 7676 .setIsPreallocated( 7677 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7678 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7679 7680 if (Result.first.getNode()) { 7681 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7682 setValue(&CB, Result.first); 7683 } 7684 7685 // The last element of CLI.InVals has the SDValue for swifterror return. 7686 // Here we copy it to a virtual register and update SwiftErrorMap for 7687 // book-keeping. 7688 if (SwiftErrorVal && TLI.supportSwiftError()) { 7689 // Get the last element of InVals. 7690 SDValue Src = CLI.InVals.back(); 7691 Register VReg = 7692 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7693 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7694 DAG.setRoot(CopyNode); 7695 } 7696 } 7697 7698 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7699 SelectionDAGBuilder &Builder) { 7700 // Check to see if this load can be trivially constant folded, e.g. if the 7701 // input is from a string literal. 7702 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7703 // Cast pointer to the type we really want to load. 7704 Type *LoadTy = 7705 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7706 if (LoadVT.isVector()) 7707 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7708 7709 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7710 PointerType::getUnqual(LoadTy)); 7711 7712 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7713 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7714 return Builder.getValue(LoadCst); 7715 } 7716 7717 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7718 // still constant memory, the input chain can be the entry node. 7719 SDValue Root; 7720 bool ConstantMemory = false; 7721 7722 // Do not serialize (non-volatile) loads of constant memory with anything. 7723 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7724 Root = Builder.DAG.getEntryNode(); 7725 ConstantMemory = true; 7726 } else { 7727 // Do not serialize non-volatile loads against each other. 7728 Root = Builder.DAG.getRoot(); 7729 } 7730 7731 SDValue Ptr = Builder.getValue(PtrVal); 7732 SDValue LoadVal = 7733 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7734 MachinePointerInfo(PtrVal), Align(1)); 7735 7736 if (!ConstantMemory) 7737 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7738 return LoadVal; 7739 } 7740 7741 /// Record the value for an instruction that produces an integer result, 7742 /// converting the type where necessary. 7743 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7744 SDValue Value, 7745 bool IsSigned) { 7746 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7747 I.getType(), true); 7748 if (IsSigned) 7749 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7750 else 7751 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7752 setValue(&I, Value); 7753 } 7754 7755 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7756 /// true and lower it. Otherwise return false, and it will be lowered like a 7757 /// normal call. 7758 /// The caller already checked that \p I calls the appropriate LibFunc with a 7759 /// correct prototype. 7760 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7761 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7762 const Value *Size = I.getArgOperand(2); 7763 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7764 if (CSize && CSize->getZExtValue() == 0) { 7765 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7766 I.getType(), true); 7767 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7768 return true; 7769 } 7770 7771 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7772 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7773 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7774 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7775 if (Res.first.getNode()) { 7776 processIntegerCallValue(I, Res.first, true); 7777 PendingLoads.push_back(Res.second); 7778 return true; 7779 } 7780 7781 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7782 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7783 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7784 return false; 7785 7786 // If the target has a fast compare for the given size, it will return a 7787 // preferred load type for that size. Require that the load VT is legal and 7788 // that the target supports unaligned loads of that type. Otherwise, return 7789 // INVALID. 7790 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7791 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7792 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7793 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7794 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7795 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7796 // TODO: Check alignment of src and dest ptrs. 7797 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7798 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7799 if (!TLI.isTypeLegal(LVT) || 7800 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7801 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7802 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7803 } 7804 7805 return LVT; 7806 }; 7807 7808 // This turns into unaligned loads. We only do this if the target natively 7809 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7810 // we'll only produce a small number of byte loads. 7811 MVT LoadVT; 7812 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7813 switch (NumBitsToCompare) { 7814 default: 7815 return false; 7816 case 16: 7817 LoadVT = MVT::i16; 7818 break; 7819 case 32: 7820 LoadVT = MVT::i32; 7821 break; 7822 case 64: 7823 case 128: 7824 case 256: 7825 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7826 break; 7827 } 7828 7829 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7830 return false; 7831 7832 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7833 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7834 7835 // Bitcast to a wide integer type if the loads are vectors. 7836 if (LoadVT.isVector()) { 7837 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7838 LoadL = DAG.getBitcast(CmpVT, LoadL); 7839 LoadR = DAG.getBitcast(CmpVT, LoadR); 7840 } 7841 7842 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7843 processIntegerCallValue(I, Cmp, false); 7844 return true; 7845 } 7846 7847 /// See if we can lower a memchr call into an optimized form. If so, return 7848 /// true and lower it. Otherwise return false, and it will be lowered like a 7849 /// normal call. 7850 /// The caller already checked that \p I calls the appropriate LibFunc with a 7851 /// correct prototype. 7852 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7853 const Value *Src = I.getArgOperand(0); 7854 const Value *Char = I.getArgOperand(1); 7855 const Value *Length = I.getArgOperand(2); 7856 7857 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7858 std::pair<SDValue, SDValue> Res = 7859 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7860 getValue(Src), getValue(Char), getValue(Length), 7861 MachinePointerInfo(Src)); 7862 if (Res.first.getNode()) { 7863 setValue(&I, Res.first); 7864 PendingLoads.push_back(Res.second); 7865 return true; 7866 } 7867 7868 return false; 7869 } 7870 7871 /// See if we can lower a mempcpy call into an optimized form. If so, return 7872 /// true and lower it. Otherwise return false, and it will be lowered like a 7873 /// normal call. 7874 /// The caller already checked that \p I calls the appropriate LibFunc with a 7875 /// correct prototype. 7876 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7877 SDValue Dst = getValue(I.getArgOperand(0)); 7878 SDValue Src = getValue(I.getArgOperand(1)); 7879 SDValue Size = getValue(I.getArgOperand(2)); 7880 7881 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7882 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7883 // DAG::getMemcpy needs Alignment to be defined. 7884 Align Alignment = std::min(DstAlign, SrcAlign); 7885 7886 bool isVol = false; 7887 SDLoc sdl = getCurSDLoc(); 7888 7889 // In the mempcpy context we need to pass in a false value for isTailCall 7890 // because the return pointer needs to be adjusted by the size of 7891 // the copied memory. 7892 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7893 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7894 /*isTailCall=*/false, 7895 MachinePointerInfo(I.getArgOperand(0)), 7896 MachinePointerInfo(I.getArgOperand(1)), 7897 I.getAAMetadata()); 7898 assert(MC.getNode() != nullptr && 7899 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7900 DAG.setRoot(MC); 7901 7902 // Check if Size needs to be truncated or extended. 7903 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7904 7905 // Adjust return pointer to point just past the last dst byte. 7906 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7907 Dst, Size); 7908 setValue(&I, DstPlusSize); 7909 return true; 7910 } 7911 7912 /// See if we can lower a strcpy call into an optimized form. If so, return 7913 /// true and lower it, otherwise return false and it will be lowered like a 7914 /// normal call. 7915 /// The caller already checked that \p I calls the appropriate LibFunc with a 7916 /// correct prototype. 7917 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7918 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7919 7920 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7921 std::pair<SDValue, SDValue> Res = 7922 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7923 getValue(Arg0), getValue(Arg1), 7924 MachinePointerInfo(Arg0), 7925 MachinePointerInfo(Arg1), isStpcpy); 7926 if (Res.first.getNode()) { 7927 setValue(&I, Res.first); 7928 DAG.setRoot(Res.second); 7929 return true; 7930 } 7931 7932 return false; 7933 } 7934 7935 /// See if we can lower a strcmp call into an optimized form. If so, return 7936 /// true and lower it, otherwise return false and it will be lowered like a 7937 /// normal call. 7938 /// The caller already checked that \p I calls the appropriate LibFunc with a 7939 /// correct prototype. 7940 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7941 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7942 7943 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7944 std::pair<SDValue, SDValue> Res = 7945 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7946 getValue(Arg0), getValue(Arg1), 7947 MachinePointerInfo(Arg0), 7948 MachinePointerInfo(Arg1)); 7949 if (Res.first.getNode()) { 7950 processIntegerCallValue(I, Res.first, true); 7951 PendingLoads.push_back(Res.second); 7952 return true; 7953 } 7954 7955 return false; 7956 } 7957 7958 /// See if we can lower a strlen call into an optimized form. If so, return 7959 /// true and lower it, otherwise return false and it will be lowered like a 7960 /// normal call. 7961 /// The caller already checked that \p I calls the appropriate LibFunc with a 7962 /// correct prototype. 7963 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7964 const Value *Arg0 = I.getArgOperand(0); 7965 7966 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7967 std::pair<SDValue, SDValue> Res = 7968 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7969 getValue(Arg0), MachinePointerInfo(Arg0)); 7970 if (Res.first.getNode()) { 7971 processIntegerCallValue(I, Res.first, false); 7972 PendingLoads.push_back(Res.second); 7973 return true; 7974 } 7975 7976 return false; 7977 } 7978 7979 /// See if we can lower a strnlen call into an optimized form. If so, return 7980 /// true and lower it, otherwise return false and it will be lowered like a 7981 /// normal call. 7982 /// The caller already checked that \p I calls the appropriate LibFunc with a 7983 /// correct prototype. 7984 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7985 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7986 7987 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7988 std::pair<SDValue, SDValue> Res = 7989 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7990 getValue(Arg0), getValue(Arg1), 7991 MachinePointerInfo(Arg0)); 7992 if (Res.first.getNode()) { 7993 processIntegerCallValue(I, Res.first, false); 7994 PendingLoads.push_back(Res.second); 7995 return true; 7996 } 7997 7998 return false; 7999 } 8000 8001 /// See if we can lower a unary floating-point operation into an SDNode with 8002 /// the specified Opcode. If so, return true and lower it, otherwise return 8003 /// false and it will be lowered like a normal call. 8004 /// The caller already checked that \p I calls the appropriate LibFunc with a 8005 /// correct prototype. 8006 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8007 unsigned Opcode) { 8008 // We already checked this call's prototype; verify it doesn't modify errno. 8009 if (!I.onlyReadsMemory()) 8010 return false; 8011 8012 SDNodeFlags Flags; 8013 Flags.copyFMF(cast<FPMathOperator>(I)); 8014 8015 SDValue Tmp = getValue(I.getArgOperand(0)); 8016 setValue(&I, 8017 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8018 return true; 8019 } 8020 8021 /// See if we can lower a binary floating-point operation into an SDNode with 8022 /// the specified Opcode. If so, return true and lower it. Otherwise return 8023 /// false, and it will be lowered like a normal call. 8024 /// The caller already checked that \p I calls the appropriate LibFunc with a 8025 /// correct prototype. 8026 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8027 unsigned Opcode) { 8028 // We already checked this call's prototype; verify it doesn't modify errno. 8029 if (!I.onlyReadsMemory()) 8030 return false; 8031 8032 SDNodeFlags Flags; 8033 Flags.copyFMF(cast<FPMathOperator>(I)); 8034 8035 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8036 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8037 EVT VT = Tmp0.getValueType(); 8038 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8039 return true; 8040 } 8041 8042 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8043 // Handle inline assembly differently. 8044 if (I.isInlineAsm()) { 8045 visitInlineAsm(I); 8046 return; 8047 } 8048 8049 if (Function *F = I.getCalledFunction()) { 8050 diagnoseDontCall(I); 8051 8052 if (F->isDeclaration()) { 8053 // Is this an LLVM intrinsic or a target-specific intrinsic? 8054 unsigned IID = F->getIntrinsicID(); 8055 if (!IID) 8056 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8057 IID = II->getIntrinsicID(F); 8058 8059 if (IID) { 8060 visitIntrinsicCall(I, IID); 8061 return; 8062 } 8063 } 8064 8065 // Check for well-known libc/libm calls. If the function is internal, it 8066 // can't be a library call. Don't do the check if marked as nobuiltin for 8067 // some reason or the call site requires strict floating point semantics. 8068 LibFunc Func; 8069 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8070 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8071 LibInfo->hasOptimizedCodeGen(Func)) { 8072 switch (Func) { 8073 default: break; 8074 case LibFunc_bcmp: 8075 if (visitMemCmpBCmpCall(I)) 8076 return; 8077 break; 8078 case LibFunc_copysign: 8079 case LibFunc_copysignf: 8080 case LibFunc_copysignl: 8081 // We already checked this call's prototype; verify it doesn't modify 8082 // errno. 8083 if (I.onlyReadsMemory()) { 8084 SDValue LHS = getValue(I.getArgOperand(0)); 8085 SDValue RHS = getValue(I.getArgOperand(1)); 8086 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8087 LHS.getValueType(), LHS, RHS)); 8088 return; 8089 } 8090 break; 8091 case LibFunc_fabs: 8092 case LibFunc_fabsf: 8093 case LibFunc_fabsl: 8094 if (visitUnaryFloatCall(I, ISD::FABS)) 8095 return; 8096 break; 8097 case LibFunc_fmin: 8098 case LibFunc_fminf: 8099 case LibFunc_fminl: 8100 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8101 return; 8102 break; 8103 case LibFunc_fmax: 8104 case LibFunc_fmaxf: 8105 case LibFunc_fmaxl: 8106 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8107 return; 8108 break; 8109 case LibFunc_sin: 8110 case LibFunc_sinf: 8111 case LibFunc_sinl: 8112 if (visitUnaryFloatCall(I, ISD::FSIN)) 8113 return; 8114 break; 8115 case LibFunc_cos: 8116 case LibFunc_cosf: 8117 case LibFunc_cosl: 8118 if (visitUnaryFloatCall(I, ISD::FCOS)) 8119 return; 8120 break; 8121 case LibFunc_sqrt: 8122 case LibFunc_sqrtf: 8123 case LibFunc_sqrtl: 8124 case LibFunc_sqrt_finite: 8125 case LibFunc_sqrtf_finite: 8126 case LibFunc_sqrtl_finite: 8127 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8128 return; 8129 break; 8130 case LibFunc_floor: 8131 case LibFunc_floorf: 8132 case LibFunc_floorl: 8133 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8134 return; 8135 break; 8136 case LibFunc_nearbyint: 8137 case LibFunc_nearbyintf: 8138 case LibFunc_nearbyintl: 8139 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8140 return; 8141 break; 8142 case LibFunc_ceil: 8143 case LibFunc_ceilf: 8144 case LibFunc_ceill: 8145 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8146 return; 8147 break; 8148 case LibFunc_rint: 8149 case LibFunc_rintf: 8150 case LibFunc_rintl: 8151 if (visitUnaryFloatCall(I, ISD::FRINT)) 8152 return; 8153 break; 8154 case LibFunc_round: 8155 case LibFunc_roundf: 8156 case LibFunc_roundl: 8157 if (visitUnaryFloatCall(I, ISD::FROUND)) 8158 return; 8159 break; 8160 case LibFunc_trunc: 8161 case LibFunc_truncf: 8162 case LibFunc_truncl: 8163 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8164 return; 8165 break; 8166 case LibFunc_log2: 8167 case LibFunc_log2f: 8168 case LibFunc_log2l: 8169 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8170 return; 8171 break; 8172 case LibFunc_exp2: 8173 case LibFunc_exp2f: 8174 case LibFunc_exp2l: 8175 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8176 return; 8177 break; 8178 case LibFunc_memcmp: 8179 if (visitMemCmpBCmpCall(I)) 8180 return; 8181 break; 8182 case LibFunc_mempcpy: 8183 if (visitMemPCpyCall(I)) 8184 return; 8185 break; 8186 case LibFunc_memchr: 8187 if (visitMemChrCall(I)) 8188 return; 8189 break; 8190 case LibFunc_strcpy: 8191 if (visitStrCpyCall(I, false)) 8192 return; 8193 break; 8194 case LibFunc_stpcpy: 8195 if (visitStrCpyCall(I, true)) 8196 return; 8197 break; 8198 case LibFunc_strcmp: 8199 if (visitStrCmpCall(I)) 8200 return; 8201 break; 8202 case LibFunc_strlen: 8203 if (visitStrLenCall(I)) 8204 return; 8205 break; 8206 case LibFunc_strnlen: 8207 if (visitStrNLenCall(I)) 8208 return; 8209 break; 8210 } 8211 } 8212 } 8213 8214 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8215 // have to do anything here to lower funclet bundles. 8216 // CFGuardTarget bundles are lowered in LowerCallTo. 8217 assert(!I.hasOperandBundlesOtherThan( 8218 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8219 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8220 LLVMContext::OB_clang_arc_attachedcall}) && 8221 "Cannot lower calls with arbitrary operand bundles!"); 8222 8223 SDValue Callee = getValue(I.getCalledOperand()); 8224 8225 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8226 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8227 else 8228 // Check if we can potentially perform a tail call. More detailed checking 8229 // is be done within LowerCallTo, after more information about the call is 8230 // known. 8231 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8232 } 8233 8234 namespace { 8235 8236 /// AsmOperandInfo - This contains information for each constraint that we are 8237 /// lowering. 8238 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8239 public: 8240 /// CallOperand - If this is the result output operand or a clobber 8241 /// this is null, otherwise it is the incoming operand to the CallInst. 8242 /// This gets modified as the asm is processed. 8243 SDValue CallOperand; 8244 8245 /// AssignedRegs - If this is a register or register class operand, this 8246 /// contains the set of register corresponding to the operand. 8247 RegsForValue AssignedRegs; 8248 8249 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8250 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8251 } 8252 8253 /// Whether or not this operand accesses memory 8254 bool hasMemory(const TargetLowering &TLI) const { 8255 // Indirect operand accesses access memory. 8256 if (isIndirect) 8257 return true; 8258 8259 for (const auto &Code : Codes) 8260 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8261 return true; 8262 8263 return false; 8264 } 8265 8266 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8267 /// corresponds to. If there is no Value* for this operand, it returns 8268 /// MVT::Other. 8269 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8270 const DataLayout &DL) const { 8271 if (!CallOperandVal) return MVT::Other; 8272 8273 if (isa<BasicBlock>(CallOperandVal)) 8274 return TLI.getProgramPointerTy(DL); 8275 8276 llvm::Type *OpTy = CallOperandVal->getType(); 8277 8278 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8279 // If this is an indirect operand, the operand is a pointer to the 8280 // accessed type. 8281 if (isIndirect) { 8282 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8283 if (!PtrTy) 8284 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8285 OpTy = PtrTy->getElementType(); 8286 } 8287 8288 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8289 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8290 if (STy->getNumElements() == 1) 8291 OpTy = STy->getElementType(0); 8292 8293 // If OpTy is not a single value, it may be a struct/union that we 8294 // can tile with integers. 8295 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8296 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8297 switch (BitSize) { 8298 default: break; 8299 case 1: 8300 case 8: 8301 case 16: 8302 case 32: 8303 case 64: 8304 case 128: 8305 OpTy = IntegerType::get(Context, BitSize); 8306 break; 8307 } 8308 } 8309 8310 return TLI.getAsmOperandValueType(DL, OpTy, true); 8311 } 8312 }; 8313 8314 8315 } // end anonymous namespace 8316 8317 /// Make sure that the output operand \p OpInfo and its corresponding input 8318 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8319 /// out). 8320 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8321 SDISelAsmOperandInfo &MatchingOpInfo, 8322 SelectionDAG &DAG) { 8323 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8324 return; 8325 8326 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8327 const auto &TLI = DAG.getTargetLoweringInfo(); 8328 8329 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8330 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8331 OpInfo.ConstraintVT); 8332 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8333 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8334 MatchingOpInfo.ConstraintVT); 8335 if ((OpInfo.ConstraintVT.isInteger() != 8336 MatchingOpInfo.ConstraintVT.isInteger()) || 8337 (MatchRC.second != InputRC.second)) { 8338 // FIXME: error out in a more elegant fashion 8339 report_fatal_error("Unsupported asm: input constraint" 8340 " with a matching output constraint of" 8341 " incompatible type!"); 8342 } 8343 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8344 } 8345 8346 /// Get a direct memory input to behave well as an indirect operand. 8347 /// This may introduce stores, hence the need for a \p Chain. 8348 /// \return The (possibly updated) chain. 8349 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8350 SDISelAsmOperandInfo &OpInfo, 8351 SelectionDAG &DAG) { 8352 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8353 8354 // If we don't have an indirect input, put it in the constpool if we can, 8355 // otherwise spill it to a stack slot. 8356 // TODO: This isn't quite right. We need to handle these according to 8357 // the addressing mode that the constraint wants. Also, this may take 8358 // an additional register for the computation and we don't want that 8359 // either. 8360 8361 // If the operand is a float, integer, or vector constant, spill to a 8362 // constant pool entry to get its address. 8363 const Value *OpVal = OpInfo.CallOperandVal; 8364 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8365 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8366 OpInfo.CallOperand = DAG.getConstantPool( 8367 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8368 return Chain; 8369 } 8370 8371 // Otherwise, create a stack slot and emit a store to it before the asm. 8372 Type *Ty = OpVal->getType(); 8373 auto &DL = DAG.getDataLayout(); 8374 uint64_t TySize = DL.getTypeAllocSize(Ty); 8375 MachineFunction &MF = DAG.getMachineFunction(); 8376 int SSFI = MF.getFrameInfo().CreateStackObject( 8377 TySize, DL.getPrefTypeAlign(Ty), false); 8378 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8379 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8380 MachinePointerInfo::getFixedStack(MF, SSFI), 8381 TLI.getMemValueType(DL, Ty)); 8382 OpInfo.CallOperand = StackSlot; 8383 8384 return Chain; 8385 } 8386 8387 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8388 /// specified operand. We prefer to assign virtual registers, to allow the 8389 /// register allocator to handle the assignment process. However, if the asm 8390 /// uses features that we can't model on machineinstrs, we have SDISel do the 8391 /// allocation. This produces generally horrible, but correct, code. 8392 /// 8393 /// OpInfo describes the operand 8394 /// RefOpInfo describes the matching operand if any, the operand otherwise 8395 static llvm::Optional<unsigned> 8396 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8397 SDISelAsmOperandInfo &OpInfo, 8398 SDISelAsmOperandInfo &RefOpInfo) { 8399 LLVMContext &Context = *DAG.getContext(); 8400 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8401 8402 MachineFunction &MF = DAG.getMachineFunction(); 8403 SmallVector<unsigned, 4> Regs; 8404 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8405 8406 // No work to do for memory operations. 8407 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8408 return None; 8409 8410 // If this is a constraint for a single physreg, or a constraint for a 8411 // register class, find it. 8412 unsigned AssignedReg; 8413 const TargetRegisterClass *RC; 8414 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8415 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8416 // RC is unset only on failure. Return immediately. 8417 if (!RC) 8418 return None; 8419 8420 // Get the actual register value type. This is important, because the user 8421 // may have asked for (e.g.) the AX register in i32 type. We need to 8422 // remember that AX is actually i16 to get the right extension. 8423 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8424 8425 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8426 // If this is an FP operand in an integer register (or visa versa), or more 8427 // generally if the operand value disagrees with the register class we plan 8428 // to stick it in, fix the operand type. 8429 // 8430 // If this is an input value, the bitcast to the new type is done now. 8431 // Bitcast for output value is done at the end of visitInlineAsm(). 8432 if ((OpInfo.Type == InlineAsm::isOutput || 8433 OpInfo.Type == InlineAsm::isInput) && 8434 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8435 // Try to convert to the first EVT that the reg class contains. If the 8436 // types are identical size, use a bitcast to convert (e.g. two differing 8437 // vector types). Note: output bitcast is done at the end of 8438 // visitInlineAsm(). 8439 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8440 // Exclude indirect inputs while they are unsupported because the code 8441 // to perform the load is missing and thus OpInfo.CallOperand still 8442 // refers to the input address rather than the pointed-to value. 8443 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8444 OpInfo.CallOperand = 8445 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8446 OpInfo.ConstraintVT = RegVT; 8447 // If the operand is an FP value and we want it in integer registers, 8448 // use the corresponding integer type. This turns an f64 value into 8449 // i64, which can be passed with two i32 values on a 32-bit machine. 8450 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8451 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8452 if (OpInfo.Type == InlineAsm::isInput) 8453 OpInfo.CallOperand = 8454 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8455 OpInfo.ConstraintVT = VT; 8456 } 8457 } 8458 } 8459 8460 // No need to allocate a matching input constraint since the constraint it's 8461 // matching to has already been allocated. 8462 if (OpInfo.isMatchingInputConstraint()) 8463 return None; 8464 8465 EVT ValueVT = OpInfo.ConstraintVT; 8466 if (OpInfo.ConstraintVT == MVT::Other) 8467 ValueVT = RegVT; 8468 8469 // Initialize NumRegs. 8470 unsigned NumRegs = 1; 8471 if (OpInfo.ConstraintVT != MVT::Other) 8472 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8473 8474 // If this is a constraint for a specific physical register, like {r17}, 8475 // assign it now. 8476 8477 // If this associated to a specific register, initialize iterator to correct 8478 // place. If virtual, make sure we have enough registers 8479 8480 // Initialize iterator if necessary 8481 TargetRegisterClass::iterator I = RC->begin(); 8482 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8483 8484 // Do not check for single registers. 8485 if (AssignedReg) { 8486 I = std::find(I, RC->end(), AssignedReg); 8487 if (I == RC->end()) { 8488 // RC does not contain the selected register, which indicates a 8489 // mismatch between the register and the required type/bitwidth. 8490 return {AssignedReg}; 8491 } 8492 } 8493 8494 for (; NumRegs; --NumRegs, ++I) { 8495 assert(I != RC->end() && "Ran out of registers to allocate!"); 8496 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8497 Regs.push_back(R); 8498 } 8499 8500 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8501 return None; 8502 } 8503 8504 static unsigned 8505 findMatchingInlineAsmOperand(unsigned OperandNo, 8506 const std::vector<SDValue> &AsmNodeOperands) { 8507 // Scan until we find the definition we already emitted of this operand. 8508 unsigned CurOp = InlineAsm::Op_FirstOperand; 8509 for (; OperandNo; --OperandNo) { 8510 // Advance to the next operand. 8511 unsigned OpFlag = 8512 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8513 assert((InlineAsm::isRegDefKind(OpFlag) || 8514 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8515 InlineAsm::isMemKind(OpFlag)) && 8516 "Skipped past definitions?"); 8517 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8518 } 8519 return CurOp; 8520 } 8521 8522 namespace { 8523 8524 class ExtraFlags { 8525 unsigned Flags = 0; 8526 8527 public: 8528 explicit ExtraFlags(const CallBase &Call) { 8529 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8530 if (IA->hasSideEffects()) 8531 Flags |= InlineAsm::Extra_HasSideEffects; 8532 if (IA->isAlignStack()) 8533 Flags |= InlineAsm::Extra_IsAlignStack; 8534 if (Call.isConvergent()) 8535 Flags |= InlineAsm::Extra_IsConvergent; 8536 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8537 } 8538 8539 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8540 // Ideally, we would only check against memory constraints. However, the 8541 // meaning of an Other constraint can be target-specific and we can't easily 8542 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8543 // for Other constraints as well. 8544 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8545 OpInfo.ConstraintType == TargetLowering::C_Other) { 8546 if (OpInfo.Type == InlineAsm::isInput) 8547 Flags |= InlineAsm::Extra_MayLoad; 8548 else if (OpInfo.Type == InlineAsm::isOutput) 8549 Flags |= InlineAsm::Extra_MayStore; 8550 else if (OpInfo.Type == InlineAsm::isClobber) 8551 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8552 } 8553 } 8554 8555 unsigned get() const { return Flags; } 8556 }; 8557 8558 } // end anonymous namespace 8559 8560 /// visitInlineAsm - Handle a call to an InlineAsm object. 8561 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8562 const BasicBlock *EHPadBB) { 8563 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8564 8565 /// ConstraintOperands - Information about all of the constraints. 8566 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8567 8568 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8569 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8570 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8571 8572 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8573 // AsmDialect, MayLoad, MayStore). 8574 bool HasSideEffect = IA->hasSideEffects(); 8575 ExtraFlags ExtraInfo(Call); 8576 8577 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8578 unsigned ResNo = 0; // ResNo - The result number of the next output. 8579 unsigned NumMatchingOps = 0; 8580 for (auto &T : TargetConstraints) { 8581 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8582 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8583 8584 // Compute the value type for each operand. 8585 if (OpInfo.Type == InlineAsm::isInput || 8586 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8587 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8588 8589 // Process the call argument. BasicBlocks are labels, currently appearing 8590 // only in asm's. 8591 if (isa<CallBrInst>(Call) && 8592 ArgNo - 1 >= (cast<CallBrInst>(&Call)->arg_size() - 8593 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8594 NumMatchingOps) && 8595 (NumMatchingOps == 0 || 8596 ArgNo - 1 < 8597 (cast<CallBrInst>(&Call)->arg_size() - NumMatchingOps))) { 8598 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8599 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8600 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8601 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8602 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8603 } else { 8604 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8605 } 8606 8607 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8608 DAG.getDataLayout()); 8609 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8610 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8611 // The return value of the call is this value. As such, there is no 8612 // corresponding argument. 8613 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8614 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8615 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8616 DAG.getDataLayout(), STy->getElementType(ResNo)); 8617 } else { 8618 assert(ResNo == 0 && "Asm only has one result!"); 8619 OpInfo.ConstraintVT = TLI.getAsmOperandValueType( 8620 DAG.getDataLayout(), Call.getType()).getSimpleVT(); 8621 } 8622 ++ResNo; 8623 } else { 8624 OpInfo.ConstraintVT = MVT::Other; 8625 } 8626 8627 if (OpInfo.hasMatchingInput()) 8628 ++NumMatchingOps; 8629 8630 if (!HasSideEffect) 8631 HasSideEffect = OpInfo.hasMemory(TLI); 8632 8633 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8634 // FIXME: Could we compute this on OpInfo rather than T? 8635 8636 // Compute the constraint code and ConstraintType to use. 8637 TLI.ComputeConstraintToUse(T, SDValue()); 8638 8639 if (T.ConstraintType == TargetLowering::C_Immediate && 8640 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8641 // We've delayed emitting a diagnostic like the "n" constraint because 8642 // inlining could cause an integer showing up. 8643 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8644 "' expects an integer constant " 8645 "expression"); 8646 8647 ExtraInfo.update(T); 8648 } 8649 8650 // We won't need to flush pending loads if this asm doesn't touch 8651 // memory and is nonvolatile. 8652 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8653 8654 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8655 if (EmitEHLabels) { 8656 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8657 } 8658 bool IsCallBr = isa<CallBrInst>(Call); 8659 8660 if (IsCallBr || EmitEHLabels) { 8661 // If this is a callbr or invoke we need to flush pending exports since 8662 // inlineasm_br and invoke are terminators. 8663 // We need to do this before nodes are glued to the inlineasm_br node. 8664 Chain = getControlRoot(); 8665 } 8666 8667 MCSymbol *BeginLabel = nullptr; 8668 if (EmitEHLabels) { 8669 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8670 } 8671 8672 // Second pass over the constraints: compute which constraint option to use. 8673 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8674 // If this is an output operand with a matching input operand, look up the 8675 // matching input. If their types mismatch, e.g. one is an integer, the 8676 // other is floating point, or their sizes are different, flag it as an 8677 // error. 8678 if (OpInfo.hasMatchingInput()) { 8679 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8680 patchMatchingInput(OpInfo, Input, DAG); 8681 } 8682 8683 // Compute the constraint code and ConstraintType to use. 8684 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8685 8686 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8687 OpInfo.Type == InlineAsm::isClobber) 8688 continue; 8689 8690 // If this is a memory input, and if the operand is not indirect, do what we 8691 // need to provide an address for the memory input. 8692 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8693 !OpInfo.isIndirect) { 8694 assert((OpInfo.isMultipleAlternative || 8695 (OpInfo.Type == InlineAsm::isInput)) && 8696 "Can only indirectify direct input operands!"); 8697 8698 // Memory operands really want the address of the value. 8699 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8700 8701 // There is no longer a Value* corresponding to this operand. 8702 OpInfo.CallOperandVal = nullptr; 8703 8704 // It is now an indirect operand. 8705 OpInfo.isIndirect = true; 8706 } 8707 8708 } 8709 8710 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8711 std::vector<SDValue> AsmNodeOperands; 8712 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8713 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8714 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8715 8716 // If we have a !srcloc metadata node associated with it, we want to attach 8717 // this to the ultimately generated inline asm machineinstr. To do this, we 8718 // pass in the third operand as this (potentially null) inline asm MDNode. 8719 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8720 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8721 8722 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8723 // bits as operand 3. 8724 AsmNodeOperands.push_back(DAG.getTargetConstant( 8725 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8726 8727 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8728 // this, assign virtual and physical registers for inputs and otput. 8729 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8730 // Assign Registers. 8731 SDISelAsmOperandInfo &RefOpInfo = 8732 OpInfo.isMatchingInputConstraint() 8733 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8734 : OpInfo; 8735 const auto RegError = 8736 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8737 if (RegError.hasValue()) { 8738 const MachineFunction &MF = DAG.getMachineFunction(); 8739 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8740 const char *RegName = TRI.getName(RegError.getValue()); 8741 emitInlineAsmError(Call, "register '" + Twine(RegName) + 8742 "' allocated for constraint '" + 8743 Twine(OpInfo.ConstraintCode) + 8744 "' does not match required type"); 8745 return; 8746 } 8747 8748 auto DetectWriteToReservedRegister = [&]() { 8749 const MachineFunction &MF = DAG.getMachineFunction(); 8750 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8751 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8752 if (Register::isPhysicalRegister(Reg) && 8753 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8754 const char *RegName = TRI.getName(Reg); 8755 emitInlineAsmError(Call, "write to reserved register '" + 8756 Twine(RegName) + "'"); 8757 return true; 8758 } 8759 } 8760 return false; 8761 }; 8762 8763 switch (OpInfo.Type) { 8764 case InlineAsm::isOutput: 8765 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8766 unsigned ConstraintID = 8767 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8768 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8769 "Failed to convert memory constraint code to constraint id."); 8770 8771 // Add information to the INLINEASM node to know about this output. 8772 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8773 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8774 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8775 MVT::i32)); 8776 AsmNodeOperands.push_back(OpInfo.CallOperand); 8777 } else { 8778 // Otherwise, this outputs to a register (directly for C_Register / 8779 // C_RegisterClass, and a target-defined fashion for 8780 // C_Immediate/C_Other). Find a register that we can use. 8781 if (OpInfo.AssignedRegs.Regs.empty()) { 8782 emitInlineAsmError( 8783 Call, "couldn't allocate output register for constraint '" + 8784 Twine(OpInfo.ConstraintCode) + "'"); 8785 return; 8786 } 8787 8788 if (DetectWriteToReservedRegister()) 8789 return; 8790 8791 // Add information to the INLINEASM node to know that this register is 8792 // set. 8793 OpInfo.AssignedRegs.AddInlineAsmOperands( 8794 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8795 : InlineAsm::Kind_RegDef, 8796 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8797 } 8798 break; 8799 8800 case InlineAsm::isInput: { 8801 SDValue InOperandVal = OpInfo.CallOperand; 8802 8803 if (OpInfo.isMatchingInputConstraint()) { 8804 // If this is required to match an output register we have already set, 8805 // just use its register. 8806 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8807 AsmNodeOperands); 8808 unsigned OpFlag = 8809 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8810 if (InlineAsm::isRegDefKind(OpFlag) || 8811 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8812 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8813 if (OpInfo.isIndirect) { 8814 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8815 emitInlineAsmError(Call, "inline asm not supported yet: " 8816 "don't know how to handle tied " 8817 "indirect register inputs"); 8818 return; 8819 } 8820 8821 SmallVector<unsigned, 4> Regs; 8822 MachineFunction &MF = DAG.getMachineFunction(); 8823 MachineRegisterInfo &MRI = MF.getRegInfo(); 8824 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8825 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 8826 Register TiedReg = R->getReg(); 8827 MVT RegVT = R->getSimpleValueType(0); 8828 const TargetRegisterClass *RC = 8829 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 8830 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 8831 : TRI.getMinimalPhysRegClass(TiedReg); 8832 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8833 for (unsigned i = 0; i != NumRegs; ++i) 8834 Regs.push_back(MRI.createVirtualRegister(RC)); 8835 8836 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8837 8838 SDLoc dl = getCurSDLoc(); 8839 // Use the produced MatchedRegs object to 8840 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8841 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8842 true, OpInfo.getMatchedOperand(), dl, 8843 DAG, AsmNodeOperands); 8844 break; 8845 } 8846 8847 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8848 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8849 "Unexpected number of operands"); 8850 // Add information to the INLINEASM node to know about this input. 8851 // See InlineAsm.h isUseOperandTiedToDef. 8852 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8853 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8854 OpInfo.getMatchedOperand()); 8855 AsmNodeOperands.push_back(DAG.getTargetConstant( 8856 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8857 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8858 break; 8859 } 8860 8861 // Treat indirect 'X' constraint as memory. 8862 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8863 OpInfo.isIndirect) 8864 OpInfo.ConstraintType = TargetLowering::C_Memory; 8865 8866 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8867 OpInfo.ConstraintType == TargetLowering::C_Other) { 8868 std::vector<SDValue> Ops; 8869 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8870 Ops, DAG); 8871 if (Ops.empty()) { 8872 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8873 if (isa<ConstantSDNode>(InOperandVal)) { 8874 emitInlineAsmError(Call, "value out of range for constraint '" + 8875 Twine(OpInfo.ConstraintCode) + "'"); 8876 return; 8877 } 8878 8879 emitInlineAsmError(Call, 8880 "invalid operand for inline asm constraint '" + 8881 Twine(OpInfo.ConstraintCode) + "'"); 8882 return; 8883 } 8884 8885 // Add information to the INLINEASM node to know about this input. 8886 unsigned ResOpType = 8887 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8888 AsmNodeOperands.push_back(DAG.getTargetConstant( 8889 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8890 llvm::append_range(AsmNodeOperands, Ops); 8891 break; 8892 } 8893 8894 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8895 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8896 assert(InOperandVal.getValueType() == 8897 TLI.getPointerTy(DAG.getDataLayout()) && 8898 "Memory operands expect pointer values"); 8899 8900 unsigned ConstraintID = 8901 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8902 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8903 "Failed to convert memory constraint code to constraint id."); 8904 8905 // Add information to the INLINEASM node to know about this input. 8906 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8907 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8908 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8909 getCurSDLoc(), 8910 MVT::i32)); 8911 AsmNodeOperands.push_back(InOperandVal); 8912 break; 8913 } 8914 8915 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8916 OpInfo.ConstraintType == TargetLowering::C_Register) && 8917 "Unknown constraint type!"); 8918 8919 // TODO: Support this. 8920 if (OpInfo.isIndirect) { 8921 emitInlineAsmError( 8922 Call, "Don't know how to handle indirect register inputs yet " 8923 "for constraint '" + 8924 Twine(OpInfo.ConstraintCode) + "'"); 8925 return; 8926 } 8927 8928 // Copy the input into the appropriate registers. 8929 if (OpInfo.AssignedRegs.Regs.empty()) { 8930 emitInlineAsmError(Call, 8931 "couldn't allocate input reg for constraint '" + 8932 Twine(OpInfo.ConstraintCode) + "'"); 8933 return; 8934 } 8935 8936 if (DetectWriteToReservedRegister()) 8937 return; 8938 8939 SDLoc dl = getCurSDLoc(); 8940 8941 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8942 &Call); 8943 8944 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8945 dl, DAG, AsmNodeOperands); 8946 break; 8947 } 8948 case InlineAsm::isClobber: 8949 // Add the clobbered value to the operand list, so that the register 8950 // allocator is aware that the physreg got clobbered. 8951 if (!OpInfo.AssignedRegs.Regs.empty()) 8952 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8953 false, 0, getCurSDLoc(), DAG, 8954 AsmNodeOperands); 8955 break; 8956 } 8957 } 8958 8959 // Finish up input operands. Set the input chain and add the flag last. 8960 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8961 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8962 8963 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8964 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8965 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8966 Flag = Chain.getValue(1); 8967 8968 // Do additional work to generate outputs. 8969 8970 SmallVector<EVT, 1> ResultVTs; 8971 SmallVector<SDValue, 1> ResultValues; 8972 SmallVector<SDValue, 8> OutChains; 8973 8974 llvm::Type *CallResultType = Call.getType(); 8975 ArrayRef<Type *> ResultTypes; 8976 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8977 ResultTypes = StructResult->elements(); 8978 else if (!CallResultType->isVoidTy()) 8979 ResultTypes = makeArrayRef(CallResultType); 8980 8981 auto CurResultType = ResultTypes.begin(); 8982 auto handleRegAssign = [&](SDValue V) { 8983 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8984 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8985 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8986 ++CurResultType; 8987 // If the type of the inline asm call site return value is different but has 8988 // same size as the type of the asm output bitcast it. One example of this 8989 // is for vectors with different width / number of elements. This can 8990 // happen for register classes that can contain multiple different value 8991 // types. The preg or vreg allocated may not have the same VT as was 8992 // expected. 8993 // 8994 // This can also happen for a return value that disagrees with the register 8995 // class it is put in, eg. a double in a general-purpose register on a 8996 // 32-bit machine. 8997 if (ResultVT != V.getValueType() && 8998 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8999 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9000 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9001 V.getValueType().isInteger()) { 9002 // If a result value was tied to an input value, the computed result 9003 // may have a wider width than the expected result. Extract the 9004 // relevant portion. 9005 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9006 } 9007 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9008 ResultVTs.push_back(ResultVT); 9009 ResultValues.push_back(V); 9010 }; 9011 9012 // Deal with output operands. 9013 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9014 if (OpInfo.Type == InlineAsm::isOutput) { 9015 SDValue Val; 9016 // Skip trivial output operands. 9017 if (OpInfo.AssignedRegs.Regs.empty()) 9018 continue; 9019 9020 switch (OpInfo.ConstraintType) { 9021 case TargetLowering::C_Register: 9022 case TargetLowering::C_RegisterClass: 9023 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9024 Chain, &Flag, &Call); 9025 break; 9026 case TargetLowering::C_Immediate: 9027 case TargetLowering::C_Other: 9028 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9029 OpInfo, DAG); 9030 break; 9031 case TargetLowering::C_Memory: 9032 break; // Already handled. 9033 case TargetLowering::C_Unknown: 9034 assert(false && "Unexpected unknown constraint"); 9035 } 9036 9037 // Indirect output manifest as stores. Record output chains. 9038 if (OpInfo.isIndirect) { 9039 const Value *Ptr = OpInfo.CallOperandVal; 9040 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9041 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9042 MachinePointerInfo(Ptr)); 9043 OutChains.push_back(Store); 9044 } else { 9045 // generate CopyFromRegs to associated registers. 9046 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9047 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9048 for (const SDValue &V : Val->op_values()) 9049 handleRegAssign(V); 9050 } else 9051 handleRegAssign(Val); 9052 } 9053 } 9054 } 9055 9056 // Set results. 9057 if (!ResultValues.empty()) { 9058 assert(CurResultType == ResultTypes.end() && 9059 "Mismatch in number of ResultTypes"); 9060 assert(ResultValues.size() == ResultTypes.size() && 9061 "Mismatch in number of output operands in asm result"); 9062 9063 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9064 DAG.getVTList(ResultVTs), ResultValues); 9065 setValue(&Call, V); 9066 } 9067 9068 // Collect store chains. 9069 if (!OutChains.empty()) 9070 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9071 9072 if (EmitEHLabels) { 9073 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9074 } 9075 9076 // Only Update Root if inline assembly has a memory effect. 9077 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9078 EmitEHLabels) 9079 DAG.setRoot(Chain); 9080 } 9081 9082 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9083 const Twine &Message) { 9084 LLVMContext &Ctx = *DAG.getContext(); 9085 Ctx.emitError(&Call, Message); 9086 9087 // Make sure we leave the DAG in a valid state 9088 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9089 SmallVector<EVT, 1> ValueVTs; 9090 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9091 9092 if (ValueVTs.empty()) 9093 return; 9094 9095 SmallVector<SDValue, 1> Ops; 9096 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9097 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9098 9099 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9100 } 9101 9102 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9103 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9104 MVT::Other, getRoot(), 9105 getValue(I.getArgOperand(0)), 9106 DAG.getSrcValue(I.getArgOperand(0)))); 9107 } 9108 9109 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9110 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9111 const DataLayout &DL = DAG.getDataLayout(); 9112 SDValue V = DAG.getVAArg( 9113 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9114 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9115 DL.getABITypeAlign(I.getType()).value()); 9116 DAG.setRoot(V.getValue(1)); 9117 9118 if (I.getType()->isPointerTy()) 9119 V = DAG.getPtrExtOrTrunc( 9120 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9121 setValue(&I, V); 9122 } 9123 9124 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9125 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9126 MVT::Other, getRoot(), 9127 getValue(I.getArgOperand(0)), 9128 DAG.getSrcValue(I.getArgOperand(0)))); 9129 } 9130 9131 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9132 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9133 MVT::Other, getRoot(), 9134 getValue(I.getArgOperand(0)), 9135 getValue(I.getArgOperand(1)), 9136 DAG.getSrcValue(I.getArgOperand(0)), 9137 DAG.getSrcValue(I.getArgOperand(1)))); 9138 } 9139 9140 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9141 const Instruction &I, 9142 SDValue Op) { 9143 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9144 if (!Range) 9145 return Op; 9146 9147 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9148 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9149 return Op; 9150 9151 APInt Lo = CR.getUnsignedMin(); 9152 if (!Lo.isMinValue()) 9153 return Op; 9154 9155 APInt Hi = CR.getUnsignedMax(); 9156 unsigned Bits = std::max(Hi.getActiveBits(), 9157 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9158 9159 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9160 9161 SDLoc SL = getCurSDLoc(); 9162 9163 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9164 DAG.getValueType(SmallVT)); 9165 unsigned NumVals = Op.getNode()->getNumValues(); 9166 if (NumVals == 1) 9167 return ZExt; 9168 9169 SmallVector<SDValue, 4> Ops; 9170 9171 Ops.push_back(ZExt); 9172 for (unsigned I = 1; I != NumVals; ++I) 9173 Ops.push_back(Op.getValue(I)); 9174 9175 return DAG.getMergeValues(Ops, SL); 9176 } 9177 9178 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9179 /// the call being lowered. 9180 /// 9181 /// This is a helper for lowering intrinsics that follow a target calling 9182 /// convention or require stack pointer adjustment. Only a subset of the 9183 /// intrinsic's operands need to participate in the calling convention. 9184 void SelectionDAGBuilder::populateCallLoweringInfo( 9185 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9186 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9187 bool IsPatchPoint) { 9188 TargetLowering::ArgListTy Args; 9189 Args.reserve(NumArgs); 9190 9191 // Populate the argument list. 9192 // Attributes for args start at offset 1, after the return attribute. 9193 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9194 ArgI != ArgE; ++ArgI) { 9195 const Value *V = Call->getOperand(ArgI); 9196 9197 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9198 9199 TargetLowering::ArgListEntry Entry; 9200 Entry.Node = getValue(V); 9201 Entry.Ty = V->getType(); 9202 Entry.setAttributes(Call, ArgI); 9203 Args.push_back(Entry); 9204 } 9205 9206 CLI.setDebugLoc(getCurSDLoc()) 9207 .setChain(getRoot()) 9208 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9209 .setDiscardResult(Call->use_empty()) 9210 .setIsPatchPoint(IsPatchPoint) 9211 .setIsPreallocated( 9212 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9213 } 9214 9215 /// Add a stack map intrinsic call's live variable operands to a stackmap 9216 /// or patchpoint target node's operand list. 9217 /// 9218 /// Constants are converted to TargetConstants purely as an optimization to 9219 /// avoid constant materialization and register allocation. 9220 /// 9221 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9222 /// generate addess computation nodes, and so FinalizeISel can convert the 9223 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9224 /// address materialization and register allocation, but may also be required 9225 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9226 /// alloca in the entry block, then the runtime may assume that the alloca's 9227 /// StackMap location can be read immediately after compilation and that the 9228 /// location is valid at any point during execution (this is similar to the 9229 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9230 /// only available in a register, then the runtime would need to trap when 9231 /// execution reaches the StackMap in order to read the alloca's location. 9232 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9233 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9234 SelectionDAGBuilder &Builder) { 9235 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 9236 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 9237 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 9238 Ops.push_back( 9239 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 9240 Ops.push_back( 9241 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 9242 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 9243 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 9244 Ops.push_back(Builder.DAG.getTargetFrameIndex( 9245 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 9246 } else 9247 Ops.push_back(OpVal); 9248 } 9249 } 9250 9251 /// Lower llvm.experimental.stackmap directly to its target opcode. 9252 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9253 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 9254 // [live variables...]) 9255 9256 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9257 9258 SDValue Chain, InFlag, Callee, NullPtr; 9259 SmallVector<SDValue, 32> Ops; 9260 9261 SDLoc DL = getCurSDLoc(); 9262 Callee = getValue(CI.getCalledOperand()); 9263 NullPtr = DAG.getIntPtrConstant(0, DL, true); 9264 9265 // The stackmap intrinsic only records the live variables (the arguments 9266 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9267 // intrinsic, this won't be lowered to a function call. This means we don't 9268 // have to worry about calling conventions and target specific lowering code. 9269 // Instead we perform the call lowering right here. 9270 // 9271 // chain, flag = CALLSEQ_START(chain, 0, 0) 9272 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9273 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9274 // 9275 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9276 InFlag = Chain.getValue(1); 9277 9278 // Add the <id> and <numBytes> constants. 9279 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9280 Ops.push_back(DAG.getTargetConstant( 9281 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9282 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9283 Ops.push_back(DAG.getTargetConstant( 9284 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9285 MVT::i32)); 9286 9287 // Push live variables for the stack map. 9288 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9289 9290 // We are not pushing any register mask info here on the operands list, 9291 // because the stackmap doesn't clobber anything. 9292 9293 // Push the chain and the glue flag. 9294 Ops.push_back(Chain); 9295 Ops.push_back(InFlag); 9296 9297 // Create the STACKMAP node. 9298 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9299 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9300 Chain = SDValue(SM, 0); 9301 InFlag = Chain.getValue(1); 9302 9303 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9304 9305 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9306 9307 // Set the root to the target-lowered call chain. 9308 DAG.setRoot(Chain); 9309 9310 // Inform the Frame Information that we have a stackmap in this function. 9311 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9312 } 9313 9314 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9315 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9316 const BasicBlock *EHPadBB) { 9317 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9318 // i32 <numBytes>, 9319 // i8* <target>, 9320 // i32 <numArgs>, 9321 // [Args...], 9322 // [live variables...]) 9323 9324 CallingConv::ID CC = CB.getCallingConv(); 9325 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9326 bool HasDef = !CB.getType()->isVoidTy(); 9327 SDLoc dl = getCurSDLoc(); 9328 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9329 9330 // Handle immediate and symbolic callees. 9331 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9332 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9333 /*isTarget=*/true); 9334 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9335 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9336 SDLoc(SymbolicCallee), 9337 SymbolicCallee->getValueType(0)); 9338 9339 // Get the real number of arguments participating in the call <numArgs> 9340 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9341 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9342 9343 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9344 // Intrinsics include all meta-operands up to but not including CC. 9345 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9346 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9347 "Not enough arguments provided to the patchpoint intrinsic"); 9348 9349 // For AnyRegCC the arguments are lowered later on manually. 9350 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9351 Type *ReturnTy = 9352 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9353 9354 TargetLowering::CallLoweringInfo CLI(DAG); 9355 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9356 ReturnTy, true); 9357 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9358 9359 SDNode *CallEnd = Result.second.getNode(); 9360 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9361 CallEnd = CallEnd->getOperand(0).getNode(); 9362 9363 /// Get a call instruction from the call sequence chain. 9364 /// Tail calls are not allowed. 9365 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9366 "Expected a callseq node."); 9367 SDNode *Call = CallEnd->getOperand(0).getNode(); 9368 bool HasGlue = Call->getGluedNode(); 9369 9370 // Replace the target specific call node with the patchable intrinsic. 9371 SmallVector<SDValue, 8> Ops; 9372 9373 // Add the <id> and <numBytes> constants. 9374 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9375 Ops.push_back(DAG.getTargetConstant( 9376 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9377 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9378 Ops.push_back(DAG.getTargetConstant( 9379 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9380 MVT::i32)); 9381 9382 // Add the callee. 9383 Ops.push_back(Callee); 9384 9385 // Adjust <numArgs> to account for any arguments that have been passed on the 9386 // stack instead. 9387 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9388 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9389 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9390 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9391 9392 // Add the calling convention 9393 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9394 9395 // Add the arguments we omitted previously. The register allocator should 9396 // place these in any free register. 9397 if (IsAnyRegCC) 9398 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9399 Ops.push_back(getValue(CB.getArgOperand(i))); 9400 9401 // Push the arguments from the call instruction up to the register mask. 9402 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9403 Ops.append(Call->op_begin() + 2, e); 9404 9405 // Push live variables for the stack map. 9406 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9407 9408 // Push the register mask info. 9409 if (HasGlue) 9410 Ops.push_back(*(Call->op_end()-2)); 9411 else 9412 Ops.push_back(*(Call->op_end()-1)); 9413 9414 // Push the chain (this is originally the first operand of the call, but 9415 // becomes now the last or second to last operand). 9416 Ops.push_back(*(Call->op_begin())); 9417 9418 // Push the glue flag (last operand). 9419 if (HasGlue) 9420 Ops.push_back(*(Call->op_end()-1)); 9421 9422 SDVTList NodeTys; 9423 if (IsAnyRegCC && HasDef) { 9424 // Create the return types based on the intrinsic definition 9425 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9426 SmallVector<EVT, 3> ValueVTs; 9427 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9428 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9429 9430 // There is always a chain and a glue type at the end 9431 ValueVTs.push_back(MVT::Other); 9432 ValueVTs.push_back(MVT::Glue); 9433 NodeTys = DAG.getVTList(ValueVTs); 9434 } else 9435 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9436 9437 // Replace the target specific call node with a PATCHPOINT node. 9438 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9439 dl, NodeTys, Ops); 9440 9441 // Update the NodeMap. 9442 if (HasDef) { 9443 if (IsAnyRegCC) 9444 setValue(&CB, SDValue(MN, 0)); 9445 else 9446 setValue(&CB, Result.first); 9447 } 9448 9449 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9450 // call sequence. Furthermore the location of the chain and glue can change 9451 // when the AnyReg calling convention is used and the intrinsic returns a 9452 // value. 9453 if (IsAnyRegCC && HasDef) { 9454 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9455 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9456 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9457 } else 9458 DAG.ReplaceAllUsesWith(Call, MN); 9459 DAG.DeleteNode(Call); 9460 9461 // Inform the Frame Information that we have a patchpoint in this function. 9462 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9463 } 9464 9465 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9466 unsigned Intrinsic) { 9467 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9468 SDValue Op1 = getValue(I.getArgOperand(0)); 9469 SDValue Op2; 9470 if (I.arg_size() > 1) 9471 Op2 = getValue(I.getArgOperand(1)); 9472 SDLoc dl = getCurSDLoc(); 9473 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9474 SDValue Res; 9475 SDNodeFlags SDFlags; 9476 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9477 SDFlags.copyFMF(*FPMO); 9478 9479 switch (Intrinsic) { 9480 case Intrinsic::vector_reduce_fadd: 9481 if (SDFlags.hasAllowReassociation()) 9482 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9483 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9484 SDFlags); 9485 else 9486 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9487 break; 9488 case Intrinsic::vector_reduce_fmul: 9489 if (SDFlags.hasAllowReassociation()) 9490 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9491 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9492 SDFlags); 9493 else 9494 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9495 break; 9496 case Intrinsic::vector_reduce_add: 9497 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9498 break; 9499 case Intrinsic::vector_reduce_mul: 9500 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9501 break; 9502 case Intrinsic::vector_reduce_and: 9503 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9504 break; 9505 case Intrinsic::vector_reduce_or: 9506 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9507 break; 9508 case Intrinsic::vector_reduce_xor: 9509 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9510 break; 9511 case Intrinsic::vector_reduce_smax: 9512 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9513 break; 9514 case Intrinsic::vector_reduce_smin: 9515 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9516 break; 9517 case Intrinsic::vector_reduce_umax: 9518 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9519 break; 9520 case Intrinsic::vector_reduce_umin: 9521 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9522 break; 9523 case Intrinsic::vector_reduce_fmax: 9524 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9525 break; 9526 case Intrinsic::vector_reduce_fmin: 9527 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9528 break; 9529 default: 9530 llvm_unreachable("Unhandled vector reduce intrinsic"); 9531 } 9532 setValue(&I, Res); 9533 } 9534 9535 /// Returns an AttributeList representing the attributes applied to the return 9536 /// value of the given call. 9537 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9538 SmallVector<Attribute::AttrKind, 2> Attrs; 9539 if (CLI.RetSExt) 9540 Attrs.push_back(Attribute::SExt); 9541 if (CLI.RetZExt) 9542 Attrs.push_back(Attribute::ZExt); 9543 if (CLI.IsInReg) 9544 Attrs.push_back(Attribute::InReg); 9545 9546 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9547 Attrs); 9548 } 9549 9550 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9551 /// implementation, which just calls LowerCall. 9552 /// FIXME: When all targets are 9553 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9554 std::pair<SDValue, SDValue> 9555 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9556 // Handle the incoming return values from the call. 9557 CLI.Ins.clear(); 9558 Type *OrigRetTy = CLI.RetTy; 9559 SmallVector<EVT, 4> RetTys; 9560 SmallVector<uint64_t, 4> Offsets; 9561 auto &DL = CLI.DAG.getDataLayout(); 9562 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9563 9564 if (CLI.IsPostTypeLegalization) { 9565 // If we are lowering a libcall after legalization, split the return type. 9566 SmallVector<EVT, 4> OldRetTys; 9567 SmallVector<uint64_t, 4> OldOffsets; 9568 RetTys.swap(OldRetTys); 9569 Offsets.swap(OldOffsets); 9570 9571 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9572 EVT RetVT = OldRetTys[i]; 9573 uint64_t Offset = OldOffsets[i]; 9574 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9575 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9576 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9577 RetTys.append(NumRegs, RegisterVT); 9578 for (unsigned j = 0; j != NumRegs; ++j) 9579 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9580 } 9581 } 9582 9583 SmallVector<ISD::OutputArg, 4> Outs; 9584 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9585 9586 bool CanLowerReturn = 9587 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9588 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9589 9590 SDValue DemoteStackSlot; 9591 int DemoteStackIdx = -100; 9592 if (!CanLowerReturn) { 9593 // FIXME: equivalent assert? 9594 // assert(!CS.hasInAllocaArgument() && 9595 // "sret demotion is incompatible with inalloca"); 9596 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9597 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9598 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9599 DemoteStackIdx = 9600 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9601 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9602 DL.getAllocaAddrSpace()); 9603 9604 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9605 ArgListEntry Entry; 9606 Entry.Node = DemoteStackSlot; 9607 Entry.Ty = StackSlotPtrType; 9608 Entry.IsSExt = false; 9609 Entry.IsZExt = false; 9610 Entry.IsInReg = false; 9611 Entry.IsSRet = true; 9612 Entry.IsNest = false; 9613 Entry.IsByVal = false; 9614 Entry.IsByRef = false; 9615 Entry.IsReturned = false; 9616 Entry.IsSwiftSelf = false; 9617 Entry.IsSwiftAsync = false; 9618 Entry.IsSwiftError = false; 9619 Entry.IsCFGuardTarget = false; 9620 Entry.Alignment = Alignment; 9621 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9622 CLI.NumFixedArgs += 1; 9623 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9624 9625 // sret demotion isn't compatible with tail-calls, since the sret argument 9626 // points into the callers stack frame. 9627 CLI.IsTailCall = false; 9628 } else { 9629 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9630 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9631 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9632 ISD::ArgFlagsTy Flags; 9633 if (NeedsRegBlock) { 9634 Flags.setInConsecutiveRegs(); 9635 if (I == RetTys.size() - 1) 9636 Flags.setInConsecutiveRegsLast(); 9637 } 9638 EVT VT = RetTys[I]; 9639 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9640 CLI.CallConv, VT); 9641 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9642 CLI.CallConv, VT); 9643 for (unsigned i = 0; i != NumRegs; ++i) { 9644 ISD::InputArg MyFlags; 9645 MyFlags.Flags = Flags; 9646 MyFlags.VT = RegisterVT; 9647 MyFlags.ArgVT = VT; 9648 MyFlags.Used = CLI.IsReturnValueUsed; 9649 if (CLI.RetTy->isPointerTy()) { 9650 MyFlags.Flags.setPointer(); 9651 MyFlags.Flags.setPointerAddrSpace( 9652 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9653 } 9654 if (CLI.RetSExt) 9655 MyFlags.Flags.setSExt(); 9656 if (CLI.RetZExt) 9657 MyFlags.Flags.setZExt(); 9658 if (CLI.IsInReg) 9659 MyFlags.Flags.setInReg(); 9660 CLI.Ins.push_back(MyFlags); 9661 } 9662 } 9663 } 9664 9665 // We push in swifterror return as the last element of CLI.Ins. 9666 ArgListTy &Args = CLI.getArgs(); 9667 if (supportSwiftError()) { 9668 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9669 if (Args[i].IsSwiftError) { 9670 ISD::InputArg MyFlags; 9671 MyFlags.VT = getPointerTy(DL); 9672 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9673 MyFlags.Flags.setSwiftError(); 9674 CLI.Ins.push_back(MyFlags); 9675 } 9676 } 9677 } 9678 9679 // Handle all of the outgoing arguments. 9680 CLI.Outs.clear(); 9681 CLI.OutVals.clear(); 9682 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9683 SmallVector<EVT, 4> ValueVTs; 9684 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9685 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9686 Type *FinalType = Args[i].Ty; 9687 if (Args[i].IsByVal) 9688 FinalType = Args[i].IndirectType; 9689 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9690 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9691 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9692 ++Value) { 9693 EVT VT = ValueVTs[Value]; 9694 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9695 SDValue Op = SDValue(Args[i].Node.getNode(), 9696 Args[i].Node.getResNo() + Value); 9697 ISD::ArgFlagsTy Flags; 9698 9699 // Certain targets (such as MIPS), may have a different ABI alignment 9700 // for a type depending on the context. Give the target a chance to 9701 // specify the alignment it wants. 9702 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9703 Flags.setOrigAlign(OriginalAlignment); 9704 9705 if (Args[i].Ty->isPointerTy()) { 9706 Flags.setPointer(); 9707 Flags.setPointerAddrSpace( 9708 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9709 } 9710 if (Args[i].IsZExt) 9711 Flags.setZExt(); 9712 if (Args[i].IsSExt) 9713 Flags.setSExt(); 9714 if (Args[i].IsInReg) { 9715 // If we are using vectorcall calling convention, a structure that is 9716 // passed InReg - is surely an HVA 9717 if (CLI.CallConv == CallingConv::X86_VectorCall && 9718 isa<StructType>(FinalType)) { 9719 // The first value of a structure is marked 9720 if (0 == Value) 9721 Flags.setHvaStart(); 9722 Flags.setHva(); 9723 } 9724 // Set InReg Flag 9725 Flags.setInReg(); 9726 } 9727 if (Args[i].IsSRet) 9728 Flags.setSRet(); 9729 if (Args[i].IsSwiftSelf) 9730 Flags.setSwiftSelf(); 9731 if (Args[i].IsSwiftAsync) 9732 Flags.setSwiftAsync(); 9733 if (Args[i].IsSwiftError) 9734 Flags.setSwiftError(); 9735 if (Args[i].IsCFGuardTarget) 9736 Flags.setCFGuardTarget(); 9737 if (Args[i].IsByVal) 9738 Flags.setByVal(); 9739 if (Args[i].IsByRef) 9740 Flags.setByRef(); 9741 if (Args[i].IsPreallocated) { 9742 Flags.setPreallocated(); 9743 // Set the byval flag for CCAssignFn callbacks that don't know about 9744 // preallocated. This way we can know how many bytes we should've 9745 // allocated and how many bytes a callee cleanup function will pop. If 9746 // we port preallocated to more targets, we'll have to add custom 9747 // preallocated handling in the various CC lowering callbacks. 9748 Flags.setByVal(); 9749 } 9750 if (Args[i].IsInAlloca) { 9751 Flags.setInAlloca(); 9752 // Set the byval flag for CCAssignFn callbacks that don't know about 9753 // inalloca. This way we can know how many bytes we should've allocated 9754 // and how many bytes a callee cleanup function will pop. If we port 9755 // inalloca to more targets, we'll have to add custom inalloca handling 9756 // in the various CC lowering callbacks. 9757 Flags.setByVal(); 9758 } 9759 Align MemAlign; 9760 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9761 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 9762 Flags.setByValSize(FrameSize); 9763 9764 // info is not there but there are cases it cannot get right. 9765 if (auto MA = Args[i].Alignment) 9766 MemAlign = *MA; 9767 else 9768 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 9769 } else if (auto MA = Args[i].Alignment) { 9770 MemAlign = *MA; 9771 } else { 9772 MemAlign = OriginalAlignment; 9773 } 9774 Flags.setMemAlign(MemAlign); 9775 if (Args[i].IsNest) 9776 Flags.setNest(); 9777 if (NeedsRegBlock) 9778 Flags.setInConsecutiveRegs(); 9779 9780 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9781 CLI.CallConv, VT); 9782 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9783 CLI.CallConv, VT); 9784 SmallVector<SDValue, 4> Parts(NumParts); 9785 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9786 9787 if (Args[i].IsSExt) 9788 ExtendKind = ISD::SIGN_EXTEND; 9789 else if (Args[i].IsZExt) 9790 ExtendKind = ISD::ZERO_EXTEND; 9791 9792 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9793 // for now. 9794 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9795 CanLowerReturn) { 9796 assert((CLI.RetTy == Args[i].Ty || 9797 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9798 CLI.RetTy->getPointerAddressSpace() == 9799 Args[i].Ty->getPointerAddressSpace())) && 9800 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9801 // Before passing 'returned' to the target lowering code, ensure that 9802 // either the register MVT and the actual EVT are the same size or that 9803 // the return value and argument are extended in the same way; in these 9804 // cases it's safe to pass the argument register value unchanged as the 9805 // return register value (although it's at the target's option whether 9806 // to do so) 9807 // TODO: allow code generation to take advantage of partially preserved 9808 // registers rather than clobbering the entire register when the 9809 // parameter extension method is not compatible with the return 9810 // extension method 9811 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9812 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9813 CLI.RetZExt == Args[i].IsZExt)) 9814 Flags.setReturned(); 9815 } 9816 9817 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9818 CLI.CallConv, ExtendKind); 9819 9820 for (unsigned j = 0; j != NumParts; ++j) { 9821 // if it isn't first piece, alignment must be 1 9822 // For scalable vectors the scalable part is currently handled 9823 // by individual targets, so we just use the known minimum size here. 9824 ISD::OutputArg MyFlags( 9825 Flags, Parts[j].getValueType().getSimpleVT(), VT, 9826 i < CLI.NumFixedArgs, i, 9827 j * Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9828 if (NumParts > 1 && j == 0) 9829 MyFlags.Flags.setSplit(); 9830 else if (j != 0) { 9831 MyFlags.Flags.setOrigAlign(Align(1)); 9832 if (j == NumParts - 1) 9833 MyFlags.Flags.setSplitEnd(); 9834 } 9835 9836 CLI.Outs.push_back(MyFlags); 9837 CLI.OutVals.push_back(Parts[j]); 9838 } 9839 9840 if (NeedsRegBlock && Value == NumValues - 1) 9841 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9842 } 9843 } 9844 9845 SmallVector<SDValue, 4> InVals; 9846 CLI.Chain = LowerCall(CLI, InVals); 9847 9848 // Update CLI.InVals to use outside of this function. 9849 CLI.InVals = InVals; 9850 9851 // Verify that the target's LowerCall behaved as expected. 9852 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9853 "LowerCall didn't return a valid chain!"); 9854 assert((!CLI.IsTailCall || InVals.empty()) && 9855 "LowerCall emitted a return value for a tail call!"); 9856 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9857 "LowerCall didn't emit the correct number of values!"); 9858 9859 // For a tail call, the return value is merely live-out and there aren't 9860 // any nodes in the DAG representing it. Return a special value to 9861 // indicate that a tail call has been emitted and no more Instructions 9862 // should be processed in the current block. 9863 if (CLI.IsTailCall) { 9864 CLI.DAG.setRoot(CLI.Chain); 9865 return std::make_pair(SDValue(), SDValue()); 9866 } 9867 9868 #ifndef NDEBUG 9869 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9870 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9871 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9872 "LowerCall emitted a value with the wrong type!"); 9873 } 9874 #endif 9875 9876 SmallVector<SDValue, 4> ReturnValues; 9877 if (!CanLowerReturn) { 9878 // The instruction result is the result of loading from the 9879 // hidden sret parameter. 9880 SmallVector<EVT, 1> PVTs; 9881 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9882 9883 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9884 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9885 EVT PtrVT = PVTs[0]; 9886 9887 unsigned NumValues = RetTys.size(); 9888 ReturnValues.resize(NumValues); 9889 SmallVector<SDValue, 4> Chains(NumValues); 9890 9891 // An aggregate return value cannot wrap around the address space, so 9892 // offsets to its parts don't wrap either. 9893 SDNodeFlags Flags; 9894 Flags.setNoUnsignedWrap(true); 9895 9896 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9897 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9898 for (unsigned i = 0; i < NumValues; ++i) { 9899 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9900 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9901 PtrVT), Flags); 9902 SDValue L = CLI.DAG.getLoad( 9903 RetTys[i], CLI.DL, CLI.Chain, Add, 9904 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9905 DemoteStackIdx, Offsets[i]), 9906 HiddenSRetAlign); 9907 ReturnValues[i] = L; 9908 Chains[i] = L.getValue(1); 9909 } 9910 9911 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9912 } else { 9913 // Collect the legal value parts into potentially illegal values 9914 // that correspond to the original function's return values. 9915 Optional<ISD::NodeType> AssertOp; 9916 if (CLI.RetSExt) 9917 AssertOp = ISD::AssertSext; 9918 else if (CLI.RetZExt) 9919 AssertOp = ISD::AssertZext; 9920 unsigned CurReg = 0; 9921 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9922 EVT VT = RetTys[I]; 9923 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9924 CLI.CallConv, VT); 9925 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9926 CLI.CallConv, VT); 9927 9928 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9929 NumRegs, RegisterVT, VT, nullptr, 9930 CLI.CallConv, AssertOp)); 9931 CurReg += NumRegs; 9932 } 9933 9934 // For a function returning void, there is no return value. We can't create 9935 // such a node, so we just return a null return value in that case. In 9936 // that case, nothing will actually look at the value. 9937 if (ReturnValues.empty()) 9938 return std::make_pair(SDValue(), CLI.Chain); 9939 } 9940 9941 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9942 CLI.DAG.getVTList(RetTys), ReturnValues); 9943 return std::make_pair(Res, CLI.Chain); 9944 } 9945 9946 /// Places new result values for the node in Results (their number 9947 /// and types must exactly match those of the original return values of 9948 /// the node), or leaves Results empty, which indicates that the node is not 9949 /// to be custom lowered after all. 9950 void TargetLowering::LowerOperationWrapper(SDNode *N, 9951 SmallVectorImpl<SDValue> &Results, 9952 SelectionDAG &DAG) const { 9953 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9954 9955 if (!Res.getNode()) 9956 return; 9957 9958 // If the original node has one result, take the return value from 9959 // LowerOperation as is. It might not be result number 0. 9960 if (N->getNumValues() == 1) { 9961 Results.push_back(Res); 9962 return; 9963 } 9964 9965 // If the original node has multiple results, then the return node should 9966 // have the same number of results. 9967 assert((N->getNumValues() == Res->getNumValues()) && 9968 "Lowering returned the wrong number of results!"); 9969 9970 // Places new result values base on N result number. 9971 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9972 Results.push_back(Res.getValue(I)); 9973 } 9974 9975 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9976 llvm_unreachable("LowerOperation not implemented for this target!"); 9977 } 9978 9979 void 9980 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9981 SDValue Op = getNonRegisterValue(V); 9982 assert((Op.getOpcode() != ISD::CopyFromReg || 9983 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9984 "Copy from a reg to the same reg!"); 9985 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9986 9987 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9988 // If this is an InlineAsm we have to match the registers required, not the 9989 // notional registers required by the type. 9990 9991 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9992 None); // This is not an ABI copy. 9993 SDValue Chain = DAG.getEntryNode(); 9994 9995 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 9996 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 9997 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 9998 ExtendType = PreferredExtendIt->second; 9999 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10000 PendingExports.push_back(Chain); 10001 } 10002 10003 #include "llvm/CodeGen/SelectionDAGISel.h" 10004 10005 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10006 /// entry block, return true. This includes arguments used by switches, since 10007 /// the switch may expand into multiple basic blocks. 10008 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10009 // With FastISel active, we may be splitting blocks, so force creation 10010 // of virtual registers for all non-dead arguments. 10011 if (FastISel) 10012 return A->use_empty(); 10013 10014 const BasicBlock &Entry = A->getParent()->front(); 10015 for (const User *U : A->users()) 10016 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10017 return false; // Use not in entry block. 10018 10019 return true; 10020 } 10021 10022 using ArgCopyElisionMapTy = 10023 DenseMap<const Argument *, 10024 std::pair<const AllocaInst *, const StoreInst *>>; 10025 10026 /// Scan the entry block of the function in FuncInfo for arguments that look 10027 /// like copies into a local alloca. Record any copied arguments in 10028 /// ArgCopyElisionCandidates. 10029 static void 10030 findArgumentCopyElisionCandidates(const DataLayout &DL, 10031 FunctionLoweringInfo *FuncInfo, 10032 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10033 // Record the state of every static alloca used in the entry block. Argument 10034 // allocas are all used in the entry block, so we need approximately as many 10035 // entries as we have arguments. 10036 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10037 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10038 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10039 StaticAllocas.reserve(NumArgs * 2); 10040 10041 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10042 if (!V) 10043 return nullptr; 10044 V = V->stripPointerCasts(); 10045 const auto *AI = dyn_cast<AllocaInst>(V); 10046 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10047 return nullptr; 10048 auto Iter = StaticAllocas.insert({AI, Unknown}); 10049 return &Iter.first->second; 10050 }; 10051 10052 // Look for stores of arguments to static allocas. Look through bitcasts and 10053 // GEPs to handle type coercions, as long as the alloca is fully initialized 10054 // by the store. Any non-store use of an alloca escapes it and any subsequent 10055 // unanalyzed store might write it. 10056 // FIXME: Handle structs initialized with multiple stores. 10057 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10058 // Look for stores, and handle non-store uses conservatively. 10059 const auto *SI = dyn_cast<StoreInst>(&I); 10060 if (!SI) { 10061 // We will look through cast uses, so ignore them completely. 10062 if (I.isCast()) 10063 continue; 10064 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10065 // to allocas. 10066 if (I.isDebugOrPseudoInst()) 10067 continue; 10068 // This is an unknown instruction. Assume it escapes or writes to all 10069 // static alloca operands. 10070 for (const Use &U : I.operands()) { 10071 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10072 *Info = StaticAllocaInfo::Clobbered; 10073 } 10074 continue; 10075 } 10076 10077 // If the stored value is a static alloca, mark it as escaped. 10078 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10079 *Info = StaticAllocaInfo::Clobbered; 10080 10081 // Check if the destination is a static alloca. 10082 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10083 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10084 if (!Info) 10085 continue; 10086 const AllocaInst *AI = cast<AllocaInst>(Dst); 10087 10088 // Skip allocas that have been initialized or clobbered. 10089 if (*Info != StaticAllocaInfo::Unknown) 10090 continue; 10091 10092 // Check if the stored value is an argument, and that this store fully 10093 // initializes the alloca. 10094 // If the argument type has padding bits we can't directly forward a pointer 10095 // as the upper bits may contain garbage. 10096 // Don't elide copies from the same argument twice. 10097 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10098 const auto *Arg = dyn_cast<Argument>(Val); 10099 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10100 Arg->getType()->isEmptyTy() || 10101 DL.getTypeStoreSize(Arg->getType()) != 10102 DL.getTypeAllocSize(AI->getAllocatedType()) || 10103 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10104 ArgCopyElisionCandidates.count(Arg)) { 10105 *Info = StaticAllocaInfo::Clobbered; 10106 continue; 10107 } 10108 10109 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10110 << '\n'); 10111 10112 // Mark this alloca and store for argument copy elision. 10113 *Info = StaticAllocaInfo::Elidable; 10114 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10115 10116 // Stop scanning if we've seen all arguments. This will happen early in -O0 10117 // builds, which is useful, because -O0 builds have large entry blocks and 10118 // many allocas. 10119 if (ArgCopyElisionCandidates.size() == NumArgs) 10120 break; 10121 } 10122 } 10123 10124 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10125 /// ArgVal is a load from a suitable fixed stack object. 10126 static void tryToElideArgumentCopy( 10127 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10128 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10129 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10130 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10131 SDValue ArgVal, bool &ArgHasUses) { 10132 // Check if this is a load from a fixed stack object. 10133 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10134 if (!LNode) 10135 return; 10136 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10137 if (!FINode) 10138 return; 10139 10140 // Check that the fixed stack object is the right size and alignment. 10141 // Look at the alignment that the user wrote on the alloca instead of looking 10142 // at the stack object. 10143 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10144 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10145 const AllocaInst *AI = ArgCopyIter->second.first; 10146 int FixedIndex = FINode->getIndex(); 10147 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10148 int OldIndex = AllocaIndex; 10149 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10150 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10151 LLVM_DEBUG( 10152 dbgs() << " argument copy elision failed due to bad fixed stack " 10153 "object size\n"); 10154 return; 10155 } 10156 Align RequiredAlignment = AI->getAlign(); 10157 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10158 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10159 "greater than stack argument alignment (" 10160 << DebugStr(RequiredAlignment) << " vs " 10161 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10162 return; 10163 } 10164 10165 // Perform the elision. Delete the old stack object and replace its only use 10166 // in the variable info map. Mark the stack object as mutable. 10167 LLVM_DEBUG({ 10168 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10169 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10170 << '\n'; 10171 }); 10172 MFI.RemoveStackObject(OldIndex); 10173 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10174 AllocaIndex = FixedIndex; 10175 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10176 Chains.push_back(ArgVal.getValue(1)); 10177 10178 // Avoid emitting code for the store implementing the copy. 10179 const StoreInst *SI = ArgCopyIter->second.second; 10180 ElidedArgCopyInstrs.insert(SI); 10181 10182 // Check for uses of the argument again so that we can avoid exporting ArgVal 10183 // if it is't used by anything other than the store. 10184 for (const Value *U : Arg.users()) { 10185 if (U != SI) { 10186 ArgHasUses = true; 10187 break; 10188 } 10189 } 10190 } 10191 10192 void SelectionDAGISel::LowerArguments(const Function &F) { 10193 SelectionDAG &DAG = SDB->DAG; 10194 SDLoc dl = SDB->getCurSDLoc(); 10195 const DataLayout &DL = DAG.getDataLayout(); 10196 SmallVector<ISD::InputArg, 16> Ins; 10197 10198 // In Naked functions we aren't going to save any registers. 10199 if (F.hasFnAttribute(Attribute::Naked)) 10200 return; 10201 10202 if (!FuncInfo->CanLowerReturn) { 10203 // Put in an sret pointer parameter before all the other parameters. 10204 SmallVector<EVT, 1> ValueVTs; 10205 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10206 F.getReturnType()->getPointerTo( 10207 DAG.getDataLayout().getAllocaAddrSpace()), 10208 ValueVTs); 10209 10210 // NOTE: Assuming that a pointer will never break down to more than one VT 10211 // or one register. 10212 ISD::ArgFlagsTy Flags; 10213 Flags.setSRet(); 10214 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10215 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10216 ISD::InputArg::NoArgIndex, 0); 10217 Ins.push_back(RetArg); 10218 } 10219 10220 // Look for stores of arguments to static allocas. Mark such arguments with a 10221 // flag to ask the target to give us the memory location of that argument if 10222 // available. 10223 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10224 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10225 ArgCopyElisionCandidates); 10226 10227 // Set up the incoming argument description vector. 10228 for (const Argument &Arg : F.args()) { 10229 unsigned ArgNo = Arg.getArgNo(); 10230 SmallVector<EVT, 4> ValueVTs; 10231 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10232 bool isArgValueUsed = !Arg.use_empty(); 10233 unsigned PartBase = 0; 10234 Type *FinalType = Arg.getType(); 10235 if (Arg.hasAttribute(Attribute::ByVal)) 10236 FinalType = Arg.getParamByValType(); 10237 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10238 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10239 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10240 Value != NumValues; ++Value) { 10241 EVT VT = ValueVTs[Value]; 10242 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10243 ISD::ArgFlagsTy Flags; 10244 10245 10246 if (Arg.getType()->isPointerTy()) { 10247 Flags.setPointer(); 10248 Flags.setPointerAddrSpace( 10249 cast<PointerType>(Arg.getType())->getAddressSpace()); 10250 } 10251 if (Arg.hasAttribute(Attribute::ZExt)) 10252 Flags.setZExt(); 10253 if (Arg.hasAttribute(Attribute::SExt)) 10254 Flags.setSExt(); 10255 if (Arg.hasAttribute(Attribute::InReg)) { 10256 // If we are using vectorcall calling convention, a structure that is 10257 // passed InReg - is surely an HVA 10258 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10259 isa<StructType>(Arg.getType())) { 10260 // The first value of a structure is marked 10261 if (0 == Value) 10262 Flags.setHvaStart(); 10263 Flags.setHva(); 10264 } 10265 // Set InReg Flag 10266 Flags.setInReg(); 10267 } 10268 if (Arg.hasAttribute(Attribute::StructRet)) 10269 Flags.setSRet(); 10270 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10271 Flags.setSwiftSelf(); 10272 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10273 Flags.setSwiftAsync(); 10274 if (Arg.hasAttribute(Attribute::SwiftError)) 10275 Flags.setSwiftError(); 10276 if (Arg.hasAttribute(Attribute::ByVal)) 10277 Flags.setByVal(); 10278 if (Arg.hasAttribute(Attribute::ByRef)) 10279 Flags.setByRef(); 10280 if (Arg.hasAttribute(Attribute::InAlloca)) { 10281 Flags.setInAlloca(); 10282 // Set the byval flag for CCAssignFn callbacks that don't know about 10283 // inalloca. This way we can know how many bytes we should've allocated 10284 // and how many bytes a callee cleanup function will pop. If we port 10285 // inalloca to more targets, we'll have to add custom inalloca handling 10286 // in the various CC lowering callbacks. 10287 Flags.setByVal(); 10288 } 10289 if (Arg.hasAttribute(Attribute::Preallocated)) { 10290 Flags.setPreallocated(); 10291 // Set the byval flag for CCAssignFn callbacks that don't know about 10292 // preallocated. This way we can know how many bytes we should've 10293 // allocated and how many bytes a callee cleanup function will pop. If 10294 // we port preallocated to more targets, we'll have to add custom 10295 // preallocated handling in the various CC lowering callbacks. 10296 Flags.setByVal(); 10297 } 10298 10299 // Certain targets (such as MIPS), may have a different ABI alignment 10300 // for a type depending on the context. Give the target a chance to 10301 // specify the alignment it wants. 10302 const Align OriginalAlignment( 10303 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10304 Flags.setOrigAlign(OriginalAlignment); 10305 10306 Align MemAlign; 10307 Type *ArgMemTy = nullptr; 10308 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10309 Flags.isByRef()) { 10310 if (!ArgMemTy) 10311 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10312 10313 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10314 10315 // For in-memory arguments, size and alignment should be passed from FE. 10316 // BE will guess if this info is not there but there are cases it cannot 10317 // get right. 10318 if (auto ParamAlign = Arg.getParamStackAlign()) 10319 MemAlign = *ParamAlign; 10320 else if ((ParamAlign = Arg.getParamAlign())) 10321 MemAlign = *ParamAlign; 10322 else 10323 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10324 if (Flags.isByRef()) 10325 Flags.setByRefSize(MemSize); 10326 else 10327 Flags.setByValSize(MemSize); 10328 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10329 MemAlign = *ParamAlign; 10330 } else { 10331 MemAlign = OriginalAlignment; 10332 } 10333 Flags.setMemAlign(MemAlign); 10334 10335 if (Arg.hasAttribute(Attribute::Nest)) 10336 Flags.setNest(); 10337 if (NeedsRegBlock) 10338 Flags.setInConsecutiveRegs(); 10339 if (ArgCopyElisionCandidates.count(&Arg)) 10340 Flags.setCopyElisionCandidate(); 10341 if (Arg.hasAttribute(Attribute::Returned)) 10342 Flags.setReturned(); 10343 10344 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10345 *CurDAG->getContext(), F.getCallingConv(), VT); 10346 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10347 *CurDAG->getContext(), F.getCallingConv(), VT); 10348 for (unsigned i = 0; i != NumRegs; ++i) { 10349 // For scalable vectors, use the minimum size; individual targets 10350 // are responsible for handling scalable vector arguments and 10351 // return values. 10352 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10353 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10354 if (NumRegs > 1 && i == 0) 10355 MyFlags.Flags.setSplit(); 10356 // if it isn't first piece, alignment must be 1 10357 else if (i > 0) { 10358 MyFlags.Flags.setOrigAlign(Align(1)); 10359 if (i == NumRegs - 1) 10360 MyFlags.Flags.setSplitEnd(); 10361 } 10362 Ins.push_back(MyFlags); 10363 } 10364 if (NeedsRegBlock && Value == NumValues - 1) 10365 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10366 PartBase += VT.getStoreSize().getKnownMinSize(); 10367 } 10368 } 10369 10370 // Call the target to set up the argument values. 10371 SmallVector<SDValue, 8> InVals; 10372 SDValue NewRoot = TLI->LowerFormalArguments( 10373 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10374 10375 // Verify that the target's LowerFormalArguments behaved as expected. 10376 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10377 "LowerFormalArguments didn't return a valid chain!"); 10378 assert(InVals.size() == Ins.size() && 10379 "LowerFormalArguments didn't emit the correct number of values!"); 10380 LLVM_DEBUG({ 10381 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10382 assert(InVals[i].getNode() && 10383 "LowerFormalArguments emitted a null value!"); 10384 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10385 "LowerFormalArguments emitted a value with the wrong type!"); 10386 } 10387 }); 10388 10389 // Update the DAG with the new chain value resulting from argument lowering. 10390 DAG.setRoot(NewRoot); 10391 10392 // Set up the argument values. 10393 unsigned i = 0; 10394 if (!FuncInfo->CanLowerReturn) { 10395 // Create a virtual register for the sret pointer, and put in a copy 10396 // from the sret argument into it. 10397 SmallVector<EVT, 1> ValueVTs; 10398 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10399 F.getReturnType()->getPointerTo( 10400 DAG.getDataLayout().getAllocaAddrSpace()), 10401 ValueVTs); 10402 MVT VT = ValueVTs[0].getSimpleVT(); 10403 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10404 Optional<ISD::NodeType> AssertOp = None; 10405 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10406 nullptr, F.getCallingConv(), AssertOp); 10407 10408 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10409 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10410 Register SRetReg = 10411 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10412 FuncInfo->DemoteRegister = SRetReg; 10413 NewRoot = 10414 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10415 DAG.setRoot(NewRoot); 10416 10417 // i indexes lowered arguments. Bump it past the hidden sret argument. 10418 ++i; 10419 } 10420 10421 SmallVector<SDValue, 4> Chains; 10422 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10423 for (const Argument &Arg : F.args()) { 10424 SmallVector<SDValue, 4> ArgValues; 10425 SmallVector<EVT, 4> ValueVTs; 10426 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10427 unsigned NumValues = ValueVTs.size(); 10428 if (NumValues == 0) 10429 continue; 10430 10431 bool ArgHasUses = !Arg.use_empty(); 10432 10433 // Elide the copying store if the target loaded this argument from a 10434 // suitable fixed stack object. 10435 if (Ins[i].Flags.isCopyElisionCandidate()) { 10436 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10437 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10438 InVals[i], ArgHasUses); 10439 } 10440 10441 // If this argument is unused then remember its value. It is used to generate 10442 // debugging information. 10443 bool isSwiftErrorArg = 10444 TLI->supportSwiftError() && 10445 Arg.hasAttribute(Attribute::SwiftError); 10446 if (!ArgHasUses && !isSwiftErrorArg) { 10447 SDB->setUnusedArgValue(&Arg, InVals[i]); 10448 10449 // Also remember any frame index for use in FastISel. 10450 if (FrameIndexSDNode *FI = 10451 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10452 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10453 } 10454 10455 for (unsigned Val = 0; Val != NumValues; ++Val) { 10456 EVT VT = ValueVTs[Val]; 10457 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10458 F.getCallingConv(), VT); 10459 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10460 *CurDAG->getContext(), F.getCallingConv(), VT); 10461 10462 // Even an apparent 'unused' swifterror argument needs to be returned. So 10463 // we do generate a copy for it that can be used on return from the 10464 // function. 10465 if (ArgHasUses || isSwiftErrorArg) { 10466 Optional<ISD::NodeType> AssertOp; 10467 if (Arg.hasAttribute(Attribute::SExt)) 10468 AssertOp = ISD::AssertSext; 10469 else if (Arg.hasAttribute(Attribute::ZExt)) 10470 AssertOp = ISD::AssertZext; 10471 10472 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10473 PartVT, VT, nullptr, 10474 F.getCallingConv(), AssertOp)); 10475 } 10476 10477 i += NumParts; 10478 } 10479 10480 // We don't need to do anything else for unused arguments. 10481 if (ArgValues.empty()) 10482 continue; 10483 10484 // Note down frame index. 10485 if (FrameIndexSDNode *FI = 10486 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10487 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10488 10489 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10490 SDB->getCurSDLoc()); 10491 10492 SDB->setValue(&Arg, Res); 10493 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10494 // We want to associate the argument with the frame index, among 10495 // involved operands, that correspond to the lowest address. The 10496 // getCopyFromParts function, called earlier, is swapping the order of 10497 // the operands to BUILD_PAIR depending on endianness. The result of 10498 // that swapping is that the least significant bits of the argument will 10499 // be in the first operand of the BUILD_PAIR node, and the most 10500 // significant bits will be in the second operand. 10501 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10502 if (LoadSDNode *LNode = 10503 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10504 if (FrameIndexSDNode *FI = 10505 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10506 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10507 } 10508 10509 // Analyses past this point are naive and don't expect an assertion. 10510 if (Res.getOpcode() == ISD::AssertZext) 10511 Res = Res.getOperand(0); 10512 10513 // Update the SwiftErrorVRegDefMap. 10514 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10515 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10516 if (Register::isVirtualRegister(Reg)) 10517 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10518 Reg); 10519 } 10520 10521 // If this argument is live outside of the entry block, insert a copy from 10522 // wherever we got it to the vreg that other BB's will reference it as. 10523 if (Res.getOpcode() == ISD::CopyFromReg) { 10524 // If we can, though, try to skip creating an unnecessary vreg. 10525 // FIXME: This isn't very clean... it would be nice to make this more 10526 // general. 10527 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10528 if (Register::isVirtualRegister(Reg)) { 10529 FuncInfo->ValueMap[&Arg] = Reg; 10530 continue; 10531 } 10532 } 10533 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10534 FuncInfo->InitializeRegForValue(&Arg); 10535 SDB->CopyToExportRegsIfNeeded(&Arg); 10536 } 10537 } 10538 10539 if (!Chains.empty()) { 10540 Chains.push_back(NewRoot); 10541 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10542 } 10543 10544 DAG.setRoot(NewRoot); 10545 10546 assert(i == InVals.size() && "Argument register count mismatch!"); 10547 10548 // If any argument copy elisions occurred and we have debug info, update the 10549 // stale frame indices used in the dbg.declare variable info table. 10550 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10551 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10552 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10553 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10554 if (I != ArgCopyElisionFrameIndexMap.end()) 10555 VI.Slot = I->second; 10556 } 10557 } 10558 10559 // Finally, if the target has anything special to do, allow it to do so. 10560 emitFunctionEntryCode(); 10561 } 10562 10563 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10564 /// ensure constants are generated when needed. Remember the virtual registers 10565 /// that need to be added to the Machine PHI nodes as input. We cannot just 10566 /// directly add them, because expansion might result in multiple MBB's for one 10567 /// BB. As such, the start of the BB might correspond to a different MBB than 10568 /// the end. 10569 void 10570 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10571 const Instruction *TI = LLVMBB->getTerminator(); 10572 10573 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10574 10575 // Check PHI nodes in successors that expect a value to be available from this 10576 // block. 10577 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10578 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10579 if (!isa<PHINode>(SuccBB->begin())) continue; 10580 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10581 10582 // If this terminator has multiple identical successors (common for 10583 // switches), only handle each succ once. 10584 if (!SuccsHandled.insert(SuccMBB).second) 10585 continue; 10586 10587 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10588 10589 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10590 // nodes and Machine PHI nodes, but the incoming operands have not been 10591 // emitted yet. 10592 for (const PHINode &PN : SuccBB->phis()) { 10593 // Ignore dead phi's. 10594 if (PN.use_empty()) 10595 continue; 10596 10597 // Skip empty types 10598 if (PN.getType()->isEmptyTy()) 10599 continue; 10600 10601 unsigned Reg; 10602 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10603 10604 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10605 unsigned &RegOut = ConstantsOut[C]; 10606 if (RegOut == 0) { 10607 RegOut = FuncInfo.CreateRegs(C); 10608 CopyValueToVirtualRegister(C, RegOut); 10609 } 10610 Reg = RegOut; 10611 } else { 10612 DenseMap<const Value *, Register>::iterator I = 10613 FuncInfo.ValueMap.find(PHIOp); 10614 if (I != FuncInfo.ValueMap.end()) 10615 Reg = I->second; 10616 else { 10617 assert(isa<AllocaInst>(PHIOp) && 10618 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10619 "Didn't codegen value into a register!??"); 10620 Reg = FuncInfo.CreateRegs(PHIOp); 10621 CopyValueToVirtualRegister(PHIOp, Reg); 10622 } 10623 } 10624 10625 // Remember that this register needs to added to the machine PHI node as 10626 // the input for this MBB. 10627 SmallVector<EVT, 4> ValueVTs; 10628 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10629 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10630 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10631 EVT VT = ValueVTs[vti]; 10632 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10633 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10634 FuncInfo.PHINodesToUpdate.push_back( 10635 std::make_pair(&*MBBI++, Reg + i)); 10636 Reg += NumRegisters; 10637 } 10638 } 10639 } 10640 10641 ConstantsOut.clear(); 10642 } 10643 10644 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10645 MachineFunction::iterator I(MBB); 10646 if (++I == FuncInfo.MF->end()) 10647 return nullptr; 10648 return &*I; 10649 } 10650 10651 /// During lowering new call nodes can be created (such as memset, etc.). 10652 /// Those will become new roots of the current DAG, but complications arise 10653 /// when they are tail calls. In such cases, the call lowering will update 10654 /// the root, but the builder still needs to know that a tail call has been 10655 /// lowered in order to avoid generating an additional return. 10656 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10657 // If the node is null, we do have a tail call. 10658 if (MaybeTC.getNode() != nullptr) 10659 DAG.setRoot(MaybeTC); 10660 else 10661 HasTailCall = true; 10662 } 10663 10664 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10665 MachineBasicBlock *SwitchMBB, 10666 MachineBasicBlock *DefaultMBB) { 10667 MachineFunction *CurMF = FuncInfo.MF; 10668 MachineBasicBlock *NextMBB = nullptr; 10669 MachineFunction::iterator BBI(W.MBB); 10670 if (++BBI != FuncInfo.MF->end()) 10671 NextMBB = &*BBI; 10672 10673 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10674 10675 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10676 10677 if (Size == 2 && W.MBB == SwitchMBB) { 10678 // If any two of the cases has the same destination, and if one value 10679 // is the same as the other, but has one bit unset that the other has set, 10680 // use bit manipulation to do two compares at once. For example: 10681 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10682 // TODO: This could be extended to merge any 2 cases in switches with 3 10683 // cases. 10684 // TODO: Handle cases where W.CaseBB != SwitchBB. 10685 CaseCluster &Small = *W.FirstCluster; 10686 CaseCluster &Big = *W.LastCluster; 10687 10688 if (Small.Low == Small.High && Big.Low == Big.High && 10689 Small.MBB == Big.MBB) { 10690 const APInt &SmallValue = Small.Low->getValue(); 10691 const APInt &BigValue = Big.Low->getValue(); 10692 10693 // Check that there is only one bit different. 10694 APInt CommonBit = BigValue ^ SmallValue; 10695 if (CommonBit.isPowerOf2()) { 10696 SDValue CondLHS = getValue(Cond); 10697 EVT VT = CondLHS.getValueType(); 10698 SDLoc DL = getCurSDLoc(); 10699 10700 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10701 DAG.getConstant(CommonBit, DL, VT)); 10702 SDValue Cond = DAG.getSetCC( 10703 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10704 ISD::SETEQ); 10705 10706 // Update successor info. 10707 // Both Small and Big will jump to Small.BB, so we sum up the 10708 // probabilities. 10709 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10710 if (BPI) 10711 addSuccessorWithProb( 10712 SwitchMBB, DefaultMBB, 10713 // The default destination is the first successor in IR. 10714 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10715 else 10716 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10717 10718 // Insert the true branch. 10719 SDValue BrCond = 10720 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10721 DAG.getBasicBlock(Small.MBB)); 10722 // Insert the false branch. 10723 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10724 DAG.getBasicBlock(DefaultMBB)); 10725 10726 DAG.setRoot(BrCond); 10727 return; 10728 } 10729 } 10730 } 10731 10732 if (TM.getOptLevel() != CodeGenOpt::None) { 10733 // Here, we order cases by probability so the most likely case will be 10734 // checked first. However, two clusters can have the same probability in 10735 // which case their relative ordering is non-deterministic. So we use Low 10736 // as a tie-breaker as clusters are guaranteed to never overlap. 10737 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10738 [](const CaseCluster &a, const CaseCluster &b) { 10739 return a.Prob != b.Prob ? 10740 a.Prob > b.Prob : 10741 a.Low->getValue().slt(b.Low->getValue()); 10742 }); 10743 10744 // Rearrange the case blocks so that the last one falls through if possible 10745 // without changing the order of probabilities. 10746 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10747 --I; 10748 if (I->Prob > W.LastCluster->Prob) 10749 break; 10750 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10751 std::swap(*I, *W.LastCluster); 10752 break; 10753 } 10754 } 10755 } 10756 10757 // Compute total probability. 10758 BranchProbability DefaultProb = W.DefaultProb; 10759 BranchProbability UnhandledProbs = DefaultProb; 10760 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10761 UnhandledProbs += I->Prob; 10762 10763 MachineBasicBlock *CurMBB = W.MBB; 10764 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10765 bool FallthroughUnreachable = false; 10766 MachineBasicBlock *Fallthrough; 10767 if (I == W.LastCluster) { 10768 // For the last cluster, fall through to the default destination. 10769 Fallthrough = DefaultMBB; 10770 FallthroughUnreachable = isa<UnreachableInst>( 10771 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10772 } else { 10773 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10774 CurMF->insert(BBI, Fallthrough); 10775 // Put Cond in a virtual register to make it available from the new blocks. 10776 ExportFromCurrentBlock(Cond); 10777 } 10778 UnhandledProbs -= I->Prob; 10779 10780 switch (I->Kind) { 10781 case CC_JumpTable: { 10782 // FIXME: Optimize away range check based on pivot comparisons. 10783 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10784 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10785 10786 // The jump block hasn't been inserted yet; insert it here. 10787 MachineBasicBlock *JumpMBB = JT->MBB; 10788 CurMF->insert(BBI, JumpMBB); 10789 10790 auto JumpProb = I->Prob; 10791 auto FallthroughProb = UnhandledProbs; 10792 10793 // If the default statement is a target of the jump table, we evenly 10794 // distribute the default probability to successors of CurMBB. Also 10795 // update the probability on the edge from JumpMBB to Fallthrough. 10796 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10797 SE = JumpMBB->succ_end(); 10798 SI != SE; ++SI) { 10799 if (*SI == DefaultMBB) { 10800 JumpProb += DefaultProb / 2; 10801 FallthroughProb -= DefaultProb / 2; 10802 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10803 JumpMBB->normalizeSuccProbs(); 10804 break; 10805 } 10806 } 10807 10808 if (FallthroughUnreachable) 10809 JTH->FallthroughUnreachable = true; 10810 10811 if (!JTH->FallthroughUnreachable) 10812 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10813 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10814 CurMBB->normalizeSuccProbs(); 10815 10816 // The jump table header will be inserted in our current block, do the 10817 // range check, and fall through to our fallthrough block. 10818 JTH->HeaderBB = CurMBB; 10819 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10820 10821 // If we're in the right place, emit the jump table header right now. 10822 if (CurMBB == SwitchMBB) { 10823 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10824 JTH->Emitted = true; 10825 } 10826 break; 10827 } 10828 case CC_BitTests: { 10829 // FIXME: Optimize away range check based on pivot comparisons. 10830 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10831 10832 // The bit test blocks haven't been inserted yet; insert them here. 10833 for (BitTestCase &BTC : BTB->Cases) 10834 CurMF->insert(BBI, BTC.ThisBB); 10835 10836 // Fill in fields of the BitTestBlock. 10837 BTB->Parent = CurMBB; 10838 BTB->Default = Fallthrough; 10839 10840 BTB->DefaultProb = UnhandledProbs; 10841 // If the cases in bit test don't form a contiguous range, we evenly 10842 // distribute the probability on the edge to Fallthrough to two 10843 // successors of CurMBB. 10844 if (!BTB->ContiguousRange) { 10845 BTB->Prob += DefaultProb / 2; 10846 BTB->DefaultProb -= DefaultProb / 2; 10847 } 10848 10849 if (FallthroughUnreachable) 10850 BTB->FallthroughUnreachable = true; 10851 10852 // If we're in the right place, emit the bit test header right now. 10853 if (CurMBB == SwitchMBB) { 10854 visitBitTestHeader(*BTB, SwitchMBB); 10855 BTB->Emitted = true; 10856 } 10857 break; 10858 } 10859 case CC_Range: { 10860 const Value *RHS, *LHS, *MHS; 10861 ISD::CondCode CC; 10862 if (I->Low == I->High) { 10863 // Check Cond == I->Low. 10864 CC = ISD::SETEQ; 10865 LHS = Cond; 10866 RHS=I->Low; 10867 MHS = nullptr; 10868 } else { 10869 // Check I->Low <= Cond <= I->High. 10870 CC = ISD::SETLE; 10871 LHS = I->Low; 10872 MHS = Cond; 10873 RHS = I->High; 10874 } 10875 10876 // If Fallthrough is unreachable, fold away the comparison. 10877 if (FallthroughUnreachable) 10878 CC = ISD::SETTRUE; 10879 10880 // The false probability is the sum of all unhandled cases. 10881 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10882 getCurSDLoc(), I->Prob, UnhandledProbs); 10883 10884 if (CurMBB == SwitchMBB) 10885 visitSwitchCase(CB, SwitchMBB); 10886 else 10887 SL->SwitchCases.push_back(CB); 10888 10889 break; 10890 } 10891 } 10892 CurMBB = Fallthrough; 10893 } 10894 } 10895 10896 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10897 CaseClusterIt First, 10898 CaseClusterIt Last) { 10899 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10900 if (X.Prob != CC.Prob) 10901 return X.Prob > CC.Prob; 10902 10903 // Ties are broken by comparing the case value. 10904 return X.Low->getValue().slt(CC.Low->getValue()); 10905 }); 10906 } 10907 10908 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10909 const SwitchWorkListItem &W, 10910 Value *Cond, 10911 MachineBasicBlock *SwitchMBB) { 10912 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10913 "Clusters not sorted?"); 10914 10915 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10916 10917 // Balance the tree based on branch probabilities to create a near-optimal (in 10918 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10919 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10920 CaseClusterIt LastLeft = W.FirstCluster; 10921 CaseClusterIt FirstRight = W.LastCluster; 10922 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10923 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10924 10925 // Move LastLeft and FirstRight towards each other from opposite directions to 10926 // find a partitioning of the clusters which balances the probability on both 10927 // sides. If LeftProb and RightProb are equal, alternate which side is 10928 // taken to ensure 0-probability nodes are distributed evenly. 10929 unsigned I = 0; 10930 while (LastLeft + 1 < FirstRight) { 10931 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10932 LeftProb += (++LastLeft)->Prob; 10933 else 10934 RightProb += (--FirstRight)->Prob; 10935 I++; 10936 } 10937 10938 while (true) { 10939 // Our binary search tree differs from a typical BST in that ours can have up 10940 // to three values in each leaf. The pivot selection above doesn't take that 10941 // into account, which means the tree might require more nodes and be less 10942 // efficient. We compensate for this here. 10943 10944 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10945 unsigned NumRight = W.LastCluster - FirstRight + 1; 10946 10947 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10948 // If one side has less than 3 clusters, and the other has more than 3, 10949 // consider taking a cluster from the other side. 10950 10951 if (NumLeft < NumRight) { 10952 // Consider moving the first cluster on the right to the left side. 10953 CaseCluster &CC = *FirstRight; 10954 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10955 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10956 if (LeftSideRank <= RightSideRank) { 10957 // Moving the cluster to the left does not demote it. 10958 ++LastLeft; 10959 ++FirstRight; 10960 continue; 10961 } 10962 } else { 10963 assert(NumRight < NumLeft); 10964 // Consider moving the last element on the left to the right side. 10965 CaseCluster &CC = *LastLeft; 10966 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10967 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10968 if (RightSideRank <= LeftSideRank) { 10969 // Moving the cluster to the right does not demot it. 10970 --LastLeft; 10971 --FirstRight; 10972 continue; 10973 } 10974 } 10975 } 10976 break; 10977 } 10978 10979 assert(LastLeft + 1 == FirstRight); 10980 assert(LastLeft >= W.FirstCluster); 10981 assert(FirstRight <= W.LastCluster); 10982 10983 // Use the first element on the right as pivot since we will make less-than 10984 // comparisons against it. 10985 CaseClusterIt PivotCluster = FirstRight; 10986 assert(PivotCluster > W.FirstCluster); 10987 assert(PivotCluster <= W.LastCluster); 10988 10989 CaseClusterIt FirstLeft = W.FirstCluster; 10990 CaseClusterIt LastRight = W.LastCluster; 10991 10992 const ConstantInt *Pivot = PivotCluster->Low; 10993 10994 // New blocks will be inserted immediately after the current one. 10995 MachineFunction::iterator BBI(W.MBB); 10996 ++BBI; 10997 10998 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10999 // we can branch to its destination directly if it's squeezed exactly in 11000 // between the known lower bound and Pivot - 1. 11001 MachineBasicBlock *LeftMBB; 11002 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11003 FirstLeft->Low == W.GE && 11004 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11005 LeftMBB = FirstLeft->MBB; 11006 } else { 11007 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11008 FuncInfo.MF->insert(BBI, LeftMBB); 11009 WorkList.push_back( 11010 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11011 // Put Cond in a virtual register to make it available from the new blocks. 11012 ExportFromCurrentBlock(Cond); 11013 } 11014 11015 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11016 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11017 // directly if RHS.High equals the current upper bound. 11018 MachineBasicBlock *RightMBB; 11019 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11020 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11021 RightMBB = FirstRight->MBB; 11022 } else { 11023 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11024 FuncInfo.MF->insert(BBI, RightMBB); 11025 WorkList.push_back( 11026 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11027 // Put Cond in a virtual register to make it available from the new blocks. 11028 ExportFromCurrentBlock(Cond); 11029 } 11030 11031 // Create the CaseBlock record that will be used to lower the branch. 11032 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11033 getCurSDLoc(), LeftProb, RightProb); 11034 11035 if (W.MBB == SwitchMBB) 11036 visitSwitchCase(CB, SwitchMBB); 11037 else 11038 SL->SwitchCases.push_back(CB); 11039 } 11040 11041 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11042 // from the swith statement. 11043 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11044 BranchProbability PeeledCaseProb) { 11045 if (PeeledCaseProb == BranchProbability::getOne()) 11046 return BranchProbability::getZero(); 11047 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11048 11049 uint32_t Numerator = CaseProb.getNumerator(); 11050 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11051 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11052 } 11053 11054 // Try to peel the top probability case if it exceeds the threshold. 11055 // Return current MachineBasicBlock for the switch statement if the peeling 11056 // does not occur. 11057 // If the peeling is performed, return the newly created MachineBasicBlock 11058 // for the peeled switch statement. Also update Clusters to remove the peeled 11059 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11060 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11061 const SwitchInst &SI, CaseClusterVector &Clusters, 11062 BranchProbability &PeeledCaseProb) { 11063 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11064 // Don't perform if there is only one cluster or optimizing for size. 11065 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11066 TM.getOptLevel() == CodeGenOpt::None || 11067 SwitchMBB->getParent()->getFunction().hasMinSize()) 11068 return SwitchMBB; 11069 11070 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11071 unsigned PeeledCaseIndex = 0; 11072 bool SwitchPeeled = false; 11073 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11074 CaseCluster &CC = Clusters[Index]; 11075 if (CC.Prob < TopCaseProb) 11076 continue; 11077 TopCaseProb = CC.Prob; 11078 PeeledCaseIndex = Index; 11079 SwitchPeeled = true; 11080 } 11081 if (!SwitchPeeled) 11082 return SwitchMBB; 11083 11084 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11085 << TopCaseProb << "\n"); 11086 11087 // Record the MBB for the peeled switch statement. 11088 MachineFunction::iterator BBI(SwitchMBB); 11089 ++BBI; 11090 MachineBasicBlock *PeeledSwitchMBB = 11091 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11092 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11093 11094 ExportFromCurrentBlock(SI.getCondition()); 11095 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11096 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11097 nullptr, nullptr, TopCaseProb.getCompl()}; 11098 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11099 11100 Clusters.erase(PeeledCaseIt); 11101 for (CaseCluster &CC : Clusters) { 11102 LLVM_DEBUG( 11103 dbgs() << "Scale the probablity for one cluster, before scaling: " 11104 << CC.Prob << "\n"); 11105 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11106 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11107 } 11108 PeeledCaseProb = TopCaseProb; 11109 return PeeledSwitchMBB; 11110 } 11111 11112 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11113 // Extract cases from the switch. 11114 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11115 CaseClusterVector Clusters; 11116 Clusters.reserve(SI.getNumCases()); 11117 for (auto I : SI.cases()) { 11118 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11119 const ConstantInt *CaseVal = I.getCaseValue(); 11120 BranchProbability Prob = 11121 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11122 : BranchProbability(1, SI.getNumCases() + 1); 11123 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11124 } 11125 11126 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11127 11128 // Cluster adjacent cases with the same destination. We do this at all 11129 // optimization levels because it's cheap to do and will make codegen faster 11130 // if there are many clusters. 11131 sortAndRangeify(Clusters); 11132 11133 // The branch probablity of the peeled case. 11134 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11135 MachineBasicBlock *PeeledSwitchMBB = 11136 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11137 11138 // If there is only the default destination, jump there directly. 11139 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11140 if (Clusters.empty()) { 11141 assert(PeeledSwitchMBB == SwitchMBB); 11142 SwitchMBB->addSuccessor(DefaultMBB); 11143 if (DefaultMBB != NextBlock(SwitchMBB)) { 11144 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11145 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11146 } 11147 return; 11148 } 11149 11150 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11151 SL->findBitTestClusters(Clusters, &SI); 11152 11153 LLVM_DEBUG({ 11154 dbgs() << "Case clusters: "; 11155 for (const CaseCluster &C : Clusters) { 11156 if (C.Kind == CC_JumpTable) 11157 dbgs() << "JT:"; 11158 if (C.Kind == CC_BitTests) 11159 dbgs() << "BT:"; 11160 11161 C.Low->getValue().print(dbgs(), true); 11162 if (C.Low != C.High) { 11163 dbgs() << '-'; 11164 C.High->getValue().print(dbgs(), true); 11165 } 11166 dbgs() << ' '; 11167 } 11168 dbgs() << '\n'; 11169 }); 11170 11171 assert(!Clusters.empty()); 11172 SwitchWorkList WorkList; 11173 CaseClusterIt First = Clusters.begin(); 11174 CaseClusterIt Last = Clusters.end() - 1; 11175 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11176 // Scale the branchprobability for DefaultMBB if the peel occurs and 11177 // DefaultMBB is not replaced. 11178 if (PeeledCaseProb != BranchProbability::getZero() && 11179 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11180 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11181 WorkList.push_back( 11182 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11183 11184 while (!WorkList.empty()) { 11185 SwitchWorkListItem W = WorkList.pop_back_val(); 11186 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11187 11188 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11189 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11190 // For optimized builds, lower large range as a balanced binary tree. 11191 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11192 continue; 11193 } 11194 11195 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11196 } 11197 } 11198 11199 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11200 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11201 auto DL = getCurSDLoc(); 11202 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11203 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11204 } 11205 11206 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11207 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11208 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11209 11210 SDLoc DL = getCurSDLoc(); 11211 SDValue V = getValue(I.getOperand(0)); 11212 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11213 11214 if (VT.isScalableVector()) { 11215 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11216 return; 11217 } 11218 11219 // Use VECTOR_SHUFFLE for the fixed-length vector 11220 // to maintain existing behavior. 11221 SmallVector<int, 8> Mask; 11222 unsigned NumElts = VT.getVectorMinNumElements(); 11223 for (unsigned i = 0; i != NumElts; ++i) 11224 Mask.push_back(NumElts - 1 - i); 11225 11226 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11227 } 11228 11229 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11230 SmallVector<EVT, 4> ValueVTs; 11231 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11232 ValueVTs); 11233 unsigned NumValues = ValueVTs.size(); 11234 if (NumValues == 0) return; 11235 11236 SmallVector<SDValue, 4> Values(NumValues); 11237 SDValue Op = getValue(I.getOperand(0)); 11238 11239 for (unsigned i = 0; i != NumValues; ++i) 11240 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11241 SDValue(Op.getNode(), Op.getResNo() + i)); 11242 11243 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11244 DAG.getVTList(ValueVTs), Values)); 11245 } 11246 11247 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11248 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11249 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11250 11251 SDLoc DL = getCurSDLoc(); 11252 SDValue V1 = getValue(I.getOperand(0)); 11253 SDValue V2 = getValue(I.getOperand(1)); 11254 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11255 11256 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11257 if (VT.isScalableVector()) { 11258 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11259 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11260 DAG.getConstant(Imm, DL, IdxVT))); 11261 return; 11262 } 11263 11264 unsigned NumElts = VT.getVectorNumElements(); 11265 11266 if ((-Imm > NumElts) || (Imm >= NumElts)) { 11267 // Result is undefined if immediate is out-of-bounds. 11268 setValue(&I, DAG.getUNDEF(VT)); 11269 return; 11270 } 11271 11272 uint64_t Idx = (NumElts + Imm) % NumElts; 11273 11274 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11275 SmallVector<int, 8> Mask; 11276 for (unsigned i = 0; i < NumElts; ++i) 11277 Mask.push_back(Idx + i); 11278 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11279 } 11280