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