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/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 33 #include "llvm/CodeGen/CodeGenCommonISel.h" 34 #include "llvm/CodeGen/FunctionLoweringInfo.h" 35 #include "llvm/CodeGen/GCMetadata.h" 36 #include "llvm/CodeGen/MachineBasicBlock.h" 37 #include "llvm/CodeGen/MachineFrameInfo.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 41 #include "llvm/CodeGen/MachineMemOperand.h" 42 #include "llvm/CodeGen/MachineModuleInfo.h" 43 #include "llvm/CodeGen/MachineOperand.h" 44 #include "llvm/CodeGen/MachineRegisterInfo.h" 45 #include "llvm/CodeGen/RuntimeLibcalls.h" 46 #include "llvm/CodeGen/SelectionDAG.h" 47 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 48 #include "llvm/CodeGen/StackMaps.h" 49 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 50 #include "llvm/CodeGen/TargetFrameLowering.h" 51 #include "llvm/CodeGen/TargetInstrInfo.h" 52 #include "llvm/CodeGen/TargetOpcodes.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/TargetSubtargetInfo.h" 55 #include "llvm/CodeGen/WinEHFuncInfo.h" 56 #include "llvm/IR/Argument.h" 57 #include "llvm/IR/Attributes.h" 58 #include "llvm/IR/BasicBlock.h" 59 #include "llvm/IR/CFG.h" 60 #include "llvm/IR/CallingConv.h" 61 #include "llvm/IR/Constant.h" 62 #include "llvm/IR/ConstantRange.h" 63 #include "llvm/IR/Constants.h" 64 #include "llvm/IR/DataLayout.h" 65 #include "llvm/IR/DebugInfo.h" 66 #include "llvm/IR/DebugInfoMetadata.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/DiagnosticInfo.h" 69 #include "llvm/IR/EHPersonalities.h" 70 #include "llvm/IR/Function.h" 71 #include "llvm/IR/GetElementPtrTypeIterator.h" 72 #include "llvm/IR/InlineAsm.h" 73 #include "llvm/IR/InstrTypes.h" 74 #include "llvm/IR/Instructions.h" 75 #include "llvm/IR/IntrinsicInst.h" 76 #include "llvm/IR/Intrinsics.h" 77 #include "llvm/IR/IntrinsicsAArch64.h" 78 #include "llvm/IR/IntrinsicsWebAssembly.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Metadata.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/Operator.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Statepoint.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/Support/AtomicOrdering.h" 90 #include "llvm/Support/Casting.h" 91 #include "llvm/Support/CommandLine.h" 92 #include "llvm/Support/Compiler.h" 93 #include "llvm/Support/Debug.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetIntrinsicInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include "llvm/TargetParser/Triple.h" 100 #include "llvm/Transforms/Utils/Local.h" 101 #include <cstddef> 102 #include <iterator> 103 #include <limits> 104 #include <optional> 105 #include <tuple> 106 107 using namespace llvm; 108 using namespace PatternMatch; 109 using namespace SwitchCG; 110 111 #define DEBUG_TYPE "isel" 112 113 /// LimitFloatPrecision - Generate low-precision inline sequences for 114 /// some float libcalls (6, 8 or 12 bits). 115 static unsigned LimitFloatPrecision; 116 117 static cl::opt<bool> 118 InsertAssertAlign("insert-assert-align", cl::init(true), 119 cl::desc("Insert the experimental `assertalign` node."), 120 cl::ReallyHidden); 121 122 static cl::opt<unsigned, true> 123 LimitFPPrecision("limit-float-precision", 124 cl::desc("Generate low-precision inline sequences " 125 "for some float libcalls"), 126 cl::location(LimitFloatPrecision), cl::Hidden, 127 cl::init(0)); 128 129 static cl::opt<unsigned> SwitchPeelThreshold( 130 "switch-peel-threshold", cl::Hidden, cl::init(66), 131 cl::desc("Set the case probability threshold for peeling the case from a " 132 "switch statement. A value greater than 100 will void this " 133 "optimization")); 134 135 // Limit the width of DAG chains. This is important in general to prevent 136 // DAG-based analysis from blowing up. For example, alias analysis and 137 // load clustering may not complete in reasonable time. It is difficult to 138 // recognize and avoid this situation within each individual analysis, and 139 // future analyses are likely to have the same behavior. Limiting DAG width is 140 // the safe approach and will be especially important with global DAGs. 141 // 142 // MaxParallelChains default is arbitrarily high to avoid affecting 143 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 144 // sequence over this should have been converted to llvm.memcpy by the 145 // frontend. It is easy to induce this behavior with .ll code such as: 146 // %buffer = alloca [4096 x i8] 147 // %data = load [4096 x i8]* %argPtr 148 // store [4096 x i8] %data, [4096 x i8]* %buffer 149 static const unsigned MaxParallelChains = 64; 150 151 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 152 const SDValue *Parts, unsigned NumParts, 153 MVT PartVT, EVT ValueVT, const Value *V, 154 std::optional<CallingConv::ID> CC); 155 156 /// getCopyFromParts - Create a value that contains the specified legal parts 157 /// combined into the value they represent. If the parts combine to a type 158 /// larger than ValueVT then AssertOp can be used to specify whether the extra 159 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 160 /// (ISD::AssertSext). 161 static SDValue 162 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 163 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 164 std::optional<CallingConv::ID> CC = std::nullopt, 165 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 166 // Let the target assemble the parts if it wants to 167 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 168 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 169 PartVT, ValueVT, CC)) 170 return Val; 171 172 if (ValueVT.isVector()) 173 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 174 CC); 175 176 assert(NumParts > 0 && "No parts to assemble!"); 177 SDValue Val = Parts[0]; 178 179 if (NumParts > 1) { 180 // Assemble the value from multiple parts. 181 if (ValueVT.isInteger()) { 182 unsigned PartBits = PartVT.getSizeInBits(); 183 unsigned ValueBits = ValueVT.getSizeInBits(); 184 185 // Assemble the power of 2 part. 186 unsigned RoundParts = llvm::bit_floor(NumParts); 187 unsigned RoundBits = PartBits * RoundParts; 188 EVT RoundVT = RoundBits == ValueBits ? 189 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 190 SDValue Lo, Hi; 191 192 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 193 194 if (RoundParts > 2) { 195 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 196 PartVT, HalfVT, V); 197 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 198 RoundParts / 2, PartVT, HalfVT, V); 199 } else { 200 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 201 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 202 } 203 204 if (DAG.getDataLayout().isBigEndian()) 205 std::swap(Lo, Hi); 206 207 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 208 209 if (RoundParts < NumParts) { 210 // Assemble the trailing non-power-of-2 part. 211 unsigned OddParts = NumParts - RoundParts; 212 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 213 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 214 OddVT, V, CC); 215 216 // Combine the round and odd parts. 217 Lo = Val; 218 if (DAG.getDataLayout().isBigEndian()) 219 std::swap(Lo, Hi); 220 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 221 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 222 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 223 DAG.getConstant(Lo.getValueSizeInBits(), DL, 224 TLI.getShiftAmountTy( 225 TotalVT, DAG.getDataLayout()))); 226 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 227 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 228 } 229 } else if (PartVT.isFloatingPoint()) { 230 // FP split into multiple FP parts (for ppcf128) 231 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 232 "Unexpected split"); 233 SDValue Lo, Hi; 234 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 235 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 236 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 237 std::swap(Lo, Hi); 238 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 239 } else { 240 // FP split into integer parts (soft fp) 241 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 242 !PartVT.isVector() && "Unexpected split"); 243 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 244 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 245 } 246 } 247 248 // There is now one part, held in Val. Correct it to match ValueVT. 249 // PartEVT is the type of the register class that holds the value. 250 // ValueVT is the type of the inline asm operation. 251 EVT PartEVT = Val.getValueType(); 252 253 if (PartEVT == ValueVT) 254 return Val; 255 256 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 257 ValueVT.bitsLT(PartEVT)) { 258 // For an FP value in an integer part, we need to truncate to the right 259 // width first. 260 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 261 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 262 } 263 264 // Handle types that have the same size. 265 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 266 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 267 268 // Handle types with different sizes. 269 if (PartEVT.isInteger() && ValueVT.isInteger()) { 270 if (ValueVT.bitsLT(PartEVT)) { 271 // For a truncate, see if we have any information to 272 // indicate whether the truncated bits will always be 273 // zero or sign-extension. 274 if (AssertOp) 275 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 276 DAG.getValueType(ValueVT)); 277 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 278 } 279 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 280 } 281 282 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 283 // FP_ROUND's are always exact here. 284 if (ValueVT.bitsLT(Val.getValueType())) 285 return DAG.getNode( 286 ISD::FP_ROUND, DL, ValueVT, Val, 287 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 288 289 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 290 } 291 292 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 293 // then truncating. 294 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 295 ValueVT.bitsLT(PartEVT)) { 296 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 297 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 298 } 299 300 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 301 } 302 303 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 304 const Twine &ErrMsg) { 305 const Instruction *I = dyn_cast_or_null<Instruction>(V); 306 if (!V) 307 return Ctx.emitError(ErrMsg); 308 309 const char *AsmError = ", possible invalid constraint for vector type"; 310 if (const CallInst *CI = dyn_cast<CallInst>(I)) 311 if (CI->isInlineAsm()) 312 return Ctx.emitError(I, ErrMsg + AsmError); 313 314 return Ctx.emitError(I, ErrMsg); 315 } 316 317 /// getCopyFromPartsVector - Create a value that contains the specified legal 318 /// parts combined into the value they represent. If the parts combine to a 319 /// type larger than ValueVT then AssertOp can be used to specify whether the 320 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 321 /// ValueVT (ISD::AssertSext). 322 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 323 const SDValue *Parts, unsigned NumParts, 324 MVT PartVT, EVT ValueVT, const Value *V, 325 std::optional<CallingConv::ID> CallConv) { 326 assert(ValueVT.isVector() && "Not a vector value"); 327 assert(NumParts > 0 && "No parts to assemble!"); 328 const bool IsABIRegCopy = CallConv.has_value(); 329 330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 331 SDValue Val = Parts[0]; 332 333 // Handle a multi-element vector. 334 if (NumParts > 1) { 335 EVT IntermediateVT; 336 MVT RegisterVT; 337 unsigned NumIntermediates; 338 unsigned NumRegs; 339 340 if (IsABIRegCopy) { 341 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 342 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 343 NumIntermediates, RegisterVT); 344 } else { 345 NumRegs = 346 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } 349 350 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 351 NumParts = NumRegs; // Silence a compiler warning. 352 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 353 assert(RegisterVT.getSizeInBits() == 354 Parts[0].getSimpleValueType().getSizeInBits() && 355 "Part type sizes don't match!"); 356 357 // Assemble the parts into intermediate operands. 358 SmallVector<SDValue, 8> Ops(NumIntermediates); 359 if (NumIntermediates == NumParts) { 360 // If the register was not expanded, truncate or copy the value, 361 // as appropriate. 362 for (unsigned i = 0; i != NumParts; ++i) 363 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 364 PartVT, IntermediateVT, V, CallConv); 365 } else if (NumParts > 0) { 366 // If the intermediate type was expanded, build the intermediate 367 // operands from the parts. 368 assert(NumParts % NumIntermediates == 0 && 369 "Must expand into a divisible number of parts!"); 370 unsigned Factor = NumParts / NumIntermediates; 371 for (unsigned i = 0; i != NumIntermediates; ++i) 372 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 373 PartVT, IntermediateVT, V, CallConv); 374 } 375 376 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 377 // intermediate operands. 378 EVT BuiltVectorTy = 379 IntermediateVT.isVector() 380 ? EVT::getVectorVT( 381 *DAG.getContext(), IntermediateVT.getScalarType(), 382 IntermediateVT.getVectorElementCount() * NumParts) 383 : EVT::getVectorVT(*DAG.getContext(), 384 IntermediateVT.getScalarType(), 385 NumIntermediates); 386 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 387 : ISD::BUILD_VECTOR, 388 DL, BuiltVectorTy, Ops); 389 } 390 391 // There is now one part, held in Val. Correct it to match ValueVT. 392 EVT PartEVT = Val.getValueType(); 393 394 if (PartEVT == ValueVT) 395 return Val; 396 397 if (PartEVT.isVector()) { 398 // Vector/Vector bitcast. 399 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 400 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 401 402 // If the parts vector has more elements than the value vector, then we 403 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 404 // Extract the elements we want. 405 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 406 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 407 ValueVT.getVectorElementCount().getKnownMinValue()) && 408 (PartEVT.getVectorElementCount().isScalable() == 409 ValueVT.getVectorElementCount().isScalable()) && 410 "Cannot narrow, it would be a lossy transformation"); 411 PartEVT = 412 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 413 ValueVT.getVectorElementCount()); 414 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 415 DAG.getVectorIdxConstant(0, DL)); 416 if (PartEVT == ValueVT) 417 return Val; 418 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 420 } 421 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 } 425 426 // Trivial bitcast if the types are the same size and the destination 427 // vector type is legal. 428 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 429 TLI.isTypeLegal(ValueVT)) 430 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 431 432 if (ValueVT.getVectorNumElements() != 1) { 433 // Certain ABIs require that vectors are passed as integers. For vectors 434 // are the same size, this is an obvious bitcast. 435 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 437 } else if (ValueVT.bitsLT(PartEVT)) { 438 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 439 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 440 // Drop the extra bits. 441 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 442 return DAG.getBitcast(ValueVT, Val); 443 } 444 445 diagnosePossiblyInvalidConstraint( 446 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 447 return DAG.getUNDEF(ValueVT); 448 } 449 450 // Handle cases such as i8 -> <1 x i1> 451 EVT ValueSVT = ValueVT.getVectorElementType(); 452 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 453 unsigned ValueSize = ValueSVT.getSizeInBits(); 454 if (ValueSize == PartEVT.getSizeInBits()) { 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 457 // It's possible a scalar floating point type gets softened to integer and 458 // then promoted to a larger integer. If PartEVT is the larger integer 459 // we need to truncate it and then bitcast to the FP type. 460 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 463 Val = DAG.getBitcast(ValueSVT, Val); 464 } else { 465 Val = ValueVT.isFloatingPoint() 466 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 467 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 468 } 469 } 470 471 return DAG.getBuildVector(ValueVT, DL, Val); 472 } 473 474 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 475 SDValue Val, SDValue *Parts, unsigned NumParts, 476 MVT PartVT, const Value *V, 477 std::optional<CallingConv::ID> CallConv); 478 479 /// getCopyToParts - Create a series of nodes that contain the specified value 480 /// split into legal parts. If the parts contain more bits than Val, then, for 481 /// integers, ExtendKind can be used to specify how to generate the extra bits. 482 static void 483 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 484 unsigned NumParts, MVT PartVT, const Value *V, 485 std::optional<CallingConv::ID> CallConv = std::nullopt, 486 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 487 // Let the target split the parts if it wants to 488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 489 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 490 CallConv)) 491 return; 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned PartBits = PartVT.getSizeInBits(); 500 unsigned OrigNumParts = NumParts; 501 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 502 "Copying to an illegal type!"); 503 504 if (NumParts == 0) 505 return; 506 507 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 508 EVT PartEVT = PartVT; 509 if (PartEVT == ValueVT) { 510 assert(NumParts == 1 && "No-op copy with multiple parts!"); 511 Parts[0] = Val; 512 return; 513 } 514 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = llvm::bit_floor(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 576 577 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 578 CallConv); 579 580 if (DAG.getDataLayout().isBigEndian()) 581 // The odd parts were reversed by getCopyToParts - unreverse them. 582 std::reverse(Parts + RoundParts, Parts + NumParts); 583 584 NumParts = RoundParts; 585 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 587 } 588 589 // The number of parts is a power of 2. Repeatedly bisect the value using 590 // EXTRACT_ELEMENT. 591 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 592 EVT::getIntegerVT(*DAG.getContext(), 593 ValueVT.getSizeInBits()), 594 Val); 595 596 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 597 for (unsigned i = 0; i < NumParts; i += StepSize) { 598 unsigned ThisBits = StepSize * PartBits / 2; 599 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 600 SDValue &Part0 = Parts[i]; 601 SDValue &Part1 = Parts[i+StepSize/2]; 602 603 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 605 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 606 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 607 608 if (ThisBits == PartBits && ThisVT != PartVT) { 609 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 610 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 611 } 612 } 613 } 614 615 if (DAG.getDataLayout().isBigEndian()) 616 std::reverse(Parts, Parts + OrigNumParts); 617 } 618 619 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 620 const SDLoc &DL, EVT PartVT) { 621 if (!PartVT.isVector()) 622 return SDValue(); 623 624 EVT ValueVT = Val.getValueType(); 625 ElementCount PartNumElts = PartVT.getVectorElementCount(); 626 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 627 628 // We only support widening vectors with equivalent element types and 629 // fixed/scalable properties. If a target needs to widen a fixed-length type 630 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 631 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 632 PartNumElts.isScalable() != ValueNumElts.isScalable() || 633 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 634 return SDValue(); 635 636 // Widening a scalable vector to another scalable vector is done by inserting 637 // the vector into a larger undef one. 638 if (PartNumElts.isScalable()) 639 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 640 Val, DAG.getVectorIdxConstant(0, DL)); 641 642 EVT ElementVT = PartVT.getVectorElementType(); 643 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 644 // undef elements. 645 SmallVector<SDValue, 16> Ops; 646 DAG.ExtractVectorElements(Val, Ops); 647 SDValue EltUndef = DAG.getUNDEF(ElementVT); 648 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 649 650 // FIXME: Use CONCAT for 2x -> 4x. 651 return DAG.getBuildVector(PartVT, DL, Ops); 652 } 653 654 /// getCopyToPartsVector - Create a series of nodes that contain the specified 655 /// value split into legal parts. 656 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 657 SDValue Val, SDValue *Parts, unsigned NumParts, 658 MVT PartVT, const Value *V, 659 std::optional<CallingConv::ID> CallConv) { 660 EVT ValueVT = Val.getValueType(); 661 assert(ValueVT.isVector() && "Not a vector"); 662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 663 const bool IsABIRegCopy = CallConv.has_value(); 664 665 if (NumParts == 1) { 666 EVT PartEVT = PartVT; 667 if (PartEVT == ValueVT) { 668 // Nothing to do. 669 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 670 // Bitconvert vector->vector case. 671 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 672 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 673 Val = Widened; 674 } else if (PartVT.isVector() && 675 PartEVT.getVectorElementType().bitsGE( 676 ValueVT.getVectorElementType()) && 677 PartEVT.getVectorElementCount() == 678 ValueVT.getVectorElementCount()) { 679 680 // Promoted vector extract 681 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 682 } else if (PartEVT.isVector() && 683 PartEVT.getVectorElementType() != 684 ValueVT.getVectorElementType() && 685 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 686 TargetLowering::TypeWidenVector) { 687 // Combination of widening and promotion. 688 EVT WidenVT = 689 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 690 PartVT.getVectorElementCount()); 691 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 692 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 693 } else { 694 // Don't extract an integer from a float vector. This can happen if the 695 // FP type gets softened to integer and then promoted. The promotion 696 // prevents it from being picked up by the earlier bitcast case. 697 if (ValueVT.getVectorElementCount().isScalar() && 698 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 699 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 700 DAG.getVectorIdxConstant(0, DL)); 701 } else { 702 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 703 assert(PartVT.getFixedSizeInBits() > ValueSize && 704 "lossy conversion of vector to scalar type"); 705 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 706 Val = DAG.getBitcast(IntermediateType, Val); 707 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 708 } 709 } 710 711 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 712 Parts[0] = Val; 713 return; 714 } 715 716 // Handle a multi-element vector. 717 EVT IntermediateVT; 718 MVT RegisterVT; 719 unsigned NumIntermediates; 720 unsigned NumRegs; 721 if (IsABIRegCopy) { 722 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 723 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 724 RegisterVT); 725 } else { 726 NumRegs = 727 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 728 NumIntermediates, RegisterVT); 729 } 730 731 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 732 NumParts = NumRegs; // Silence a compiler warning. 733 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 734 735 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 736 "Mixing scalable and fixed vectors when copying in parts"); 737 738 std::optional<ElementCount> DestEltCnt; 739 740 if (IntermediateVT.isVector()) 741 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 742 else 743 DestEltCnt = ElementCount::getFixed(NumIntermediates); 744 745 EVT BuiltVectorTy = EVT::getVectorVT( 746 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 747 748 if (ValueVT == BuiltVectorTy) { 749 // Nothing to do. 750 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 751 // Bitconvert vector->vector case. 752 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 753 } else { 754 if (BuiltVectorTy.getVectorElementType().bitsGT( 755 ValueVT.getVectorElementType())) { 756 // Integer promotion. 757 ValueVT = EVT::getVectorVT(*DAG.getContext(), 758 BuiltVectorTy.getVectorElementType(), 759 ValueVT.getVectorElementCount()); 760 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 761 } 762 763 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 764 Val = Widened; 765 } 766 } 767 768 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 769 770 // Split the vector into intermediate operands. 771 SmallVector<SDValue, 8> Ops(NumIntermediates); 772 for (unsigned i = 0; i != NumIntermediates; ++i) { 773 if (IntermediateVT.isVector()) { 774 // This does something sensible for scalable vectors - see the 775 // definition of EXTRACT_SUBVECTOR for further details. 776 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 777 Ops[i] = 778 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 779 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 780 } else { 781 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 782 DAG.getVectorIdxConstant(i, DL)); 783 } 784 } 785 786 // Split the intermediate operands into legal parts. 787 if (NumParts == NumIntermediates) { 788 // If the register was not expanded, promote or copy the value, 789 // as appropriate. 790 for (unsigned i = 0; i != NumParts; ++i) 791 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 792 } else if (NumParts > 0) { 793 // If the intermediate type was expanded, split each the value into 794 // legal parts. 795 assert(NumIntermediates != 0 && "division by zero"); 796 assert(NumParts % NumIntermediates == 0 && 797 "Must expand into a divisible number of parts!"); 798 unsigned Factor = NumParts / NumIntermediates; 799 for (unsigned i = 0; i != NumIntermediates; ++i) 800 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 801 CallConv); 802 } 803 } 804 805 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 806 EVT valuevt, std::optional<CallingConv::ID> CC) 807 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 808 RegCount(1, regs.size()), CallConv(CC) {} 809 810 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 811 const DataLayout &DL, unsigned Reg, Type *Ty, 812 std::optional<CallingConv::ID> CC) { 813 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 814 815 CallConv = CC; 816 817 for (EVT ValueVT : ValueVTs) { 818 unsigned NumRegs = 819 isABIMangled() 820 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 821 : TLI.getNumRegisters(Context, ValueVT); 822 MVT RegisterVT = 823 isABIMangled() 824 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 825 : TLI.getRegisterType(Context, ValueVT); 826 for (unsigned i = 0; i != NumRegs; ++i) 827 Regs.push_back(Reg + i); 828 RegVTs.push_back(RegisterVT); 829 RegCount.push_back(NumRegs); 830 Reg += NumRegs; 831 } 832 } 833 834 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 835 FunctionLoweringInfo &FuncInfo, 836 const SDLoc &dl, SDValue &Chain, 837 SDValue *Flag, const Value *V) const { 838 // A Value with type {} or [0 x %t] needs no registers. 839 if (ValueVTs.empty()) 840 return SDValue(); 841 842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 843 844 // Assemble the legal parts into the final values. 845 SmallVector<SDValue, 4> Values(ValueVTs.size()); 846 SmallVector<SDValue, 8> Parts; 847 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 848 // Copy the legal parts from the registers. 849 EVT ValueVT = ValueVTs[Value]; 850 unsigned NumRegs = RegCount[Value]; 851 MVT RegisterVT = isABIMangled() 852 ? TLI.getRegisterTypeForCallingConv( 853 *DAG.getContext(), *CallConv, RegVTs[Value]) 854 : RegVTs[Value]; 855 856 Parts.resize(NumRegs); 857 for (unsigned i = 0; i != NumRegs; ++i) { 858 SDValue P; 859 if (!Flag) { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 861 } else { 862 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 863 *Flag = P.getValue(2); 864 } 865 866 Chain = P.getValue(1); 867 Parts[i] = P; 868 869 // If the source register was virtual and if we know something about it, 870 // add an assert node. 871 if (!Register::isVirtualRegister(Regs[Part + i]) || 872 !RegisterVT.isInteger()) 873 continue; 874 875 const FunctionLoweringInfo::LiveOutInfo *LOI = 876 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 877 if (!LOI) 878 continue; 879 880 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 881 unsigned NumSignBits = LOI->NumSignBits; 882 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 883 884 if (NumZeroBits == RegSize) { 885 // The current value is a zero. 886 // Explicitly express that as it would be easier for 887 // optimizations to kick in. 888 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 889 continue; 890 } 891 892 // FIXME: We capture more information than the dag can represent. For 893 // now, just use the tightest assertzext/assertsext possible. 894 bool isSExt; 895 EVT FromVT(MVT::Other); 896 if (NumZeroBits) { 897 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 898 isSExt = false; 899 } else if (NumSignBits > 1) { 900 FromVT = 901 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 902 isSExt = true; 903 } else { 904 continue; 905 } 906 // Add an assertion node. 907 assert(FromVT != MVT::Other); 908 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 909 RegisterVT, P, DAG.getValueType(FromVT)); 910 } 911 912 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 913 RegisterVT, ValueVT, V, CallConv); 914 Part += NumRegs; 915 Parts.clear(); 916 } 917 918 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 919 } 920 921 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 922 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 923 const Value *V, 924 ISD::NodeType PreferredExtendType) const { 925 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 926 ISD::NodeType ExtendKind = PreferredExtendType; 927 928 // Get the list of the values's legal parts. 929 unsigned NumRegs = Regs.size(); 930 SmallVector<SDValue, 8> Parts(NumRegs); 931 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 932 unsigned NumParts = RegCount[Value]; 933 934 MVT RegisterVT = isABIMangled() 935 ? TLI.getRegisterTypeForCallingConv( 936 *DAG.getContext(), *CallConv, RegVTs[Value]) 937 : RegVTs[Value]; 938 939 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 940 ExtendKind = ISD::ZERO_EXTEND; 941 942 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 943 NumParts, RegisterVT, V, CallConv, ExtendKind); 944 Part += NumParts; 945 } 946 947 // Copy the parts into the registers. 948 SmallVector<SDValue, 8> Chains(NumRegs); 949 for (unsigned i = 0; i != NumRegs; ++i) { 950 SDValue Part; 951 if (!Flag) { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 953 } else { 954 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 955 *Flag = Part.getValue(1); 956 } 957 958 Chains[i] = Part.getValue(0); 959 } 960 961 if (NumRegs == 1 || Flag) 962 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 963 // flagged to it. That is the CopyToReg nodes and the user are considered 964 // a single scheduling unit. If we create a TokenFactor and return it as 965 // chain, then the TokenFactor is both a predecessor (operand) of the 966 // user as well as a successor (the TF operands are flagged to the user). 967 // c1, f1 = CopyToReg 968 // c2, f2 = CopyToReg 969 // c3 = TokenFactor c1, c2 970 // ... 971 // = op c3, ..., f2 972 Chain = Chains[NumRegs-1]; 973 else 974 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 975 } 976 977 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 978 unsigned MatchingIdx, const SDLoc &dl, 979 SelectionDAG &DAG, 980 std::vector<SDValue> &Ops) const { 981 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 982 983 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 984 if (HasMatching) 985 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 986 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 987 // Put the register class of the virtual registers in the flag word. That 988 // way, later passes can recompute register class constraints for inline 989 // assembly as well as normal instructions. 990 // Don't do this for tied operands that can use the regclass information 991 // from the def. 992 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 993 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 994 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 995 } 996 997 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 998 Ops.push_back(Res); 999 1000 if (Code == InlineAsm::Kind_Clobber) { 1001 // Clobbers should always have a 1:1 mapping with registers, and may 1002 // reference registers that have illegal (e.g. vector) types. Hence, we 1003 // shouldn't try to apply any sort of splitting logic to them. 1004 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1005 "No 1:1 mapping from clobbers to regs?"); 1006 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1007 (void)SP; 1008 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1009 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1010 assert( 1011 (Regs[I] != SP || 1012 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1013 "If we clobbered the stack pointer, MFI should know about it."); 1014 } 1015 return; 1016 } 1017 1018 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1019 MVT RegisterVT = RegVTs[Value]; 1020 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1021 RegisterVT); 1022 for (unsigned i = 0; i != NumRegs; ++i) { 1023 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1024 unsigned TheReg = Regs[Reg++]; 1025 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1026 } 1027 } 1028 } 1029 1030 SmallVector<std::pair<unsigned, TypeSize>, 4> 1031 RegsForValue::getRegsAndSizes() const { 1032 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1033 unsigned I = 0; 1034 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1035 unsigned RegCount = std::get<0>(CountAndVT); 1036 MVT RegisterVT = std::get<1>(CountAndVT); 1037 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1038 for (unsigned E = I + RegCount; I != E; ++I) 1039 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1040 } 1041 return OutVec; 1042 } 1043 1044 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1045 AssumptionCache *ac, 1046 const TargetLibraryInfo *li) { 1047 AA = aa; 1048 AC = ac; 1049 GFI = gfi; 1050 LibInfo = li; 1051 Context = DAG.getContext(); 1052 LPadToCallSiteMap.clear(); 1053 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1054 } 1055 1056 void SelectionDAGBuilder::clear() { 1057 NodeMap.clear(); 1058 UnusedArgNodeMap.clear(); 1059 PendingLoads.clear(); 1060 PendingExports.clear(); 1061 PendingConstrainedFP.clear(); 1062 PendingConstrainedFPStrict.clear(); 1063 CurInst = nullptr; 1064 HasTailCall = false; 1065 SDNodeOrder = LowestSDNodeOrder; 1066 StatepointLowering.clear(); 1067 } 1068 1069 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1070 DanglingDebugInfoMap.clear(); 1071 } 1072 1073 // Update DAG root to include dependencies on Pending chains. 1074 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1075 SDValue Root = DAG.getRoot(); 1076 1077 if (Pending.empty()) 1078 return Root; 1079 1080 // Add current root to PendingChains, unless we already indirectly 1081 // depend on it. 1082 if (Root.getOpcode() != ISD::EntryToken) { 1083 unsigned i = 0, e = Pending.size(); 1084 for (; i != e; ++i) { 1085 assert(Pending[i].getNode()->getNumOperands() > 1); 1086 if (Pending[i].getNode()->getOperand(0) == Root) 1087 break; // Don't add the root if we already indirectly depend on it. 1088 } 1089 1090 if (i == e) 1091 Pending.push_back(Root); 1092 } 1093 1094 if (Pending.size() == 1) 1095 Root = Pending[0]; 1096 else 1097 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1098 1099 DAG.setRoot(Root); 1100 Pending.clear(); 1101 return Root; 1102 } 1103 1104 SDValue SelectionDAGBuilder::getMemoryRoot() { 1105 return updateRoot(PendingLoads); 1106 } 1107 1108 SDValue SelectionDAGBuilder::getRoot() { 1109 // Chain up all pending constrained intrinsics together with all 1110 // pending loads, by simply appending them to PendingLoads and 1111 // then calling getMemoryRoot(). 1112 PendingLoads.reserve(PendingLoads.size() + 1113 PendingConstrainedFP.size() + 1114 PendingConstrainedFPStrict.size()); 1115 PendingLoads.append(PendingConstrainedFP.begin(), 1116 PendingConstrainedFP.end()); 1117 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1118 PendingConstrainedFPStrict.end()); 1119 PendingConstrainedFP.clear(); 1120 PendingConstrainedFPStrict.clear(); 1121 return getMemoryRoot(); 1122 } 1123 1124 SDValue SelectionDAGBuilder::getControlRoot() { 1125 // We need to emit pending fpexcept.strict constrained intrinsics, 1126 // so append them to the PendingExports list. 1127 PendingExports.append(PendingConstrainedFPStrict.begin(), 1128 PendingConstrainedFPStrict.end()); 1129 PendingConstrainedFPStrict.clear(); 1130 return updateRoot(PendingExports); 1131 } 1132 1133 void SelectionDAGBuilder::visit(const Instruction &I) { 1134 // Set up outgoing PHI node register values before emitting the terminator. 1135 if (I.isTerminator()) { 1136 HandlePHINodesInSuccessorBlocks(I.getParent()); 1137 } 1138 1139 // Add SDDbgValue nodes for any var locs here. Do so before updating 1140 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1141 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1142 // Add SDDbgValue nodes for any var locs here. Do so before updating 1143 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1144 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1145 It != End; ++It) { 1146 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1147 dropDanglingDebugInfo(Var, It->Expr); 1148 if (!handleDebugValue(It->V, Var, It->Expr, It->DL, SDNodeOrder, 1149 /*IsVariadic=*/false)) 1150 addDanglingDebugInfo(It, SDNodeOrder); 1151 } 1152 } 1153 1154 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1155 if (!isa<DbgInfoIntrinsic>(I)) 1156 ++SDNodeOrder; 1157 1158 CurInst = &I; 1159 1160 // Set inserted listener only if required. 1161 bool NodeInserted = false; 1162 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1163 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1164 if (PCSectionsMD) { 1165 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1166 DAG, [&](SDNode *) { NodeInserted = true; }); 1167 } 1168 1169 visit(I.getOpcode(), I); 1170 1171 if (!I.isTerminator() && !HasTailCall && 1172 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1173 CopyToExportRegsIfNeeded(&I); 1174 1175 // Handle metadata. 1176 if (PCSectionsMD) { 1177 auto It = NodeMap.find(&I); 1178 if (It != NodeMap.end()) { 1179 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1180 } else if (NodeInserted) { 1181 // This should not happen; if it does, don't let it go unnoticed so we can 1182 // fix it. Relevant visit*() function is probably missing a setValue(). 1183 errs() << "warning: loosing !pcsections metadata [" 1184 << I.getModule()->getName() << "]\n"; 1185 LLVM_DEBUG(I.dump()); 1186 assert(false); 1187 } 1188 } 1189 1190 CurInst = nullptr; 1191 } 1192 1193 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1194 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1195 } 1196 1197 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1198 // Note: this doesn't use InstVisitor, because it has to work with 1199 // ConstantExpr's in addition to instructions. 1200 switch (Opcode) { 1201 default: llvm_unreachable("Unknown instruction type encountered!"); 1202 // Build the switch statement using the Instruction.def file. 1203 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1204 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1205 #include "llvm/IR/Instruction.def" 1206 } 1207 } 1208 1209 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1210 unsigned Order) { 1211 DanglingDebugInfoMap[VarLoc->V].emplace_back(VarLoc, Order); 1212 } 1213 1214 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1215 unsigned Order) { 1216 // We treat variadic dbg_values differently at this stage. 1217 if (DI->hasArgList()) { 1218 // For variadic dbg_values we will now insert an undef. 1219 // FIXME: We can potentially recover these! 1220 SmallVector<SDDbgOperand, 2> Locs; 1221 for (const Value *V : DI->getValues()) { 1222 auto Undef = UndefValue::get(V->getType()); 1223 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1224 } 1225 SDDbgValue *SDV = DAG.getDbgValueList( 1226 DI->getVariable(), DI->getExpression(), Locs, {}, 1227 /*IsIndirect=*/false, DI->getDebugLoc(), Order, /*IsVariadic=*/true); 1228 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1229 } else { 1230 // TODO: Dangling debug info will eventually either be resolved or produce 1231 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1232 // between the original dbg.value location and its resolved DBG_VALUE, 1233 // which we should ideally fill with an extra Undef DBG_VALUE. 1234 assert(DI->getNumVariableLocationOps() == 1 && 1235 "DbgValueInst without an ArgList should have a single location " 1236 "operand."); 1237 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1238 } 1239 } 1240 1241 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1242 const DIExpression *Expr) { 1243 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1244 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1245 DIExpression *DanglingExpr = DDI.getExpression(); 1246 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1247 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1248 << "\n"); 1249 return true; 1250 } 1251 return false; 1252 }; 1253 1254 for (auto &DDIMI : DanglingDebugInfoMap) { 1255 DanglingDebugInfoVector &DDIV = DDIMI.second; 1256 1257 // If debug info is to be dropped, run it through final checks to see 1258 // whether it can be salvaged. 1259 for (auto &DDI : DDIV) 1260 if (isMatchingDbgValue(DDI)) 1261 salvageUnresolvedDbgValue(DDI); 1262 1263 erase_if(DDIV, isMatchingDbgValue); 1264 } 1265 } 1266 1267 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1268 // generate the debug data structures now that we've seen its definition. 1269 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1270 SDValue Val) { 1271 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1272 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1273 return; 1274 1275 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1276 for (auto &DDI : DDIV) { 1277 DebugLoc DL = DDI.getDebugLoc(); 1278 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1279 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1280 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1281 DIExpression *Expr = DDI.getExpression(); 1282 assert(Variable->isValidLocationForIntrinsic(DL) && 1283 "Expected inlined-at fields to agree"); 1284 SDDbgValue *SDV; 1285 if (Val.getNode()) { 1286 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1287 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1288 // we couldn't resolve it directly when examining the DbgValue intrinsic 1289 // in the first place we should not be more successful here). Unless we 1290 // have some test case that prove this to be correct we should avoid 1291 // calling EmitFuncArgumentDbgValue here. 1292 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1293 FuncArgumentDbgValueKind::Value, Val)) { 1294 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1295 << "\n"); 1296 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1297 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1298 // inserted after the definition of Val when emitting the instructions 1299 // after ISel. An alternative could be to teach 1300 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1301 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1302 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1303 << ValSDNodeOrder << "\n"); 1304 SDV = getDbgValue(Val, Variable, Expr, DL, 1305 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1306 DAG.AddDbgValue(SDV, false); 1307 } else 1308 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1309 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1310 } else { 1311 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1312 auto Undef = UndefValue::get(V->getType()); 1313 auto SDV = 1314 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1315 DAG.AddDbgValue(SDV, false); 1316 } 1317 } 1318 DDIV.clear(); 1319 } 1320 1321 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1322 // TODO: For the variadic implementation, instead of only checking the fail 1323 // state of `handleDebugValue`, we need know specifically which values were 1324 // invalid, so that we attempt to salvage only those values when processing 1325 // a DIArgList. 1326 Value *V = DDI.getVariableLocationOp(0); 1327 Value *OrigV = V; 1328 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1329 DIExpression *Expr = DDI.getExpression(); 1330 DebugLoc DL = DDI.getDebugLoc(); 1331 unsigned SDOrder = DDI.getSDNodeOrder(); 1332 1333 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1334 // that DW_OP_stack_value is desired. 1335 bool StackValue = true; 1336 1337 // Can this Value can be encoded without any further work? 1338 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1339 return; 1340 1341 // Attempt to salvage back through as many instructions as possible. Bail if 1342 // a non-instruction is seen, such as a constant expression or global 1343 // variable. FIXME: Further work could recover those too. 1344 while (isa<Instruction>(V)) { 1345 Instruction &VAsInst = *cast<Instruction>(V); 1346 // Temporary "0", awaiting real implementation. 1347 SmallVector<uint64_t, 16> Ops; 1348 SmallVector<Value *, 4> AdditionalValues; 1349 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1350 AdditionalValues); 1351 // If we cannot salvage any further, and haven't yet found a suitable debug 1352 // expression, bail out. 1353 if (!V) 1354 break; 1355 1356 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1357 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1358 // here for variadic dbg_values, remove that condition. 1359 if (!AdditionalValues.empty()) 1360 break; 1361 1362 // New value and expr now represent this debuginfo. 1363 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1364 1365 // Some kind of simplification occurred: check whether the operand of the 1366 // salvaged debug expression can be encoded in this DAG. 1367 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1368 LLVM_DEBUG( 1369 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1370 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1371 return; 1372 } 1373 } 1374 1375 // This was the final opportunity to salvage this debug information, and it 1376 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1377 // any earlier variable location. 1378 assert(OrigV && "V shouldn't be null"); 1379 auto *Undef = UndefValue::get(OrigV->getType()); 1380 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1381 DAG.AddDbgValue(SDV, false); 1382 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1383 << "\n"); 1384 } 1385 1386 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1387 DILocalVariable *Var, 1388 DIExpression *Expr, DebugLoc DbgLoc, 1389 unsigned Order, bool IsVariadic) { 1390 if (Values.empty()) 1391 return true; 1392 SmallVector<SDDbgOperand> LocationOps; 1393 SmallVector<SDNode *> Dependencies; 1394 for (const Value *V : Values) { 1395 // Constant value. 1396 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1397 isa<ConstantPointerNull>(V)) { 1398 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1399 continue; 1400 } 1401 1402 // Look through IntToPtr constants. 1403 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1404 if (CE->getOpcode() == Instruction::IntToPtr) { 1405 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1406 continue; 1407 } 1408 1409 // If the Value is a frame index, we can create a FrameIndex debug value 1410 // without relying on the DAG at all. 1411 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1412 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1413 if (SI != FuncInfo.StaticAllocaMap.end()) { 1414 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1415 continue; 1416 } 1417 } 1418 1419 // Do not use getValue() in here; we don't want to generate code at 1420 // this point if it hasn't been done yet. 1421 SDValue N = NodeMap[V]; 1422 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1423 N = UnusedArgNodeMap[V]; 1424 if (N.getNode()) { 1425 // Only emit func arg dbg value for non-variadic dbg.values for now. 1426 if (!IsVariadic && 1427 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1428 FuncArgumentDbgValueKind::Value, N)) 1429 return true; 1430 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1431 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1432 // describe stack slot locations. 1433 // 1434 // Consider "int x = 0; int *px = &x;". There are two kinds of 1435 // interesting debug values here after optimization: 1436 // 1437 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1438 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1439 // 1440 // Both describe the direct values of their associated variables. 1441 Dependencies.push_back(N.getNode()); 1442 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1443 continue; 1444 } 1445 LocationOps.emplace_back( 1446 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1447 continue; 1448 } 1449 1450 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1451 // Special rules apply for the first dbg.values of parameter variables in a 1452 // function. Identify them by the fact they reference Argument Values, that 1453 // they're parameters, and they are parameters of the current function. We 1454 // need to let them dangle until they get an SDNode. 1455 bool IsParamOfFunc = 1456 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1457 if (IsParamOfFunc) 1458 return false; 1459 1460 // The value is not used in this block yet (or it would have an SDNode). 1461 // We still want the value to appear for the user if possible -- if it has 1462 // an associated VReg, we can refer to that instead. 1463 auto VMI = FuncInfo.ValueMap.find(V); 1464 if (VMI != FuncInfo.ValueMap.end()) { 1465 unsigned Reg = VMI->second; 1466 // If this is a PHI node, it may be split up into several MI PHI nodes 1467 // (in FunctionLoweringInfo::set). 1468 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1469 V->getType(), std::nullopt); 1470 if (RFV.occupiesMultipleRegs()) { 1471 // FIXME: We could potentially support variadic dbg_values here. 1472 if (IsVariadic) 1473 return false; 1474 unsigned Offset = 0; 1475 unsigned BitsToDescribe = 0; 1476 if (auto VarSize = Var->getSizeInBits()) 1477 BitsToDescribe = *VarSize; 1478 if (auto Fragment = Expr->getFragmentInfo()) 1479 BitsToDescribe = Fragment->SizeInBits; 1480 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1481 // Bail out if all bits are described already. 1482 if (Offset >= BitsToDescribe) 1483 break; 1484 // TODO: handle scalable vectors. 1485 unsigned RegisterSize = RegAndSize.second; 1486 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1487 ? BitsToDescribe - Offset 1488 : RegisterSize; 1489 auto FragmentExpr = DIExpression::createFragmentExpression( 1490 Expr, Offset, FragmentSize); 1491 if (!FragmentExpr) 1492 continue; 1493 SDDbgValue *SDV = DAG.getVRegDbgValue( 1494 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1495 DAG.AddDbgValue(SDV, false); 1496 Offset += RegisterSize; 1497 } 1498 return true; 1499 } 1500 // We can use simple vreg locations for variadic dbg_values as well. 1501 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1502 continue; 1503 } 1504 // We failed to create a SDDbgOperand for V. 1505 return false; 1506 } 1507 1508 // We have created a SDDbgOperand for each Value in Values. 1509 // Should use Order instead of SDNodeOrder? 1510 assert(!LocationOps.empty()); 1511 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1512 /*IsIndirect=*/false, DbgLoc, 1513 SDNodeOrder, IsVariadic); 1514 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1515 return true; 1516 } 1517 1518 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1519 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1520 for (auto &Pair : DanglingDebugInfoMap) 1521 for (auto &DDI : Pair.second) 1522 salvageUnresolvedDbgValue(DDI); 1523 clearDanglingDebugInfo(); 1524 } 1525 1526 /// getCopyFromRegs - If there was virtual register allocated for the value V 1527 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1528 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1529 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1530 SDValue Result; 1531 1532 if (It != FuncInfo.ValueMap.end()) { 1533 Register InReg = It->second; 1534 1535 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1536 DAG.getDataLayout(), InReg, Ty, 1537 std::nullopt); // This is not an ABI copy. 1538 SDValue Chain = DAG.getEntryNode(); 1539 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1540 V); 1541 resolveDanglingDebugInfo(V, Result); 1542 } 1543 1544 return Result; 1545 } 1546 1547 /// getValue - Return an SDValue for the given Value. 1548 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1549 // If we already have an SDValue for this value, use it. It's important 1550 // to do this first, so that we don't create a CopyFromReg if we already 1551 // have a regular SDValue. 1552 SDValue &N = NodeMap[V]; 1553 if (N.getNode()) return N; 1554 1555 // If there's a virtual register allocated and initialized for this 1556 // value, use it. 1557 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1558 return copyFromReg; 1559 1560 // Otherwise create a new SDValue and remember it. 1561 SDValue Val = getValueImpl(V); 1562 NodeMap[V] = Val; 1563 resolveDanglingDebugInfo(V, Val); 1564 return Val; 1565 } 1566 1567 /// getNonRegisterValue - Return an SDValue for the given Value, but 1568 /// don't look in FuncInfo.ValueMap for a virtual register. 1569 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1570 // If we already have an SDValue for this value, use it. 1571 SDValue &N = NodeMap[V]; 1572 if (N.getNode()) { 1573 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1574 // Remove the debug location from the node as the node is about to be used 1575 // in a location which may differ from the original debug location. This 1576 // is relevant to Constant and ConstantFP nodes because they can appear 1577 // as constant expressions inside PHI nodes. 1578 N->setDebugLoc(DebugLoc()); 1579 } 1580 return N; 1581 } 1582 1583 // Otherwise create a new SDValue and remember it. 1584 SDValue Val = getValueImpl(V); 1585 NodeMap[V] = Val; 1586 resolveDanglingDebugInfo(V, Val); 1587 return Val; 1588 } 1589 1590 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1591 /// Create an SDValue for the given value. 1592 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1593 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1594 1595 if (const Constant *C = dyn_cast<Constant>(V)) { 1596 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1597 1598 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1599 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1600 1601 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1602 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1603 1604 if (isa<ConstantPointerNull>(C)) { 1605 unsigned AS = V->getType()->getPointerAddressSpace(); 1606 return DAG.getConstant(0, getCurSDLoc(), 1607 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1608 } 1609 1610 if (match(C, m_VScale(DAG.getDataLayout()))) 1611 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1612 1613 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1614 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1615 1616 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1617 return DAG.getUNDEF(VT); 1618 1619 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1620 visit(CE->getOpcode(), *CE); 1621 SDValue N1 = NodeMap[V]; 1622 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1623 return N1; 1624 } 1625 1626 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1627 SmallVector<SDValue, 4> Constants; 1628 for (const Use &U : C->operands()) { 1629 SDNode *Val = getValue(U).getNode(); 1630 // If the operand is an empty aggregate, there are no values. 1631 if (!Val) continue; 1632 // Add each leaf value from the operand to the Constants list 1633 // to form a flattened list of all the values. 1634 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1635 Constants.push_back(SDValue(Val, i)); 1636 } 1637 1638 return DAG.getMergeValues(Constants, getCurSDLoc()); 1639 } 1640 1641 if (const ConstantDataSequential *CDS = 1642 dyn_cast<ConstantDataSequential>(C)) { 1643 SmallVector<SDValue, 4> Ops; 1644 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1645 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1646 // Add each leaf value from the operand to the Constants list 1647 // to form a flattened list of all the values. 1648 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1649 Ops.push_back(SDValue(Val, i)); 1650 } 1651 1652 if (isa<ArrayType>(CDS->getType())) 1653 return DAG.getMergeValues(Ops, getCurSDLoc()); 1654 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1655 } 1656 1657 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1658 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1659 "Unknown struct or array constant!"); 1660 1661 SmallVector<EVT, 4> ValueVTs; 1662 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1663 unsigned NumElts = ValueVTs.size(); 1664 if (NumElts == 0) 1665 return SDValue(); // empty struct 1666 SmallVector<SDValue, 4> Constants(NumElts); 1667 for (unsigned i = 0; i != NumElts; ++i) { 1668 EVT EltVT = ValueVTs[i]; 1669 if (isa<UndefValue>(C)) 1670 Constants[i] = DAG.getUNDEF(EltVT); 1671 else if (EltVT.isFloatingPoint()) 1672 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1673 else 1674 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1675 } 1676 1677 return DAG.getMergeValues(Constants, getCurSDLoc()); 1678 } 1679 1680 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1681 return DAG.getBlockAddress(BA, VT); 1682 1683 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1684 return getValue(Equiv->getGlobalValue()); 1685 1686 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1687 return getValue(NC->getGlobalValue()); 1688 1689 VectorType *VecTy = cast<VectorType>(V->getType()); 1690 1691 // Now that we know the number and type of the elements, get that number of 1692 // elements into the Ops array based on what kind of constant it is. 1693 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1694 SmallVector<SDValue, 16> Ops; 1695 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1696 for (unsigned i = 0; i != NumElements; ++i) 1697 Ops.push_back(getValue(CV->getOperand(i))); 1698 1699 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1700 } 1701 1702 if (isa<ConstantAggregateZero>(C)) { 1703 EVT EltVT = 1704 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1705 1706 SDValue Op; 1707 if (EltVT.isFloatingPoint()) 1708 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1709 else 1710 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1711 1712 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1713 } 1714 1715 llvm_unreachable("Unknown vector constant"); 1716 } 1717 1718 // If this is a static alloca, generate it as the frameindex instead of 1719 // computation. 1720 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1721 DenseMap<const AllocaInst*, int>::iterator SI = 1722 FuncInfo.StaticAllocaMap.find(AI); 1723 if (SI != FuncInfo.StaticAllocaMap.end()) 1724 return DAG.getFrameIndex( 1725 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1726 } 1727 1728 // If this is an instruction which fast-isel has deferred, select it now. 1729 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1730 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1731 1732 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1733 Inst->getType(), std::nullopt); 1734 SDValue Chain = DAG.getEntryNode(); 1735 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1736 } 1737 1738 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1739 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1740 1741 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1742 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1743 1744 llvm_unreachable("Can't get register for value!"); 1745 } 1746 1747 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1748 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1749 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1750 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1751 bool IsSEH = isAsynchronousEHPersonality(Pers); 1752 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1753 if (!IsSEH) 1754 CatchPadMBB->setIsEHScopeEntry(); 1755 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1756 if (IsMSVCCXX || IsCoreCLR) 1757 CatchPadMBB->setIsEHFuncletEntry(); 1758 } 1759 1760 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1761 // Update machine-CFG edge. 1762 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1763 FuncInfo.MBB->addSuccessor(TargetMBB); 1764 TargetMBB->setIsEHCatchretTarget(true); 1765 DAG.getMachineFunction().setHasEHCatchret(true); 1766 1767 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1768 bool IsSEH = isAsynchronousEHPersonality(Pers); 1769 if (IsSEH) { 1770 // If this is not a fall-through branch or optimizations are switched off, 1771 // emit the branch. 1772 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1773 TM.getOptLevel() == CodeGenOpt::None) 1774 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1775 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1776 return; 1777 } 1778 1779 // Figure out the funclet membership for the catchret's successor. 1780 // This will be used by the FuncletLayout pass to determine how to order the 1781 // BB's. 1782 // A 'catchret' returns to the outer scope's color. 1783 Value *ParentPad = I.getCatchSwitchParentPad(); 1784 const BasicBlock *SuccessorColor; 1785 if (isa<ConstantTokenNone>(ParentPad)) 1786 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1787 else 1788 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1789 assert(SuccessorColor && "No parent funclet for catchret!"); 1790 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1791 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1792 1793 // Create the terminator node. 1794 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1795 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1796 DAG.getBasicBlock(SuccessorColorMBB)); 1797 DAG.setRoot(Ret); 1798 } 1799 1800 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1801 // Don't emit any special code for the cleanuppad instruction. It just marks 1802 // the start of an EH scope/funclet. 1803 FuncInfo.MBB->setIsEHScopeEntry(); 1804 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1805 if (Pers != EHPersonality::Wasm_CXX) { 1806 FuncInfo.MBB->setIsEHFuncletEntry(); 1807 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1808 } 1809 } 1810 1811 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1812 // not match, it is OK to add only the first unwind destination catchpad to the 1813 // successors, because there will be at least one invoke instruction within the 1814 // catch scope that points to the next unwind destination, if one exists, so 1815 // CFGSort cannot mess up with BB sorting order. 1816 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1817 // call within them, and catchpads only consisting of 'catch (...)' have a 1818 // '__cxa_end_catch' call within them, both of which generate invokes in case 1819 // the next unwind destination exists, i.e., the next unwind destination is not 1820 // the caller.) 1821 // 1822 // Having at most one EH pad successor is also simpler and helps later 1823 // transformations. 1824 // 1825 // For example, 1826 // current: 1827 // invoke void @foo to ... unwind label %catch.dispatch 1828 // catch.dispatch: 1829 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1830 // catch.start: 1831 // ... 1832 // ... in this BB or some other child BB dominated by this BB there will be an 1833 // invoke that points to 'next' BB as an unwind destination 1834 // 1835 // next: ; We don't need to add this to 'current' BB's successor 1836 // ... 1837 static void findWasmUnwindDestinations( 1838 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1839 BranchProbability Prob, 1840 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1841 &UnwindDests) { 1842 while (EHPadBB) { 1843 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1844 if (isa<CleanupPadInst>(Pad)) { 1845 // Stop on cleanup pads. 1846 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1847 UnwindDests.back().first->setIsEHScopeEntry(); 1848 break; 1849 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1850 // Add the catchpad handlers to the possible destinations. We don't 1851 // continue to the unwind destination of the catchswitch for wasm. 1852 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1853 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1854 UnwindDests.back().first->setIsEHScopeEntry(); 1855 } 1856 break; 1857 } else { 1858 continue; 1859 } 1860 } 1861 } 1862 1863 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1864 /// many places it could ultimately go. In the IR, we have a single unwind 1865 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1866 /// This function skips over imaginary basic blocks that hold catchswitch 1867 /// instructions, and finds all the "real" machine 1868 /// basic block destinations. As those destinations may not be successors of 1869 /// EHPadBB, here we also calculate the edge probability to those destinations. 1870 /// The passed-in Prob is the edge probability to EHPadBB. 1871 static void findUnwindDestinations( 1872 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1873 BranchProbability Prob, 1874 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1875 &UnwindDests) { 1876 EHPersonality Personality = 1877 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1878 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1879 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1880 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1881 bool IsSEH = isAsynchronousEHPersonality(Personality); 1882 1883 if (IsWasmCXX) { 1884 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1885 assert(UnwindDests.size() <= 1 && 1886 "There should be at most one unwind destination for wasm"); 1887 return; 1888 } 1889 1890 while (EHPadBB) { 1891 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1892 BasicBlock *NewEHPadBB = nullptr; 1893 if (isa<LandingPadInst>(Pad)) { 1894 // Stop on landingpads. They are not funclets. 1895 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1896 break; 1897 } else if (isa<CleanupPadInst>(Pad)) { 1898 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1899 // personalities. 1900 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1901 UnwindDests.back().first->setIsEHScopeEntry(); 1902 UnwindDests.back().first->setIsEHFuncletEntry(); 1903 break; 1904 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1905 // Add the catchpad handlers to the possible destinations. 1906 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1907 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1908 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1909 if (IsMSVCCXX || IsCoreCLR) 1910 UnwindDests.back().first->setIsEHFuncletEntry(); 1911 if (!IsSEH) 1912 UnwindDests.back().first->setIsEHScopeEntry(); 1913 } 1914 NewEHPadBB = CatchSwitch->getUnwindDest(); 1915 } else { 1916 continue; 1917 } 1918 1919 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1920 if (BPI && NewEHPadBB) 1921 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1922 EHPadBB = NewEHPadBB; 1923 } 1924 } 1925 1926 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1927 // Update successor info. 1928 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1929 auto UnwindDest = I.getUnwindDest(); 1930 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1931 BranchProbability UnwindDestProb = 1932 (BPI && UnwindDest) 1933 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1934 : BranchProbability::getZero(); 1935 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1936 for (auto &UnwindDest : UnwindDests) { 1937 UnwindDest.first->setIsEHPad(); 1938 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1939 } 1940 FuncInfo.MBB->normalizeSuccProbs(); 1941 1942 // Create the terminator node. 1943 SDValue Ret = 1944 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1945 DAG.setRoot(Ret); 1946 } 1947 1948 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1949 report_fatal_error("visitCatchSwitch not yet implemented!"); 1950 } 1951 1952 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1954 auto &DL = DAG.getDataLayout(); 1955 SDValue Chain = getControlRoot(); 1956 SmallVector<ISD::OutputArg, 8> Outs; 1957 SmallVector<SDValue, 8> OutVals; 1958 1959 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1960 // lower 1961 // 1962 // %val = call <ty> @llvm.experimental.deoptimize() 1963 // ret <ty> %val 1964 // 1965 // differently. 1966 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1967 LowerDeoptimizingReturn(); 1968 return; 1969 } 1970 1971 if (!FuncInfo.CanLowerReturn) { 1972 unsigned DemoteReg = FuncInfo.DemoteRegister; 1973 const Function *F = I.getParent()->getParent(); 1974 1975 // Emit a store of the return value through the virtual register. 1976 // Leave Outs empty so that LowerReturn won't try to load return 1977 // registers the usual way. 1978 SmallVector<EVT, 1> PtrValueVTs; 1979 ComputeValueVTs(TLI, DL, 1980 F->getReturnType()->getPointerTo( 1981 DAG.getDataLayout().getAllocaAddrSpace()), 1982 PtrValueVTs); 1983 1984 SDValue RetPtr = 1985 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 1986 SDValue RetOp = getValue(I.getOperand(0)); 1987 1988 SmallVector<EVT, 4> ValueVTs, MemVTs; 1989 SmallVector<uint64_t, 4> Offsets; 1990 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1991 &Offsets); 1992 unsigned NumValues = ValueVTs.size(); 1993 1994 SmallVector<SDValue, 4> Chains(NumValues); 1995 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1996 for (unsigned i = 0; i != NumValues; ++i) { 1997 // An aggregate return value cannot wrap around the address space, so 1998 // offsets to its parts don't wrap either. 1999 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2000 TypeSize::Fixed(Offsets[i])); 2001 2002 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2003 if (MemVTs[i] != ValueVTs[i]) 2004 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2005 Chains[i] = DAG.getStore( 2006 Chain, getCurSDLoc(), Val, 2007 // FIXME: better loc info would be nice. 2008 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2009 commonAlignment(BaseAlign, Offsets[i])); 2010 } 2011 2012 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2013 MVT::Other, Chains); 2014 } else if (I.getNumOperands() != 0) { 2015 SmallVector<EVT, 4> ValueVTs; 2016 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2017 unsigned NumValues = ValueVTs.size(); 2018 if (NumValues) { 2019 SDValue RetOp = getValue(I.getOperand(0)); 2020 2021 const Function *F = I.getParent()->getParent(); 2022 2023 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2024 I.getOperand(0)->getType(), F->getCallingConv(), 2025 /*IsVarArg*/ false, DL); 2026 2027 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2028 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2029 ExtendKind = ISD::SIGN_EXTEND; 2030 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2031 ExtendKind = ISD::ZERO_EXTEND; 2032 2033 LLVMContext &Context = F->getContext(); 2034 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2035 2036 for (unsigned j = 0; j != NumValues; ++j) { 2037 EVT VT = ValueVTs[j]; 2038 2039 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2040 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2041 2042 CallingConv::ID CC = F->getCallingConv(); 2043 2044 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2045 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2046 SmallVector<SDValue, 4> Parts(NumParts); 2047 getCopyToParts(DAG, getCurSDLoc(), 2048 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2049 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2050 2051 // 'inreg' on function refers to return value 2052 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2053 if (RetInReg) 2054 Flags.setInReg(); 2055 2056 if (I.getOperand(0)->getType()->isPointerTy()) { 2057 Flags.setPointer(); 2058 Flags.setPointerAddrSpace( 2059 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2060 } 2061 2062 if (NeedsRegBlock) { 2063 Flags.setInConsecutiveRegs(); 2064 if (j == NumValues - 1) 2065 Flags.setInConsecutiveRegsLast(); 2066 } 2067 2068 // Propagate extension type if any 2069 if (ExtendKind == ISD::SIGN_EXTEND) 2070 Flags.setSExt(); 2071 else if (ExtendKind == ISD::ZERO_EXTEND) 2072 Flags.setZExt(); 2073 2074 for (unsigned i = 0; i < NumParts; ++i) { 2075 Outs.push_back(ISD::OutputArg(Flags, 2076 Parts[i].getValueType().getSimpleVT(), 2077 VT, /*isfixed=*/true, 0, 0)); 2078 OutVals.push_back(Parts[i]); 2079 } 2080 } 2081 } 2082 } 2083 2084 // Push in swifterror virtual register as the last element of Outs. This makes 2085 // sure swifterror virtual register will be returned in the swifterror 2086 // physical register. 2087 const Function *F = I.getParent()->getParent(); 2088 if (TLI.supportSwiftError() && 2089 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2090 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2091 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2092 Flags.setSwiftError(); 2093 Outs.push_back(ISD::OutputArg( 2094 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2095 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2096 // Create SDNode for the swifterror virtual register. 2097 OutVals.push_back( 2098 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2099 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2100 EVT(TLI.getPointerTy(DL)))); 2101 } 2102 2103 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2104 CallingConv::ID CallConv = 2105 DAG.getMachineFunction().getFunction().getCallingConv(); 2106 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2107 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2108 2109 // Verify that the target's LowerReturn behaved as expected. 2110 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2111 "LowerReturn didn't return a valid chain!"); 2112 2113 // Update the DAG with the new chain value resulting from return lowering. 2114 DAG.setRoot(Chain); 2115 } 2116 2117 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2118 /// created for it, emit nodes to copy the value into the virtual 2119 /// registers. 2120 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2121 // Skip empty types 2122 if (V->getType()->isEmptyTy()) 2123 return; 2124 2125 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2126 if (VMI != FuncInfo.ValueMap.end()) { 2127 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2128 "Unused value assigned virtual registers!"); 2129 CopyValueToVirtualRegister(V, VMI->second); 2130 } 2131 } 2132 2133 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2134 /// the current basic block, add it to ValueMap now so that we'll get a 2135 /// CopyTo/FromReg. 2136 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2137 // No need to export constants. 2138 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2139 2140 // Already exported? 2141 if (FuncInfo.isExportedInst(V)) return; 2142 2143 Register Reg = FuncInfo.InitializeRegForValue(V); 2144 CopyValueToVirtualRegister(V, Reg); 2145 } 2146 2147 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2148 const BasicBlock *FromBB) { 2149 // The operands of the setcc have to be in this block. We don't know 2150 // how to export them from some other block. 2151 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2152 // Can export from current BB. 2153 if (VI->getParent() == FromBB) 2154 return true; 2155 2156 // Is already exported, noop. 2157 return FuncInfo.isExportedInst(V); 2158 } 2159 2160 // If this is an argument, we can export it if the BB is the entry block or 2161 // if it is already exported. 2162 if (isa<Argument>(V)) { 2163 if (FromBB->isEntryBlock()) 2164 return true; 2165 2166 // Otherwise, can only export this if it is already exported. 2167 return FuncInfo.isExportedInst(V); 2168 } 2169 2170 // Otherwise, constants can always be exported. 2171 return true; 2172 } 2173 2174 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2175 BranchProbability 2176 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2177 const MachineBasicBlock *Dst) const { 2178 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2179 const BasicBlock *SrcBB = Src->getBasicBlock(); 2180 const BasicBlock *DstBB = Dst->getBasicBlock(); 2181 if (!BPI) { 2182 // If BPI is not available, set the default probability as 1 / N, where N is 2183 // the number of successors. 2184 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2185 return BranchProbability(1, SuccSize); 2186 } 2187 return BPI->getEdgeProbability(SrcBB, DstBB); 2188 } 2189 2190 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2191 MachineBasicBlock *Dst, 2192 BranchProbability Prob) { 2193 if (!FuncInfo.BPI) 2194 Src->addSuccessorWithoutProb(Dst); 2195 else { 2196 if (Prob.isUnknown()) 2197 Prob = getEdgeProbability(Src, Dst); 2198 Src->addSuccessor(Dst, Prob); 2199 } 2200 } 2201 2202 static bool InBlock(const Value *V, const BasicBlock *BB) { 2203 if (const Instruction *I = dyn_cast<Instruction>(V)) 2204 return I->getParent() == BB; 2205 return true; 2206 } 2207 2208 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2209 /// This function emits a branch and is used at the leaves of an OR or an 2210 /// AND operator tree. 2211 void 2212 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2213 MachineBasicBlock *TBB, 2214 MachineBasicBlock *FBB, 2215 MachineBasicBlock *CurBB, 2216 MachineBasicBlock *SwitchBB, 2217 BranchProbability TProb, 2218 BranchProbability FProb, 2219 bool InvertCond) { 2220 const BasicBlock *BB = CurBB->getBasicBlock(); 2221 2222 // If the leaf of the tree is a comparison, merge the condition into 2223 // the caseblock. 2224 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2225 // The operands of the cmp have to be in this block. We don't know 2226 // how to export them from some other block. If this is the first block 2227 // of the sequence, no exporting is needed. 2228 if (CurBB == SwitchBB || 2229 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2230 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2231 ISD::CondCode Condition; 2232 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2233 ICmpInst::Predicate Pred = 2234 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2235 Condition = getICmpCondCode(Pred); 2236 } else { 2237 const FCmpInst *FC = cast<FCmpInst>(Cond); 2238 FCmpInst::Predicate Pred = 2239 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2240 Condition = getFCmpCondCode(Pred); 2241 if (TM.Options.NoNaNsFPMath) 2242 Condition = getFCmpCodeWithoutNaN(Condition); 2243 } 2244 2245 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2246 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2247 SL->SwitchCases.push_back(CB); 2248 return; 2249 } 2250 } 2251 2252 // Create a CaseBlock record representing this branch. 2253 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2254 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2255 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2256 SL->SwitchCases.push_back(CB); 2257 } 2258 2259 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2260 MachineBasicBlock *TBB, 2261 MachineBasicBlock *FBB, 2262 MachineBasicBlock *CurBB, 2263 MachineBasicBlock *SwitchBB, 2264 Instruction::BinaryOps Opc, 2265 BranchProbability TProb, 2266 BranchProbability FProb, 2267 bool InvertCond) { 2268 // Skip over not part of the tree and remember to invert op and operands at 2269 // next level. 2270 Value *NotCond; 2271 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2272 InBlock(NotCond, CurBB->getBasicBlock())) { 2273 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2274 !InvertCond); 2275 return; 2276 } 2277 2278 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2279 const Value *BOpOp0, *BOpOp1; 2280 // Compute the effective opcode for Cond, taking into account whether it needs 2281 // to be inverted, e.g. 2282 // and (not (or A, B)), C 2283 // gets lowered as 2284 // and (and (not A, not B), C) 2285 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2286 if (BOp) { 2287 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2288 ? Instruction::And 2289 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2290 ? Instruction::Or 2291 : (Instruction::BinaryOps)0); 2292 if (InvertCond) { 2293 if (BOpc == Instruction::And) 2294 BOpc = Instruction::Or; 2295 else if (BOpc == Instruction::Or) 2296 BOpc = Instruction::And; 2297 } 2298 } 2299 2300 // If this node is not part of the or/and tree, emit it as a branch. 2301 // Note that all nodes in the tree should have same opcode. 2302 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2303 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2304 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2305 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2306 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2307 TProb, FProb, InvertCond); 2308 return; 2309 } 2310 2311 // Create TmpBB after CurBB. 2312 MachineFunction::iterator BBI(CurBB); 2313 MachineFunction &MF = DAG.getMachineFunction(); 2314 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2315 CurBB->getParent()->insert(++BBI, TmpBB); 2316 2317 if (Opc == Instruction::Or) { 2318 // Codegen X | Y as: 2319 // BB1: 2320 // jmp_if_X TBB 2321 // jmp TmpBB 2322 // TmpBB: 2323 // jmp_if_Y TBB 2324 // jmp FBB 2325 // 2326 2327 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2328 // The requirement is that 2329 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2330 // = TrueProb for original BB. 2331 // Assuming the original probabilities are A and B, one choice is to set 2332 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2333 // A/(1+B) and 2B/(1+B). This choice assumes that 2334 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2335 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2336 // TmpBB, but the math is more complicated. 2337 2338 auto NewTrueProb = TProb / 2; 2339 auto NewFalseProb = TProb / 2 + FProb; 2340 // Emit the LHS condition. 2341 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2342 NewFalseProb, InvertCond); 2343 2344 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2345 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2346 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2347 // Emit the RHS condition into TmpBB. 2348 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2349 Probs[1], InvertCond); 2350 } else { 2351 assert(Opc == Instruction::And && "Unknown merge op!"); 2352 // Codegen X & Y as: 2353 // BB1: 2354 // jmp_if_X TmpBB 2355 // jmp FBB 2356 // TmpBB: 2357 // jmp_if_Y TBB 2358 // jmp FBB 2359 // 2360 // This requires creation of TmpBB after CurBB. 2361 2362 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2363 // The requirement is that 2364 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2365 // = FalseProb for original BB. 2366 // Assuming the original probabilities are A and B, one choice is to set 2367 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2368 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2369 // TrueProb for BB1 * FalseProb for TmpBB. 2370 2371 auto NewTrueProb = TProb + FProb / 2; 2372 auto NewFalseProb = FProb / 2; 2373 // Emit the LHS condition. 2374 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2375 NewFalseProb, InvertCond); 2376 2377 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2378 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2379 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2380 // Emit the RHS condition into TmpBB. 2381 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2382 Probs[1], InvertCond); 2383 } 2384 } 2385 2386 /// If the set of cases should be emitted as a series of branches, return true. 2387 /// If we should emit this as a bunch of and/or'd together conditions, return 2388 /// false. 2389 bool 2390 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2391 if (Cases.size() != 2) return true; 2392 2393 // If this is two comparisons of the same values or'd or and'd together, they 2394 // will get folded into a single comparison, so don't emit two blocks. 2395 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2396 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2397 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2398 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2399 return false; 2400 } 2401 2402 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2403 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2404 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2405 Cases[0].CC == Cases[1].CC && 2406 isa<Constant>(Cases[0].CmpRHS) && 2407 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2408 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2409 return false; 2410 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2411 return false; 2412 } 2413 2414 return true; 2415 } 2416 2417 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2418 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2419 2420 // Update machine-CFG edges. 2421 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2422 2423 if (I.isUnconditional()) { 2424 // Update machine-CFG edges. 2425 BrMBB->addSuccessor(Succ0MBB); 2426 2427 // If this is not a fall-through branch or optimizations are switched off, 2428 // emit the branch. 2429 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2430 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2431 MVT::Other, getControlRoot(), 2432 DAG.getBasicBlock(Succ0MBB))); 2433 2434 return; 2435 } 2436 2437 // If this condition is one of the special cases we handle, do special stuff 2438 // now. 2439 const Value *CondVal = I.getCondition(); 2440 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2441 2442 // If this is a series of conditions that are or'd or and'd together, emit 2443 // this as a sequence of branches instead of setcc's with and/or operations. 2444 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2445 // unpredictable branches, and vector extracts because those jumps are likely 2446 // expensive for any target), this should improve performance. 2447 // For example, instead of something like: 2448 // cmp A, B 2449 // C = seteq 2450 // cmp D, E 2451 // F = setle 2452 // or C, F 2453 // jnz foo 2454 // Emit: 2455 // cmp A, B 2456 // je foo 2457 // cmp D, E 2458 // jle foo 2459 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2460 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2461 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2462 Value *Vec; 2463 const Value *BOp0, *BOp1; 2464 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2465 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2466 Opcode = Instruction::And; 2467 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2468 Opcode = Instruction::Or; 2469 2470 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2471 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2472 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2473 getEdgeProbability(BrMBB, Succ0MBB), 2474 getEdgeProbability(BrMBB, Succ1MBB), 2475 /*InvertCond=*/false); 2476 // If the compares in later blocks need to use values not currently 2477 // exported from this block, export them now. This block should always 2478 // be the first entry. 2479 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2480 2481 // Allow some cases to be rejected. 2482 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2483 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2484 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2485 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2486 } 2487 2488 // Emit the branch for this block. 2489 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2490 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2491 return; 2492 } 2493 2494 // Okay, we decided not to do this, remove any inserted MBB's and clear 2495 // SwitchCases. 2496 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2497 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2498 2499 SL->SwitchCases.clear(); 2500 } 2501 } 2502 2503 // Create a CaseBlock record representing this branch. 2504 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2505 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2506 2507 // Use visitSwitchCase to actually insert the fast branch sequence for this 2508 // cond branch. 2509 visitSwitchCase(CB, BrMBB); 2510 } 2511 2512 /// visitSwitchCase - Emits the necessary code to represent a single node in 2513 /// the binary search tree resulting from lowering a switch instruction. 2514 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2515 MachineBasicBlock *SwitchBB) { 2516 SDValue Cond; 2517 SDValue CondLHS = getValue(CB.CmpLHS); 2518 SDLoc dl = CB.DL; 2519 2520 if (CB.CC == ISD::SETTRUE) { 2521 // Branch or fall through to TrueBB. 2522 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2523 SwitchBB->normalizeSuccProbs(); 2524 if (CB.TrueBB != NextBlock(SwitchBB)) { 2525 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2526 DAG.getBasicBlock(CB.TrueBB))); 2527 } 2528 return; 2529 } 2530 2531 auto &TLI = DAG.getTargetLoweringInfo(); 2532 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2533 2534 // Build the setcc now. 2535 if (!CB.CmpMHS) { 2536 // Fold "(X == true)" to X and "(X == false)" to !X to 2537 // handle common cases produced by branch lowering. 2538 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2539 CB.CC == ISD::SETEQ) 2540 Cond = CondLHS; 2541 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2542 CB.CC == ISD::SETEQ) { 2543 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2544 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2545 } else { 2546 SDValue CondRHS = getValue(CB.CmpRHS); 2547 2548 // If a pointer's DAG type is larger than its memory type then the DAG 2549 // values are zero-extended. This breaks signed comparisons so truncate 2550 // back to the underlying type before doing the compare. 2551 if (CondLHS.getValueType() != MemVT) { 2552 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2553 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2554 } 2555 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2556 } 2557 } else { 2558 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2559 2560 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2561 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2562 2563 SDValue CmpOp = getValue(CB.CmpMHS); 2564 EVT VT = CmpOp.getValueType(); 2565 2566 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2567 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2568 ISD::SETLE); 2569 } else { 2570 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2571 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2572 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2573 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2574 } 2575 } 2576 2577 // Update successor info 2578 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2579 // TrueBB and FalseBB are always different unless the incoming IR is 2580 // degenerate. This only happens when running llc on weird IR. 2581 if (CB.TrueBB != CB.FalseBB) 2582 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2583 SwitchBB->normalizeSuccProbs(); 2584 2585 // If the lhs block is the next block, invert the condition so that we can 2586 // fall through to the lhs instead of the rhs block. 2587 if (CB.TrueBB == NextBlock(SwitchBB)) { 2588 std::swap(CB.TrueBB, CB.FalseBB); 2589 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2590 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2591 } 2592 2593 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2594 MVT::Other, getControlRoot(), Cond, 2595 DAG.getBasicBlock(CB.TrueBB)); 2596 2597 setValue(CurInst, BrCond); 2598 2599 // Insert the false branch. Do this even if it's a fall through branch, 2600 // this makes it easier to do DAG optimizations which require inverting 2601 // the branch condition. 2602 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2603 DAG.getBasicBlock(CB.FalseBB)); 2604 2605 DAG.setRoot(BrCond); 2606 } 2607 2608 /// visitJumpTable - Emit JumpTable node in the current MBB 2609 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2610 // Emit the code for the jump table 2611 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2612 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2613 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2614 JT.Reg, PTy); 2615 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2616 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2617 MVT::Other, Index.getValue(1), 2618 Table, Index); 2619 DAG.setRoot(BrJumpTable); 2620 } 2621 2622 /// visitJumpTableHeader - This function emits necessary code to produce index 2623 /// in the JumpTable from switch case. 2624 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2625 JumpTableHeader &JTH, 2626 MachineBasicBlock *SwitchBB) { 2627 SDLoc dl = getCurSDLoc(); 2628 2629 // Subtract the lowest switch case value from the value being switched on. 2630 SDValue SwitchOp = getValue(JTH.SValue); 2631 EVT VT = SwitchOp.getValueType(); 2632 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2633 DAG.getConstant(JTH.First, dl, VT)); 2634 2635 // The SDNode we just created, which holds the value being switched on minus 2636 // the smallest case value, needs to be copied to a virtual register so it 2637 // can be used as an index into the jump table in a subsequent basic block. 2638 // This value may be smaller or larger than the target's pointer type, and 2639 // therefore require extension or truncating. 2640 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2641 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2642 2643 unsigned JumpTableReg = 2644 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2645 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2646 JumpTableReg, SwitchOp); 2647 JT.Reg = JumpTableReg; 2648 2649 if (!JTH.FallthroughUnreachable) { 2650 // Emit the range check for the jump table, and branch to the default block 2651 // for the switch statement if the value being switched on exceeds the 2652 // largest case in the switch. 2653 SDValue CMP = DAG.getSetCC( 2654 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2655 Sub.getValueType()), 2656 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2657 2658 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2659 MVT::Other, CopyTo, CMP, 2660 DAG.getBasicBlock(JT.Default)); 2661 2662 // Avoid emitting unnecessary branches to the next block. 2663 if (JT.MBB != NextBlock(SwitchBB)) 2664 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2665 DAG.getBasicBlock(JT.MBB)); 2666 2667 DAG.setRoot(BrCond); 2668 } else { 2669 // Avoid emitting unnecessary branches to the next block. 2670 if (JT.MBB != NextBlock(SwitchBB)) 2671 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2672 DAG.getBasicBlock(JT.MBB))); 2673 else 2674 DAG.setRoot(CopyTo); 2675 } 2676 } 2677 2678 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2679 /// variable if there exists one. 2680 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2681 SDValue &Chain) { 2682 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2683 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2684 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2685 MachineFunction &MF = DAG.getMachineFunction(); 2686 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2687 MachineSDNode *Node = 2688 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2689 if (Global) { 2690 MachinePointerInfo MPInfo(Global); 2691 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2692 MachineMemOperand::MODereferenceable; 2693 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2694 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2695 DAG.setNodeMemRefs(Node, {MemRef}); 2696 } 2697 if (PtrTy != PtrMemTy) 2698 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2699 return SDValue(Node, 0); 2700 } 2701 2702 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2703 /// tail spliced into a stack protector check success bb. 2704 /// 2705 /// For a high level explanation of how this fits into the stack protector 2706 /// generation see the comment on the declaration of class 2707 /// StackProtectorDescriptor. 2708 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2709 MachineBasicBlock *ParentBB) { 2710 2711 // First create the loads to the guard/stack slot for the comparison. 2712 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2713 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2714 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2715 2716 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2717 int FI = MFI.getStackProtectorIndex(); 2718 2719 SDValue Guard; 2720 SDLoc dl = getCurSDLoc(); 2721 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2722 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2723 Align Align = 2724 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2725 2726 // Generate code to load the content of the guard slot. 2727 SDValue GuardVal = DAG.getLoad( 2728 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2729 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2730 MachineMemOperand::MOVolatile); 2731 2732 if (TLI.useStackGuardXorFP()) 2733 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2734 2735 // Retrieve guard check function, nullptr if instrumentation is inlined. 2736 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2737 // The target provides a guard check function to validate the guard value. 2738 // Generate a call to that function with the content of the guard slot as 2739 // argument. 2740 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2741 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2742 2743 TargetLowering::ArgListTy Args; 2744 TargetLowering::ArgListEntry Entry; 2745 Entry.Node = GuardVal; 2746 Entry.Ty = FnTy->getParamType(0); 2747 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2748 Entry.IsInReg = true; 2749 Args.push_back(Entry); 2750 2751 TargetLowering::CallLoweringInfo CLI(DAG); 2752 CLI.setDebugLoc(getCurSDLoc()) 2753 .setChain(DAG.getEntryNode()) 2754 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2755 getValue(GuardCheckFn), std::move(Args)); 2756 2757 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2758 DAG.setRoot(Result.second); 2759 return; 2760 } 2761 2762 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2763 // Otherwise, emit a volatile load to retrieve the stack guard value. 2764 SDValue Chain = DAG.getEntryNode(); 2765 if (TLI.useLoadStackGuardNode()) { 2766 Guard = getLoadStackGuard(DAG, dl, Chain); 2767 } else { 2768 const Value *IRGuard = TLI.getSDagStackGuard(M); 2769 SDValue GuardPtr = getValue(IRGuard); 2770 2771 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2772 MachinePointerInfo(IRGuard, 0), Align, 2773 MachineMemOperand::MOVolatile); 2774 } 2775 2776 // Perform the comparison via a getsetcc. 2777 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2778 *DAG.getContext(), 2779 Guard.getValueType()), 2780 Guard, GuardVal, ISD::SETNE); 2781 2782 // If the guard/stackslot do not equal, branch to failure MBB. 2783 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2784 MVT::Other, GuardVal.getOperand(0), 2785 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2786 // Otherwise branch to success MBB. 2787 SDValue Br = DAG.getNode(ISD::BR, dl, 2788 MVT::Other, BrCond, 2789 DAG.getBasicBlock(SPD.getSuccessMBB())); 2790 2791 DAG.setRoot(Br); 2792 } 2793 2794 /// Codegen the failure basic block for a stack protector check. 2795 /// 2796 /// A failure stack protector machine basic block consists simply of a call to 2797 /// __stack_chk_fail(). 2798 /// 2799 /// For a high level explanation of how this fits into the stack protector 2800 /// generation see the comment on the declaration of class 2801 /// StackProtectorDescriptor. 2802 void 2803 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2804 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2805 TargetLowering::MakeLibCallOptions CallOptions; 2806 CallOptions.setDiscardResult(true); 2807 SDValue Chain = 2808 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2809 std::nullopt, CallOptions, getCurSDLoc()) 2810 .second; 2811 // On PS4/PS5, the "return address" must still be within the calling 2812 // function, even if it's at the very end, so emit an explicit TRAP here. 2813 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2814 if (TM.getTargetTriple().isPS()) 2815 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2816 // WebAssembly needs an unreachable instruction after a non-returning call, 2817 // because the function return type can be different from __stack_chk_fail's 2818 // return type (void). 2819 if (TM.getTargetTriple().isWasm()) 2820 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2821 2822 DAG.setRoot(Chain); 2823 } 2824 2825 /// visitBitTestHeader - This function emits necessary code to produce value 2826 /// suitable for "bit tests" 2827 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2828 MachineBasicBlock *SwitchBB) { 2829 SDLoc dl = getCurSDLoc(); 2830 2831 // Subtract the minimum value. 2832 SDValue SwitchOp = getValue(B.SValue); 2833 EVT VT = SwitchOp.getValueType(); 2834 SDValue RangeSub = 2835 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2836 2837 // Determine the type of the test operands. 2838 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2839 bool UsePtrType = false; 2840 if (!TLI.isTypeLegal(VT)) { 2841 UsePtrType = true; 2842 } else { 2843 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2844 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2845 // Switch table case range are encoded into series of masks. 2846 // Just use pointer type, it's guaranteed to fit. 2847 UsePtrType = true; 2848 break; 2849 } 2850 } 2851 SDValue Sub = RangeSub; 2852 if (UsePtrType) { 2853 VT = TLI.getPointerTy(DAG.getDataLayout()); 2854 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2855 } 2856 2857 B.RegVT = VT.getSimpleVT(); 2858 B.Reg = FuncInfo.CreateReg(B.RegVT); 2859 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2860 2861 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2862 2863 if (!B.FallthroughUnreachable) 2864 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2865 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2866 SwitchBB->normalizeSuccProbs(); 2867 2868 SDValue Root = CopyTo; 2869 if (!B.FallthroughUnreachable) { 2870 // Conditional branch to the default block. 2871 SDValue RangeCmp = DAG.getSetCC(dl, 2872 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2873 RangeSub.getValueType()), 2874 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2875 ISD::SETUGT); 2876 2877 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2878 DAG.getBasicBlock(B.Default)); 2879 } 2880 2881 // Avoid emitting unnecessary branches to the next block. 2882 if (MBB != NextBlock(SwitchBB)) 2883 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2884 2885 DAG.setRoot(Root); 2886 } 2887 2888 /// visitBitTestCase - this function produces one "bit test" 2889 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2890 MachineBasicBlock* NextMBB, 2891 BranchProbability BranchProbToNext, 2892 unsigned Reg, 2893 BitTestCase &B, 2894 MachineBasicBlock *SwitchBB) { 2895 SDLoc dl = getCurSDLoc(); 2896 MVT VT = BB.RegVT; 2897 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2898 SDValue Cmp; 2899 unsigned PopCount = llvm::popcount(B.Mask); 2900 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2901 if (PopCount == 1) { 2902 // Testing for a single bit; just compare the shift count with what it 2903 // would need to be to shift a 1 bit in that position. 2904 Cmp = DAG.getSetCC( 2905 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2906 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2907 ISD::SETEQ); 2908 } else if (PopCount == BB.Range) { 2909 // There is only one zero bit in the range, test for it directly. 2910 Cmp = DAG.getSetCC( 2911 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2912 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2913 } else { 2914 // Make desired shift 2915 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2916 DAG.getConstant(1, dl, VT), ShiftOp); 2917 2918 // Emit bit tests and jumps 2919 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2920 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2921 Cmp = DAG.getSetCC( 2922 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2923 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2924 } 2925 2926 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2927 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2928 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2929 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2930 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2931 // one as they are relative probabilities (and thus work more like weights), 2932 // and hence we need to normalize them to let the sum of them become one. 2933 SwitchBB->normalizeSuccProbs(); 2934 2935 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2936 MVT::Other, getControlRoot(), 2937 Cmp, DAG.getBasicBlock(B.TargetBB)); 2938 2939 // Avoid emitting unnecessary branches to the next block. 2940 if (NextMBB != NextBlock(SwitchBB)) 2941 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2942 DAG.getBasicBlock(NextMBB)); 2943 2944 DAG.setRoot(BrAnd); 2945 } 2946 2947 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2948 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2949 2950 // Retrieve successors. Look through artificial IR level blocks like 2951 // catchswitch for successors. 2952 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2953 const BasicBlock *EHPadBB = I.getSuccessor(1); 2954 2955 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2956 // have to do anything here to lower funclet bundles. 2957 assert(!I.hasOperandBundlesOtherThan( 2958 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2959 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2960 LLVMContext::OB_cfguardtarget, 2961 LLVMContext::OB_clang_arc_attachedcall}) && 2962 "Cannot lower invokes with arbitrary operand bundles yet!"); 2963 2964 const Value *Callee(I.getCalledOperand()); 2965 const Function *Fn = dyn_cast<Function>(Callee); 2966 if (isa<InlineAsm>(Callee)) 2967 visitInlineAsm(I, EHPadBB); 2968 else if (Fn && Fn->isIntrinsic()) { 2969 switch (Fn->getIntrinsicID()) { 2970 default: 2971 llvm_unreachable("Cannot invoke this intrinsic"); 2972 case Intrinsic::donothing: 2973 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2974 case Intrinsic::seh_try_begin: 2975 case Intrinsic::seh_scope_begin: 2976 case Intrinsic::seh_try_end: 2977 case Intrinsic::seh_scope_end: 2978 break; 2979 case Intrinsic::experimental_patchpoint_void: 2980 case Intrinsic::experimental_patchpoint_i64: 2981 visitPatchpoint(I, EHPadBB); 2982 break; 2983 case Intrinsic::experimental_gc_statepoint: 2984 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2985 break; 2986 case Intrinsic::wasm_rethrow: { 2987 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2988 // special because it can be invoked, so we manually lower it to a DAG 2989 // node here. 2990 SmallVector<SDValue, 8> Ops; 2991 Ops.push_back(getRoot()); // inchain 2992 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2993 Ops.push_back( 2994 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2995 TLI.getPointerTy(DAG.getDataLayout()))); 2996 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2997 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2998 break; 2999 } 3000 } 3001 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3002 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3003 // Eventually we will support lowering the @llvm.experimental.deoptimize 3004 // intrinsic, and right now there are no plans to support other intrinsics 3005 // with deopt state. 3006 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3007 } else { 3008 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3009 } 3010 3011 // If the value of the invoke is used outside of its defining block, make it 3012 // available as a virtual register. 3013 // We already took care of the exported value for the statepoint instruction 3014 // during call to the LowerStatepoint. 3015 if (!isa<GCStatepointInst>(I)) { 3016 CopyToExportRegsIfNeeded(&I); 3017 } 3018 3019 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3020 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3021 BranchProbability EHPadBBProb = 3022 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3023 : BranchProbability::getZero(); 3024 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3025 3026 // Update successor info. 3027 addSuccessorWithProb(InvokeMBB, Return); 3028 for (auto &UnwindDest : UnwindDests) { 3029 UnwindDest.first->setIsEHPad(); 3030 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3031 } 3032 InvokeMBB->normalizeSuccProbs(); 3033 3034 // Drop into normal successor. 3035 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3036 DAG.getBasicBlock(Return))); 3037 } 3038 3039 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3040 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3041 3042 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3043 // have to do anything here to lower funclet bundles. 3044 assert(!I.hasOperandBundlesOtherThan( 3045 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3046 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3047 3048 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3049 visitInlineAsm(I); 3050 CopyToExportRegsIfNeeded(&I); 3051 3052 // Retrieve successors. 3053 SmallPtrSet<BasicBlock *, 8> Dests; 3054 Dests.insert(I.getDefaultDest()); 3055 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3056 3057 // Update successor info. 3058 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3059 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3060 BasicBlock *Dest = I.getIndirectDest(i); 3061 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3062 Target->setIsInlineAsmBrIndirectTarget(); 3063 Target->setMachineBlockAddressTaken(); 3064 Target->setLabelMustBeEmitted(); 3065 // Don't add duplicate machine successors. 3066 if (Dests.insert(Dest).second) 3067 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3068 } 3069 CallBrMBB->normalizeSuccProbs(); 3070 3071 // Drop into default successor. 3072 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3073 MVT::Other, getControlRoot(), 3074 DAG.getBasicBlock(Return))); 3075 } 3076 3077 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3078 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3079 } 3080 3081 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3082 assert(FuncInfo.MBB->isEHPad() && 3083 "Call to landingpad not in landing pad!"); 3084 3085 // If there aren't registers to copy the values into (e.g., during SjLj 3086 // exceptions), then don't bother to create these DAG nodes. 3087 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3088 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3089 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3090 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3091 return; 3092 3093 // If landingpad's return type is token type, we don't create DAG nodes 3094 // for its exception pointer and selector value. The extraction of exception 3095 // pointer or selector value from token type landingpads is not currently 3096 // supported. 3097 if (LP.getType()->isTokenTy()) 3098 return; 3099 3100 SmallVector<EVT, 2> ValueVTs; 3101 SDLoc dl = getCurSDLoc(); 3102 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3103 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3104 3105 // Get the two live-in registers as SDValues. The physregs have already been 3106 // copied into virtual registers. 3107 SDValue Ops[2]; 3108 if (FuncInfo.ExceptionPointerVirtReg) { 3109 Ops[0] = DAG.getZExtOrTrunc( 3110 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3111 FuncInfo.ExceptionPointerVirtReg, 3112 TLI.getPointerTy(DAG.getDataLayout())), 3113 dl, ValueVTs[0]); 3114 } else { 3115 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3116 } 3117 Ops[1] = DAG.getZExtOrTrunc( 3118 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3119 FuncInfo.ExceptionSelectorVirtReg, 3120 TLI.getPointerTy(DAG.getDataLayout())), 3121 dl, ValueVTs[1]); 3122 3123 // Merge into one. 3124 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3125 DAG.getVTList(ValueVTs), Ops); 3126 setValue(&LP, Res); 3127 } 3128 3129 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3130 MachineBasicBlock *Last) { 3131 // Update JTCases. 3132 for (JumpTableBlock &JTB : SL->JTCases) 3133 if (JTB.first.HeaderBB == First) 3134 JTB.first.HeaderBB = Last; 3135 3136 // Update BitTestCases. 3137 for (BitTestBlock &BTB : SL->BitTestCases) 3138 if (BTB.Parent == First) 3139 BTB.Parent = Last; 3140 } 3141 3142 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3143 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3144 3145 // Update machine-CFG edges with unique successors. 3146 SmallSet<BasicBlock*, 32> Done; 3147 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3148 BasicBlock *BB = I.getSuccessor(i); 3149 bool Inserted = Done.insert(BB).second; 3150 if (!Inserted) 3151 continue; 3152 3153 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3154 addSuccessorWithProb(IndirectBrMBB, Succ); 3155 } 3156 IndirectBrMBB->normalizeSuccProbs(); 3157 3158 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3159 MVT::Other, getControlRoot(), 3160 getValue(I.getAddress()))); 3161 } 3162 3163 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3164 if (!DAG.getTarget().Options.TrapUnreachable) 3165 return; 3166 3167 // We may be able to ignore unreachable behind a noreturn call. 3168 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3169 const BasicBlock &BB = *I.getParent(); 3170 if (&I != &BB.front()) { 3171 BasicBlock::const_iterator PredI = 3172 std::prev(BasicBlock::const_iterator(&I)); 3173 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3174 if (Call->doesNotReturn()) 3175 return; 3176 } 3177 } 3178 } 3179 3180 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3181 } 3182 3183 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3184 SDNodeFlags Flags; 3185 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3186 Flags.copyFMF(*FPOp); 3187 3188 SDValue Op = getValue(I.getOperand(0)); 3189 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3190 Op, Flags); 3191 setValue(&I, UnNodeValue); 3192 } 3193 3194 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3195 SDNodeFlags Flags; 3196 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3197 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3198 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3199 } 3200 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3201 Flags.setExact(ExactOp->isExact()); 3202 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3203 Flags.copyFMF(*FPOp); 3204 3205 SDValue Op1 = getValue(I.getOperand(0)); 3206 SDValue Op2 = getValue(I.getOperand(1)); 3207 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3208 Op1, Op2, Flags); 3209 setValue(&I, BinNodeValue); 3210 } 3211 3212 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3213 SDValue Op1 = getValue(I.getOperand(0)); 3214 SDValue Op2 = getValue(I.getOperand(1)); 3215 3216 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3217 Op1.getValueType(), DAG.getDataLayout()); 3218 3219 // Coerce the shift amount to the right type if we can. This exposes the 3220 // truncate or zext to optimization early. 3221 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3222 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3223 "Unexpected shift type"); 3224 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3225 } 3226 3227 bool nuw = false; 3228 bool nsw = false; 3229 bool exact = false; 3230 3231 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3232 3233 if (const OverflowingBinaryOperator *OFBinOp = 3234 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3235 nuw = OFBinOp->hasNoUnsignedWrap(); 3236 nsw = OFBinOp->hasNoSignedWrap(); 3237 } 3238 if (const PossiblyExactOperator *ExactOp = 3239 dyn_cast<const PossiblyExactOperator>(&I)) 3240 exact = ExactOp->isExact(); 3241 } 3242 SDNodeFlags Flags; 3243 Flags.setExact(exact); 3244 Flags.setNoSignedWrap(nsw); 3245 Flags.setNoUnsignedWrap(nuw); 3246 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3247 Flags); 3248 setValue(&I, Res); 3249 } 3250 3251 void SelectionDAGBuilder::visitSDiv(const User &I) { 3252 SDValue Op1 = getValue(I.getOperand(0)); 3253 SDValue Op2 = getValue(I.getOperand(1)); 3254 3255 SDNodeFlags Flags; 3256 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3257 cast<PossiblyExactOperator>(&I)->isExact()); 3258 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3259 Op2, Flags)); 3260 } 3261 3262 void SelectionDAGBuilder::visitICmp(const User &I) { 3263 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3264 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3265 predicate = IC->getPredicate(); 3266 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3267 predicate = ICmpInst::Predicate(IC->getPredicate()); 3268 SDValue Op1 = getValue(I.getOperand(0)); 3269 SDValue Op2 = getValue(I.getOperand(1)); 3270 ISD::CondCode Opcode = getICmpCondCode(predicate); 3271 3272 auto &TLI = DAG.getTargetLoweringInfo(); 3273 EVT MemVT = 3274 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3275 3276 // If a pointer's DAG type is larger than its memory type then the DAG values 3277 // are zero-extended. This breaks signed comparisons so truncate back to the 3278 // underlying type before doing the compare. 3279 if (Op1.getValueType() != MemVT) { 3280 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3281 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3282 } 3283 3284 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3285 I.getType()); 3286 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3287 } 3288 3289 void SelectionDAGBuilder::visitFCmp(const User &I) { 3290 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3291 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3292 predicate = FC->getPredicate(); 3293 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3294 predicate = FCmpInst::Predicate(FC->getPredicate()); 3295 SDValue Op1 = getValue(I.getOperand(0)); 3296 SDValue Op2 = getValue(I.getOperand(1)); 3297 3298 ISD::CondCode Condition = getFCmpCondCode(predicate); 3299 auto *FPMO = cast<FPMathOperator>(&I); 3300 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3301 Condition = getFCmpCodeWithoutNaN(Condition); 3302 3303 SDNodeFlags Flags; 3304 Flags.copyFMF(*FPMO); 3305 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3306 3307 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3308 I.getType()); 3309 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3310 } 3311 3312 // Check if the condition of the select has one use or two users that are both 3313 // selects with the same condition. 3314 static bool hasOnlySelectUsers(const Value *Cond) { 3315 return llvm::all_of(Cond->users(), [](const Value *V) { 3316 return isa<SelectInst>(V); 3317 }); 3318 } 3319 3320 void SelectionDAGBuilder::visitSelect(const User &I) { 3321 SmallVector<EVT, 4> ValueVTs; 3322 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3323 ValueVTs); 3324 unsigned NumValues = ValueVTs.size(); 3325 if (NumValues == 0) return; 3326 3327 SmallVector<SDValue, 4> Values(NumValues); 3328 SDValue Cond = getValue(I.getOperand(0)); 3329 SDValue LHSVal = getValue(I.getOperand(1)); 3330 SDValue RHSVal = getValue(I.getOperand(2)); 3331 SmallVector<SDValue, 1> BaseOps(1, Cond); 3332 ISD::NodeType OpCode = 3333 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3334 3335 bool IsUnaryAbs = false; 3336 bool Negate = false; 3337 3338 SDNodeFlags Flags; 3339 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3340 Flags.copyFMF(*FPOp); 3341 3342 // Min/max matching is only viable if all output VTs are the same. 3343 if (all_equal(ValueVTs)) { 3344 EVT VT = ValueVTs[0]; 3345 LLVMContext &Ctx = *DAG.getContext(); 3346 auto &TLI = DAG.getTargetLoweringInfo(); 3347 3348 // We care about the legality of the operation after it has been type 3349 // legalized. 3350 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3351 VT = TLI.getTypeToTransformTo(Ctx, VT); 3352 3353 // If the vselect is legal, assume we want to leave this as a vector setcc + 3354 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3355 // min/max is legal on the scalar type. 3356 bool UseScalarMinMax = VT.isVector() && 3357 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3358 3359 // ValueTracking's select pattern matching does not account for -0.0, 3360 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3361 // -0.0 is less than +0.0. 3362 Value *LHS, *RHS; 3363 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3364 ISD::NodeType Opc = ISD::DELETED_NODE; 3365 switch (SPR.Flavor) { 3366 case SPF_UMAX: Opc = ISD::UMAX; break; 3367 case SPF_UMIN: Opc = ISD::UMIN; break; 3368 case SPF_SMAX: Opc = ISD::SMAX; break; 3369 case SPF_SMIN: Opc = ISD::SMIN; break; 3370 case SPF_FMINNUM: 3371 switch (SPR.NaNBehavior) { 3372 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3373 case SPNB_RETURNS_NAN: break; 3374 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3375 case SPNB_RETURNS_ANY: 3376 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3377 (UseScalarMinMax && 3378 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3379 Opc = ISD::FMINNUM; 3380 break; 3381 } 3382 break; 3383 case SPF_FMAXNUM: 3384 switch (SPR.NaNBehavior) { 3385 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3386 case SPNB_RETURNS_NAN: break; 3387 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3388 case SPNB_RETURNS_ANY: 3389 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3390 (UseScalarMinMax && 3391 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3392 Opc = ISD::FMAXNUM; 3393 break; 3394 } 3395 break; 3396 case SPF_NABS: 3397 Negate = true; 3398 [[fallthrough]]; 3399 case SPF_ABS: 3400 IsUnaryAbs = true; 3401 Opc = ISD::ABS; 3402 break; 3403 default: break; 3404 } 3405 3406 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3407 (TLI.isOperationLegalOrCustom(Opc, VT) || 3408 (UseScalarMinMax && 3409 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3410 // If the underlying comparison instruction is used by any other 3411 // instruction, the consumed instructions won't be destroyed, so it is 3412 // not profitable to convert to a min/max. 3413 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3414 OpCode = Opc; 3415 LHSVal = getValue(LHS); 3416 RHSVal = getValue(RHS); 3417 BaseOps.clear(); 3418 } 3419 3420 if (IsUnaryAbs) { 3421 OpCode = Opc; 3422 LHSVal = getValue(LHS); 3423 BaseOps.clear(); 3424 } 3425 } 3426 3427 if (IsUnaryAbs) { 3428 for (unsigned i = 0; i != NumValues; ++i) { 3429 SDLoc dl = getCurSDLoc(); 3430 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3431 Values[i] = 3432 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3433 if (Negate) 3434 Values[i] = DAG.getNegative(Values[i], dl, VT); 3435 } 3436 } else { 3437 for (unsigned i = 0; i != NumValues; ++i) { 3438 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3439 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3440 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3441 Values[i] = DAG.getNode( 3442 OpCode, getCurSDLoc(), 3443 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3444 } 3445 } 3446 3447 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3448 DAG.getVTList(ValueVTs), Values)); 3449 } 3450 3451 void SelectionDAGBuilder::visitTrunc(const User &I) { 3452 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3453 SDValue N = getValue(I.getOperand(0)); 3454 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3455 I.getType()); 3456 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3457 } 3458 3459 void SelectionDAGBuilder::visitZExt(const User &I) { 3460 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3461 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3462 SDValue N = getValue(I.getOperand(0)); 3463 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3464 I.getType()); 3465 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3466 } 3467 3468 void SelectionDAGBuilder::visitSExt(const User &I) { 3469 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3470 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3471 SDValue N = getValue(I.getOperand(0)); 3472 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3473 I.getType()); 3474 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3475 } 3476 3477 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3478 // FPTrunc is never a no-op cast, no need to check 3479 SDValue N = getValue(I.getOperand(0)); 3480 SDLoc dl = getCurSDLoc(); 3481 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3482 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3483 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3484 DAG.getTargetConstant( 3485 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3486 } 3487 3488 void SelectionDAGBuilder::visitFPExt(const User &I) { 3489 // FPExt is never a no-op cast, no need to check 3490 SDValue N = getValue(I.getOperand(0)); 3491 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3492 I.getType()); 3493 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3494 } 3495 3496 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3497 // FPToUI is never a no-op cast, no need to check 3498 SDValue N = getValue(I.getOperand(0)); 3499 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3500 I.getType()); 3501 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3502 } 3503 3504 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3505 // FPToSI is never a no-op cast, no need to check 3506 SDValue N = getValue(I.getOperand(0)); 3507 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3508 I.getType()); 3509 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3510 } 3511 3512 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3513 // UIToFP is never a no-op cast, no need to check 3514 SDValue N = getValue(I.getOperand(0)); 3515 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3516 I.getType()); 3517 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3518 } 3519 3520 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3521 // SIToFP is never a no-op cast, no need to check 3522 SDValue N = getValue(I.getOperand(0)); 3523 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3524 I.getType()); 3525 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3526 } 3527 3528 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3529 // What to do depends on the size of the integer and the size of the pointer. 3530 // We can either truncate, zero extend, or no-op, accordingly. 3531 SDValue N = getValue(I.getOperand(0)); 3532 auto &TLI = DAG.getTargetLoweringInfo(); 3533 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3534 I.getType()); 3535 EVT PtrMemVT = 3536 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3537 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3538 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3539 setValue(&I, N); 3540 } 3541 3542 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3543 // What to do depends on the size of the integer and the size of the pointer. 3544 // We can either truncate, zero extend, or no-op, accordingly. 3545 SDValue N = getValue(I.getOperand(0)); 3546 auto &TLI = DAG.getTargetLoweringInfo(); 3547 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3548 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3549 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3550 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3551 setValue(&I, N); 3552 } 3553 3554 void SelectionDAGBuilder::visitBitCast(const User &I) { 3555 SDValue N = getValue(I.getOperand(0)); 3556 SDLoc dl = getCurSDLoc(); 3557 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3558 I.getType()); 3559 3560 // BitCast assures us that source and destination are the same size so this is 3561 // either a BITCAST or a no-op. 3562 if (DestVT != N.getValueType()) 3563 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3564 DestVT, N)); // convert types. 3565 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3566 // might fold any kind of constant expression to an integer constant and that 3567 // is not what we are looking for. Only recognize a bitcast of a genuine 3568 // constant integer as an opaque constant. 3569 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3570 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3571 /*isOpaque*/true)); 3572 else 3573 setValue(&I, N); // noop cast. 3574 } 3575 3576 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3577 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3578 const Value *SV = I.getOperand(0); 3579 SDValue N = getValue(SV); 3580 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3581 3582 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3583 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3584 3585 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3586 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3587 3588 setValue(&I, N); 3589 } 3590 3591 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3593 SDValue InVec = getValue(I.getOperand(0)); 3594 SDValue InVal = getValue(I.getOperand(1)); 3595 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3596 TLI.getVectorIdxTy(DAG.getDataLayout())); 3597 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3598 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3599 InVec, InVal, InIdx)); 3600 } 3601 3602 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3603 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3604 SDValue InVec = getValue(I.getOperand(0)); 3605 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3606 TLI.getVectorIdxTy(DAG.getDataLayout())); 3607 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3608 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3609 InVec, InIdx)); 3610 } 3611 3612 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3613 SDValue Src1 = getValue(I.getOperand(0)); 3614 SDValue Src2 = getValue(I.getOperand(1)); 3615 ArrayRef<int> Mask; 3616 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3617 Mask = SVI->getShuffleMask(); 3618 else 3619 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3620 SDLoc DL = getCurSDLoc(); 3621 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3622 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3623 EVT SrcVT = Src1.getValueType(); 3624 3625 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3626 VT.isScalableVector()) { 3627 // Canonical splat form of first element of first input vector. 3628 SDValue FirstElt = 3629 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3630 DAG.getVectorIdxConstant(0, DL)); 3631 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3632 return; 3633 } 3634 3635 // For now, we only handle splats for scalable vectors. 3636 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3637 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3638 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3639 3640 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3641 unsigned MaskNumElts = Mask.size(); 3642 3643 if (SrcNumElts == MaskNumElts) { 3644 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3645 return; 3646 } 3647 3648 // Normalize the shuffle vector since mask and vector length don't match. 3649 if (SrcNumElts < MaskNumElts) { 3650 // Mask is longer than the source vectors. We can use concatenate vector to 3651 // make the mask and vectors lengths match. 3652 3653 if (MaskNumElts % SrcNumElts == 0) { 3654 // Mask length is a multiple of the source vector length. 3655 // Check if the shuffle is some kind of concatenation of the input 3656 // vectors. 3657 unsigned NumConcat = MaskNumElts / SrcNumElts; 3658 bool IsConcat = true; 3659 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3660 for (unsigned i = 0; i != MaskNumElts; ++i) { 3661 int Idx = Mask[i]; 3662 if (Idx < 0) 3663 continue; 3664 // Ensure the indices in each SrcVT sized piece are sequential and that 3665 // the same source is used for the whole piece. 3666 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3667 (ConcatSrcs[i / SrcNumElts] >= 0 && 3668 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3669 IsConcat = false; 3670 break; 3671 } 3672 // Remember which source this index came from. 3673 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3674 } 3675 3676 // The shuffle is concatenating multiple vectors together. Just emit 3677 // a CONCAT_VECTORS operation. 3678 if (IsConcat) { 3679 SmallVector<SDValue, 8> ConcatOps; 3680 for (auto Src : ConcatSrcs) { 3681 if (Src < 0) 3682 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3683 else if (Src == 0) 3684 ConcatOps.push_back(Src1); 3685 else 3686 ConcatOps.push_back(Src2); 3687 } 3688 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3689 return; 3690 } 3691 } 3692 3693 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3694 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3695 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3696 PaddedMaskNumElts); 3697 3698 // Pad both vectors with undefs to make them the same length as the mask. 3699 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3700 3701 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3702 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3703 MOps1[0] = Src1; 3704 MOps2[0] = Src2; 3705 3706 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3707 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3708 3709 // Readjust mask for new input vector length. 3710 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3711 for (unsigned i = 0; i != MaskNumElts; ++i) { 3712 int Idx = Mask[i]; 3713 if (Idx >= (int)SrcNumElts) 3714 Idx -= SrcNumElts - PaddedMaskNumElts; 3715 MappedOps[i] = Idx; 3716 } 3717 3718 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3719 3720 // If the concatenated vector was padded, extract a subvector with the 3721 // correct number of elements. 3722 if (MaskNumElts != PaddedMaskNumElts) 3723 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3724 DAG.getVectorIdxConstant(0, DL)); 3725 3726 setValue(&I, Result); 3727 return; 3728 } 3729 3730 if (SrcNumElts > MaskNumElts) { 3731 // Analyze the access pattern of the vector to see if we can extract 3732 // two subvectors and do the shuffle. 3733 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3734 bool CanExtract = true; 3735 for (int Idx : Mask) { 3736 unsigned Input = 0; 3737 if (Idx < 0) 3738 continue; 3739 3740 if (Idx >= (int)SrcNumElts) { 3741 Input = 1; 3742 Idx -= SrcNumElts; 3743 } 3744 3745 // If all the indices come from the same MaskNumElts sized portion of 3746 // the sources we can use extract. Also make sure the extract wouldn't 3747 // extract past the end of the source. 3748 int NewStartIdx = alignDown(Idx, MaskNumElts); 3749 if (NewStartIdx + MaskNumElts > SrcNumElts || 3750 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3751 CanExtract = false; 3752 // Make sure we always update StartIdx as we use it to track if all 3753 // elements are undef. 3754 StartIdx[Input] = NewStartIdx; 3755 } 3756 3757 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3758 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3759 return; 3760 } 3761 if (CanExtract) { 3762 // Extract appropriate subvector and generate a vector shuffle 3763 for (unsigned Input = 0; Input < 2; ++Input) { 3764 SDValue &Src = Input == 0 ? Src1 : Src2; 3765 if (StartIdx[Input] < 0) 3766 Src = DAG.getUNDEF(VT); 3767 else { 3768 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3769 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3770 } 3771 } 3772 3773 // Calculate new mask. 3774 SmallVector<int, 8> MappedOps(Mask); 3775 for (int &Idx : MappedOps) { 3776 if (Idx >= (int)SrcNumElts) 3777 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3778 else if (Idx >= 0) 3779 Idx -= StartIdx[0]; 3780 } 3781 3782 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3783 return; 3784 } 3785 } 3786 3787 // We can't use either concat vectors or extract subvectors so fall back to 3788 // replacing the shuffle with extract and build vector. 3789 // to insert and build vector. 3790 EVT EltVT = VT.getVectorElementType(); 3791 SmallVector<SDValue,8> Ops; 3792 for (int Idx : Mask) { 3793 SDValue Res; 3794 3795 if (Idx < 0) { 3796 Res = DAG.getUNDEF(EltVT); 3797 } else { 3798 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3799 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3800 3801 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3802 DAG.getVectorIdxConstant(Idx, DL)); 3803 } 3804 3805 Ops.push_back(Res); 3806 } 3807 3808 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3809 } 3810 3811 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3812 ArrayRef<unsigned> Indices = I.getIndices(); 3813 const Value *Op0 = I.getOperand(0); 3814 const Value *Op1 = I.getOperand(1); 3815 Type *AggTy = I.getType(); 3816 Type *ValTy = Op1->getType(); 3817 bool IntoUndef = isa<UndefValue>(Op0); 3818 bool FromUndef = isa<UndefValue>(Op1); 3819 3820 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3821 3822 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3823 SmallVector<EVT, 4> AggValueVTs; 3824 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3825 SmallVector<EVT, 4> ValValueVTs; 3826 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3827 3828 unsigned NumAggValues = AggValueVTs.size(); 3829 unsigned NumValValues = ValValueVTs.size(); 3830 SmallVector<SDValue, 4> Values(NumAggValues); 3831 3832 // Ignore an insertvalue that produces an empty object 3833 if (!NumAggValues) { 3834 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3835 return; 3836 } 3837 3838 SDValue Agg = getValue(Op0); 3839 unsigned i = 0; 3840 // Copy the beginning value(s) from the original aggregate. 3841 for (; i != LinearIndex; ++i) 3842 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3843 SDValue(Agg.getNode(), Agg.getResNo() + i); 3844 // Copy values from the inserted value(s). 3845 if (NumValValues) { 3846 SDValue Val = getValue(Op1); 3847 for (; i != LinearIndex + NumValValues; ++i) 3848 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3849 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3850 } 3851 // Copy remaining value(s) from the original aggregate. 3852 for (; i != NumAggValues; ++i) 3853 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3854 SDValue(Agg.getNode(), Agg.getResNo() + i); 3855 3856 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3857 DAG.getVTList(AggValueVTs), Values)); 3858 } 3859 3860 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3861 ArrayRef<unsigned> Indices = I.getIndices(); 3862 const Value *Op0 = I.getOperand(0); 3863 Type *AggTy = Op0->getType(); 3864 Type *ValTy = I.getType(); 3865 bool OutOfUndef = isa<UndefValue>(Op0); 3866 3867 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3868 3869 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3870 SmallVector<EVT, 4> ValValueVTs; 3871 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3872 3873 unsigned NumValValues = ValValueVTs.size(); 3874 3875 // Ignore a extractvalue that produces an empty object 3876 if (!NumValValues) { 3877 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3878 return; 3879 } 3880 3881 SmallVector<SDValue, 4> Values(NumValValues); 3882 3883 SDValue Agg = getValue(Op0); 3884 // Copy out the selected value(s). 3885 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3886 Values[i - LinearIndex] = 3887 OutOfUndef ? 3888 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3889 SDValue(Agg.getNode(), Agg.getResNo() + i); 3890 3891 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3892 DAG.getVTList(ValValueVTs), Values)); 3893 } 3894 3895 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3896 Value *Op0 = I.getOperand(0); 3897 // Note that the pointer operand may be a vector of pointers. Take the scalar 3898 // element which holds a pointer. 3899 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3900 SDValue N = getValue(Op0); 3901 SDLoc dl = getCurSDLoc(); 3902 auto &TLI = DAG.getTargetLoweringInfo(); 3903 3904 // Normalize Vector GEP - all scalar operands should be converted to the 3905 // splat vector. 3906 bool IsVectorGEP = I.getType()->isVectorTy(); 3907 ElementCount VectorElementCount = 3908 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3909 : ElementCount::getFixed(0); 3910 3911 if (IsVectorGEP && !N.getValueType().isVector()) { 3912 LLVMContext &Context = *DAG.getContext(); 3913 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3914 N = DAG.getSplat(VT, dl, N); 3915 } 3916 3917 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3918 GTI != E; ++GTI) { 3919 const Value *Idx = GTI.getOperand(); 3920 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3921 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3922 if (Field) { 3923 // N = N + Offset 3924 uint64_t Offset = 3925 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3926 3927 // In an inbounds GEP with an offset that is nonnegative even when 3928 // interpreted as signed, assume there is no unsigned overflow. 3929 SDNodeFlags Flags; 3930 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3931 Flags.setNoUnsignedWrap(true); 3932 3933 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3934 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3935 } 3936 } else { 3937 // IdxSize is the width of the arithmetic according to IR semantics. 3938 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3939 // (and fix up the result later). 3940 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3941 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3942 TypeSize ElementSize = 3943 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3944 // We intentionally mask away the high bits here; ElementSize may not 3945 // fit in IdxTy. 3946 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 3947 bool ElementScalable = ElementSize.isScalable(); 3948 3949 // If this is a scalar constant or a splat vector of constants, 3950 // handle it quickly. 3951 const auto *C = dyn_cast<Constant>(Idx); 3952 if (C && isa<VectorType>(C->getType())) 3953 C = C->getSplatValue(); 3954 3955 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3956 if (CI && CI->isZero()) 3957 continue; 3958 if (CI && !ElementScalable) { 3959 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3960 LLVMContext &Context = *DAG.getContext(); 3961 SDValue OffsVal; 3962 if (IsVectorGEP) 3963 OffsVal = DAG.getConstant( 3964 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3965 else 3966 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3967 3968 // In an inbounds GEP with an offset that is nonnegative even when 3969 // interpreted as signed, assume there is no unsigned overflow. 3970 SDNodeFlags Flags; 3971 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3972 Flags.setNoUnsignedWrap(true); 3973 3974 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3975 3976 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3977 continue; 3978 } 3979 3980 // N = N + Idx * ElementMul; 3981 SDValue IdxN = getValue(Idx); 3982 3983 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3984 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3985 VectorElementCount); 3986 IdxN = DAG.getSplat(VT, dl, IdxN); 3987 } 3988 3989 // If the index is smaller or larger than intptr_t, truncate or extend 3990 // it. 3991 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3992 3993 if (ElementScalable) { 3994 EVT VScaleTy = N.getValueType().getScalarType(); 3995 SDValue VScale = DAG.getNode( 3996 ISD::VSCALE, dl, VScaleTy, 3997 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3998 if (IsVectorGEP) 3999 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4000 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4001 } else { 4002 // If this is a multiply by a power of two, turn it into a shl 4003 // immediately. This is a very common case. 4004 if (ElementMul != 1) { 4005 if (ElementMul.isPowerOf2()) { 4006 unsigned Amt = ElementMul.logBase2(); 4007 IdxN = DAG.getNode(ISD::SHL, dl, 4008 N.getValueType(), IdxN, 4009 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4010 } else { 4011 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4012 IdxN.getValueType()); 4013 IdxN = DAG.getNode(ISD::MUL, dl, 4014 N.getValueType(), IdxN, Scale); 4015 } 4016 } 4017 } 4018 4019 N = DAG.getNode(ISD::ADD, dl, 4020 N.getValueType(), N, IdxN); 4021 } 4022 } 4023 4024 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4025 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4026 if (IsVectorGEP) { 4027 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4028 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4029 } 4030 4031 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4032 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4033 4034 setValue(&I, N); 4035 } 4036 4037 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4038 // If this is a fixed sized alloca in the entry block of the function, 4039 // allocate it statically on the stack. 4040 if (FuncInfo.StaticAllocaMap.count(&I)) 4041 return; // getValue will auto-populate this. 4042 4043 SDLoc dl = getCurSDLoc(); 4044 Type *Ty = I.getAllocatedType(); 4045 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4046 auto &DL = DAG.getDataLayout(); 4047 TypeSize TySize = DL.getTypeAllocSize(Ty); 4048 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4049 4050 SDValue AllocSize = getValue(I.getArraySize()); 4051 4052 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4053 if (AllocSize.getValueType() != IntPtr) 4054 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4055 4056 if (TySize.isScalable()) 4057 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4058 DAG.getVScale(dl, IntPtr, 4059 APInt(IntPtr.getScalarSizeInBits(), 4060 TySize.getKnownMinValue()))); 4061 else 4062 AllocSize = 4063 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4064 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4065 4066 // Handle alignment. If the requested alignment is less than or equal to 4067 // the stack alignment, ignore it. If the size is greater than or equal to 4068 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4069 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4070 if (*Alignment <= StackAlign) 4071 Alignment = std::nullopt; 4072 4073 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4074 // Round the size of the allocation up to the stack alignment size 4075 // by add SA-1 to the size. This doesn't overflow because we're computing 4076 // an address inside an alloca. 4077 SDNodeFlags Flags; 4078 Flags.setNoUnsignedWrap(true); 4079 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4080 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4081 4082 // Mask out the low bits for alignment purposes. 4083 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4084 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4085 4086 SDValue Ops[] = { 4087 getRoot(), AllocSize, 4088 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4089 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4090 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4091 setValue(&I, DSA); 4092 DAG.setRoot(DSA.getValue(1)); 4093 4094 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4095 } 4096 4097 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4098 if (I.isAtomic()) 4099 return visitAtomicLoad(I); 4100 4101 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4102 const Value *SV = I.getOperand(0); 4103 if (TLI.supportSwiftError()) { 4104 // Swifterror values can come from either a function parameter with 4105 // swifterror attribute or an alloca with swifterror attribute. 4106 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4107 if (Arg->hasSwiftErrorAttr()) 4108 return visitLoadFromSwiftError(I); 4109 } 4110 4111 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4112 if (Alloca->isSwiftError()) 4113 return visitLoadFromSwiftError(I); 4114 } 4115 } 4116 4117 SDValue Ptr = getValue(SV); 4118 4119 Type *Ty = I.getType(); 4120 SmallVector<EVT, 4> ValueVTs, MemVTs; 4121 SmallVector<uint64_t, 4> Offsets; 4122 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4123 unsigned NumValues = ValueVTs.size(); 4124 if (NumValues == 0) 4125 return; 4126 4127 Align Alignment = I.getAlign(); 4128 AAMDNodes AAInfo = I.getAAMetadata(); 4129 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4130 bool isVolatile = I.isVolatile(); 4131 MachineMemOperand::Flags MMOFlags = 4132 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4133 4134 SDValue Root; 4135 bool ConstantMemory = false; 4136 if (isVolatile) 4137 // Serialize volatile loads with other side effects. 4138 Root = getRoot(); 4139 else if (NumValues > MaxParallelChains) 4140 Root = getMemoryRoot(); 4141 else if (AA && 4142 AA->pointsToConstantMemory(MemoryLocation( 4143 SV, 4144 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4145 AAInfo))) { 4146 // Do not serialize (non-volatile) loads of constant memory with anything. 4147 Root = DAG.getEntryNode(); 4148 ConstantMemory = true; 4149 MMOFlags |= MachineMemOperand::MOInvariant; 4150 } else { 4151 // Do not serialize non-volatile loads against each other. 4152 Root = DAG.getRoot(); 4153 } 4154 4155 SDLoc dl = getCurSDLoc(); 4156 4157 if (isVolatile) 4158 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4159 4160 // An aggregate load cannot wrap around the address space, so offsets to its 4161 // parts don't wrap either. 4162 SDNodeFlags Flags; 4163 Flags.setNoUnsignedWrap(true); 4164 4165 SmallVector<SDValue, 4> Values(NumValues); 4166 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4167 EVT PtrVT = Ptr.getValueType(); 4168 4169 unsigned ChainI = 0; 4170 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4171 // Serializing loads here may result in excessive register pressure, and 4172 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4173 // could recover a bit by hoisting nodes upward in the chain by recognizing 4174 // they are side-effect free or do not alias. The optimizer should really 4175 // avoid this case by converting large object/array copies to llvm.memcpy 4176 // (MaxParallelChains should always remain as failsafe). 4177 if (ChainI == MaxParallelChains) { 4178 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4179 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4180 ArrayRef(Chains.data(), ChainI)); 4181 Root = Chain; 4182 ChainI = 0; 4183 } 4184 SDValue A = DAG.getNode(ISD::ADD, dl, 4185 PtrVT, Ptr, 4186 DAG.getConstant(Offsets[i], dl, PtrVT), 4187 Flags); 4188 4189 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4190 MachinePointerInfo(SV, Offsets[i]), Alignment, 4191 MMOFlags, AAInfo, Ranges); 4192 Chains[ChainI] = L.getValue(1); 4193 4194 if (MemVTs[i] != ValueVTs[i]) 4195 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4196 4197 Values[i] = L; 4198 } 4199 4200 if (!ConstantMemory) { 4201 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4202 ArrayRef(Chains.data(), ChainI)); 4203 if (isVolatile) 4204 DAG.setRoot(Chain); 4205 else 4206 PendingLoads.push_back(Chain); 4207 } 4208 4209 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4210 DAG.getVTList(ValueVTs), Values)); 4211 } 4212 4213 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4214 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4215 "call visitStoreToSwiftError when backend supports swifterror"); 4216 4217 SmallVector<EVT, 4> ValueVTs; 4218 SmallVector<uint64_t, 4> Offsets; 4219 const Value *SrcV = I.getOperand(0); 4220 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4221 SrcV->getType(), ValueVTs, &Offsets); 4222 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4223 "expect a single EVT for swifterror"); 4224 4225 SDValue Src = getValue(SrcV); 4226 // Create a virtual register, then update the virtual register. 4227 Register VReg = 4228 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4229 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4230 // Chain can be getRoot or getControlRoot. 4231 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4232 SDValue(Src.getNode(), Src.getResNo())); 4233 DAG.setRoot(CopyNode); 4234 } 4235 4236 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4237 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4238 "call visitLoadFromSwiftError when backend supports swifterror"); 4239 4240 assert(!I.isVolatile() && 4241 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4242 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4243 "Support volatile, non temporal, invariant for load_from_swift_error"); 4244 4245 const Value *SV = I.getOperand(0); 4246 Type *Ty = I.getType(); 4247 assert( 4248 (!AA || 4249 !AA->pointsToConstantMemory(MemoryLocation( 4250 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4251 I.getAAMetadata()))) && 4252 "load_from_swift_error should not be constant memory"); 4253 4254 SmallVector<EVT, 4> ValueVTs; 4255 SmallVector<uint64_t, 4> Offsets; 4256 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4257 ValueVTs, &Offsets); 4258 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4259 "expect a single EVT for swifterror"); 4260 4261 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4262 SDValue L = DAG.getCopyFromReg( 4263 getRoot(), getCurSDLoc(), 4264 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4265 4266 setValue(&I, L); 4267 } 4268 4269 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4270 if (I.isAtomic()) 4271 return visitAtomicStore(I); 4272 4273 const Value *SrcV = I.getOperand(0); 4274 const Value *PtrV = I.getOperand(1); 4275 4276 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4277 if (TLI.supportSwiftError()) { 4278 // Swifterror values can come from either a function parameter with 4279 // swifterror attribute or an alloca with swifterror attribute. 4280 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4281 if (Arg->hasSwiftErrorAttr()) 4282 return visitStoreToSwiftError(I); 4283 } 4284 4285 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4286 if (Alloca->isSwiftError()) 4287 return visitStoreToSwiftError(I); 4288 } 4289 } 4290 4291 SmallVector<EVT, 4> ValueVTs, MemVTs; 4292 SmallVector<uint64_t, 4> Offsets; 4293 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4294 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4295 unsigned NumValues = ValueVTs.size(); 4296 if (NumValues == 0) 4297 return; 4298 4299 // Get the lowered operands. Note that we do this after 4300 // checking if NumResults is zero, because with zero results 4301 // the operands won't have values in the map. 4302 SDValue Src = getValue(SrcV); 4303 SDValue Ptr = getValue(PtrV); 4304 4305 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4306 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4307 SDLoc dl = getCurSDLoc(); 4308 Align Alignment = I.getAlign(); 4309 AAMDNodes AAInfo = I.getAAMetadata(); 4310 4311 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4312 4313 // An aggregate load cannot wrap around the address space, so offsets to its 4314 // parts don't wrap either. 4315 SDNodeFlags Flags; 4316 Flags.setNoUnsignedWrap(true); 4317 4318 unsigned ChainI = 0; 4319 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4320 // See visitLoad comments. 4321 if (ChainI == MaxParallelChains) { 4322 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4323 ArrayRef(Chains.data(), ChainI)); 4324 Root = Chain; 4325 ChainI = 0; 4326 } 4327 SDValue Add = 4328 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4329 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4330 if (MemVTs[i] != ValueVTs[i]) 4331 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4332 SDValue St = 4333 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4334 Alignment, MMOFlags, AAInfo); 4335 Chains[ChainI] = St; 4336 } 4337 4338 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4339 ArrayRef(Chains.data(), ChainI)); 4340 setValue(&I, StoreNode); 4341 DAG.setRoot(StoreNode); 4342 } 4343 4344 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4345 bool IsCompressing) { 4346 SDLoc sdl = getCurSDLoc(); 4347 4348 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4349 MaybeAlign &Alignment) { 4350 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4351 Src0 = I.getArgOperand(0); 4352 Ptr = I.getArgOperand(1); 4353 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4354 Mask = I.getArgOperand(3); 4355 }; 4356 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4357 MaybeAlign &Alignment) { 4358 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4359 Src0 = I.getArgOperand(0); 4360 Ptr = I.getArgOperand(1); 4361 Mask = I.getArgOperand(2); 4362 Alignment = std::nullopt; 4363 }; 4364 4365 Value *PtrOperand, *MaskOperand, *Src0Operand; 4366 MaybeAlign Alignment; 4367 if (IsCompressing) 4368 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4369 else 4370 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4371 4372 SDValue Ptr = getValue(PtrOperand); 4373 SDValue Src0 = getValue(Src0Operand); 4374 SDValue Mask = getValue(MaskOperand); 4375 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4376 4377 EVT VT = Src0.getValueType(); 4378 if (!Alignment) 4379 Alignment = DAG.getEVTAlign(VT); 4380 4381 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4382 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4383 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4384 SDValue StoreNode = 4385 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4386 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4387 DAG.setRoot(StoreNode); 4388 setValue(&I, StoreNode); 4389 } 4390 4391 // Get a uniform base for the Gather/Scatter intrinsic. 4392 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4393 // We try to represent it as a base pointer + vector of indices. 4394 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4395 // The first operand of the GEP may be a single pointer or a vector of pointers 4396 // Example: 4397 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4398 // or 4399 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4400 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4401 // 4402 // When the first GEP operand is a single pointer - it is the uniform base we 4403 // are looking for. If first operand of the GEP is a splat vector - we 4404 // extract the splat value and use it as a uniform base. 4405 // In all other cases the function returns 'false'. 4406 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4407 ISD::MemIndexType &IndexType, SDValue &Scale, 4408 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4409 uint64_t ElemSize) { 4410 SelectionDAG& DAG = SDB->DAG; 4411 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4412 const DataLayout &DL = DAG.getDataLayout(); 4413 4414 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4415 4416 // Handle splat constant pointer. 4417 if (auto *C = dyn_cast<Constant>(Ptr)) { 4418 C = C->getSplatValue(); 4419 if (!C) 4420 return false; 4421 4422 Base = SDB->getValue(C); 4423 4424 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4425 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4426 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4427 IndexType = ISD::SIGNED_SCALED; 4428 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4429 return true; 4430 } 4431 4432 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4433 if (!GEP || GEP->getParent() != CurBB) 4434 return false; 4435 4436 if (GEP->getNumOperands() != 2) 4437 return false; 4438 4439 const Value *BasePtr = GEP->getPointerOperand(); 4440 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4441 4442 // Make sure the base is scalar and the index is a vector. 4443 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4444 return false; 4445 4446 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4447 4448 // Target may not support the required addressing mode. 4449 if (ScaleVal != 1 && 4450 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4451 return false; 4452 4453 Base = SDB->getValue(BasePtr); 4454 Index = SDB->getValue(IndexVal); 4455 IndexType = ISD::SIGNED_SCALED; 4456 4457 Scale = 4458 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4459 return true; 4460 } 4461 4462 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4463 SDLoc sdl = getCurSDLoc(); 4464 4465 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4466 const Value *Ptr = I.getArgOperand(1); 4467 SDValue Src0 = getValue(I.getArgOperand(0)); 4468 SDValue Mask = getValue(I.getArgOperand(3)); 4469 EVT VT = Src0.getValueType(); 4470 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4471 ->getMaybeAlignValue() 4472 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4473 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4474 4475 SDValue Base; 4476 SDValue Index; 4477 ISD::MemIndexType IndexType; 4478 SDValue Scale; 4479 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4480 I.getParent(), VT.getScalarStoreSize()); 4481 4482 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4483 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4484 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4485 // TODO: Make MachineMemOperands aware of scalable 4486 // vectors. 4487 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4488 if (!UniformBase) { 4489 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4490 Index = getValue(Ptr); 4491 IndexType = ISD::SIGNED_SCALED; 4492 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4493 } 4494 4495 EVT IdxVT = Index.getValueType(); 4496 EVT EltTy = IdxVT.getVectorElementType(); 4497 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4498 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4499 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4500 } 4501 4502 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4503 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4504 Ops, MMO, IndexType, false); 4505 DAG.setRoot(Scatter); 4506 setValue(&I, Scatter); 4507 } 4508 4509 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4510 SDLoc sdl = getCurSDLoc(); 4511 4512 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4513 MaybeAlign &Alignment) { 4514 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4515 Ptr = I.getArgOperand(0); 4516 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4517 Mask = I.getArgOperand(2); 4518 Src0 = I.getArgOperand(3); 4519 }; 4520 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4521 MaybeAlign &Alignment) { 4522 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4523 Ptr = I.getArgOperand(0); 4524 Alignment = std::nullopt; 4525 Mask = I.getArgOperand(1); 4526 Src0 = I.getArgOperand(2); 4527 }; 4528 4529 Value *PtrOperand, *MaskOperand, *Src0Operand; 4530 MaybeAlign Alignment; 4531 if (IsExpanding) 4532 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4533 else 4534 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4535 4536 SDValue Ptr = getValue(PtrOperand); 4537 SDValue Src0 = getValue(Src0Operand); 4538 SDValue Mask = getValue(MaskOperand); 4539 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4540 4541 EVT VT = Src0.getValueType(); 4542 if (!Alignment) 4543 Alignment = DAG.getEVTAlign(VT); 4544 4545 AAMDNodes AAInfo = I.getAAMetadata(); 4546 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4547 4548 // Do not serialize masked loads of constant memory with anything. 4549 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4550 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4551 4552 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4553 4554 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4555 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4556 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4557 4558 SDValue Load = 4559 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4560 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4561 if (AddToChain) 4562 PendingLoads.push_back(Load.getValue(1)); 4563 setValue(&I, Load); 4564 } 4565 4566 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4567 SDLoc sdl = getCurSDLoc(); 4568 4569 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4570 const Value *Ptr = I.getArgOperand(0); 4571 SDValue Src0 = getValue(I.getArgOperand(3)); 4572 SDValue Mask = getValue(I.getArgOperand(2)); 4573 4574 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4575 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4576 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4577 ->getMaybeAlignValue() 4578 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4579 4580 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4581 4582 SDValue Root = DAG.getRoot(); 4583 SDValue Base; 4584 SDValue Index; 4585 ISD::MemIndexType IndexType; 4586 SDValue Scale; 4587 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4588 I.getParent(), VT.getScalarStoreSize()); 4589 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4590 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4591 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4592 // TODO: Make MachineMemOperands aware of scalable 4593 // vectors. 4594 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4595 4596 if (!UniformBase) { 4597 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4598 Index = getValue(Ptr); 4599 IndexType = ISD::SIGNED_SCALED; 4600 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4601 } 4602 4603 EVT IdxVT = Index.getValueType(); 4604 EVT EltTy = IdxVT.getVectorElementType(); 4605 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4606 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4607 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4608 } 4609 4610 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4611 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4612 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4613 4614 PendingLoads.push_back(Gather.getValue(1)); 4615 setValue(&I, Gather); 4616 } 4617 4618 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4619 SDLoc dl = getCurSDLoc(); 4620 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4621 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4622 SyncScope::ID SSID = I.getSyncScopeID(); 4623 4624 SDValue InChain = getRoot(); 4625 4626 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4627 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4628 4629 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4630 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4631 4632 MachineFunction &MF = DAG.getMachineFunction(); 4633 MachineMemOperand *MMO = MF.getMachineMemOperand( 4634 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4635 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4636 FailureOrdering); 4637 4638 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4639 dl, MemVT, VTs, InChain, 4640 getValue(I.getPointerOperand()), 4641 getValue(I.getCompareOperand()), 4642 getValue(I.getNewValOperand()), MMO); 4643 4644 SDValue OutChain = L.getValue(2); 4645 4646 setValue(&I, L); 4647 DAG.setRoot(OutChain); 4648 } 4649 4650 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4651 SDLoc dl = getCurSDLoc(); 4652 ISD::NodeType NT; 4653 switch (I.getOperation()) { 4654 default: llvm_unreachable("Unknown atomicrmw operation"); 4655 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4656 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4657 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4658 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4659 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4660 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4661 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4662 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4663 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4664 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4665 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4666 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4667 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4668 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4669 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4670 case AtomicRMWInst::UIncWrap: 4671 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4672 break; 4673 case AtomicRMWInst::UDecWrap: 4674 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4675 break; 4676 } 4677 AtomicOrdering Ordering = I.getOrdering(); 4678 SyncScope::ID SSID = I.getSyncScopeID(); 4679 4680 SDValue InChain = getRoot(); 4681 4682 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4683 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4684 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4685 4686 MachineFunction &MF = DAG.getMachineFunction(); 4687 MachineMemOperand *MMO = MF.getMachineMemOperand( 4688 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4689 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4690 4691 SDValue L = 4692 DAG.getAtomic(NT, dl, MemVT, InChain, 4693 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4694 MMO); 4695 4696 SDValue OutChain = L.getValue(1); 4697 4698 setValue(&I, L); 4699 DAG.setRoot(OutChain); 4700 } 4701 4702 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4703 SDLoc dl = getCurSDLoc(); 4704 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4705 SDValue Ops[3]; 4706 Ops[0] = getRoot(); 4707 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4708 TLI.getFenceOperandTy(DAG.getDataLayout())); 4709 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4710 TLI.getFenceOperandTy(DAG.getDataLayout())); 4711 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4712 setValue(&I, N); 4713 DAG.setRoot(N); 4714 } 4715 4716 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4717 SDLoc dl = getCurSDLoc(); 4718 AtomicOrdering Order = I.getOrdering(); 4719 SyncScope::ID SSID = I.getSyncScopeID(); 4720 4721 SDValue InChain = getRoot(); 4722 4723 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4724 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4725 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4726 4727 if (!TLI.supportsUnalignedAtomics() && 4728 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4729 report_fatal_error("Cannot generate unaligned atomic load"); 4730 4731 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4732 4733 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4734 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4735 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4736 4737 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4738 4739 SDValue Ptr = getValue(I.getPointerOperand()); 4740 4741 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4742 // TODO: Once this is better exercised by tests, it should be merged with 4743 // the normal path for loads to prevent future divergence. 4744 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4745 if (MemVT != VT) 4746 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4747 4748 setValue(&I, L); 4749 SDValue OutChain = L.getValue(1); 4750 if (!I.isUnordered()) 4751 DAG.setRoot(OutChain); 4752 else 4753 PendingLoads.push_back(OutChain); 4754 return; 4755 } 4756 4757 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4758 Ptr, MMO); 4759 4760 SDValue OutChain = L.getValue(1); 4761 if (MemVT != VT) 4762 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4763 4764 setValue(&I, L); 4765 DAG.setRoot(OutChain); 4766 } 4767 4768 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4769 SDLoc dl = getCurSDLoc(); 4770 4771 AtomicOrdering Ordering = I.getOrdering(); 4772 SyncScope::ID SSID = I.getSyncScopeID(); 4773 4774 SDValue InChain = getRoot(); 4775 4776 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4777 EVT MemVT = 4778 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4779 4780 if (!TLI.supportsUnalignedAtomics() && 4781 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4782 report_fatal_error("Cannot generate unaligned atomic store"); 4783 4784 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4785 4786 MachineFunction &MF = DAG.getMachineFunction(); 4787 MachineMemOperand *MMO = MF.getMachineMemOperand( 4788 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4789 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4790 4791 SDValue Val = getValue(I.getValueOperand()); 4792 if (Val.getValueType() != MemVT) 4793 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4794 SDValue Ptr = getValue(I.getPointerOperand()); 4795 4796 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4797 // TODO: Once this is better exercised by tests, it should be merged with 4798 // the normal path for stores to prevent future divergence. 4799 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4800 setValue(&I, S); 4801 DAG.setRoot(S); 4802 return; 4803 } 4804 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4805 Ptr, Val, MMO); 4806 4807 setValue(&I, OutChain); 4808 DAG.setRoot(OutChain); 4809 } 4810 4811 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4812 /// node. 4813 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4814 unsigned Intrinsic) { 4815 // Ignore the callsite's attributes. A specific call site may be marked with 4816 // readnone, but the lowering code will expect the chain based on the 4817 // definition. 4818 const Function *F = I.getCalledFunction(); 4819 bool HasChain = !F->doesNotAccessMemory(); 4820 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4821 4822 // Build the operand list. 4823 SmallVector<SDValue, 8> Ops; 4824 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4825 if (OnlyLoad) { 4826 // We don't need to serialize loads against other loads. 4827 Ops.push_back(DAG.getRoot()); 4828 } else { 4829 Ops.push_back(getRoot()); 4830 } 4831 } 4832 4833 // Info is set by getTgtMemIntrinsic 4834 TargetLowering::IntrinsicInfo Info; 4835 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4836 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4837 DAG.getMachineFunction(), 4838 Intrinsic); 4839 4840 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4841 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4842 Info.opc == ISD::INTRINSIC_W_CHAIN) 4843 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4844 TLI.getPointerTy(DAG.getDataLayout()))); 4845 4846 // Add all operands of the call to the operand list. 4847 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4848 const Value *Arg = I.getArgOperand(i); 4849 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4850 Ops.push_back(getValue(Arg)); 4851 continue; 4852 } 4853 4854 // Use TargetConstant instead of a regular constant for immarg. 4855 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4856 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4857 assert(CI->getBitWidth() <= 64 && 4858 "large intrinsic immediates not handled"); 4859 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4860 } else { 4861 Ops.push_back( 4862 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4863 } 4864 } 4865 4866 SmallVector<EVT, 4> ValueVTs; 4867 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4868 4869 if (HasChain) 4870 ValueVTs.push_back(MVT::Other); 4871 4872 SDVTList VTs = DAG.getVTList(ValueVTs); 4873 4874 // Propagate fast-math-flags from IR to node(s). 4875 SDNodeFlags Flags; 4876 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4877 Flags.copyFMF(*FPMO); 4878 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4879 4880 // Create the node. 4881 SDValue Result; 4882 // In some cases, custom collection of operands from CallInst I may be needed. 4883 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4884 if (IsTgtIntrinsic) { 4885 // This is target intrinsic that touches memory 4886 // 4887 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4888 // didn't yield anything useful. 4889 MachinePointerInfo MPI; 4890 if (Info.ptrVal) 4891 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4892 else if (Info.fallbackAddressSpace) 4893 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4894 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4895 Info.memVT, MPI, Info.align, Info.flags, 4896 Info.size, I.getAAMetadata()); 4897 } else if (!HasChain) { 4898 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4899 } else if (!I.getType()->isVoidTy()) { 4900 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4901 } else { 4902 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4903 } 4904 4905 if (HasChain) { 4906 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4907 if (OnlyLoad) 4908 PendingLoads.push_back(Chain); 4909 else 4910 DAG.setRoot(Chain); 4911 } 4912 4913 if (!I.getType()->isVoidTy()) { 4914 if (!isa<VectorType>(I.getType())) 4915 Result = lowerRangeToAssertZExt(DAG, I, Result); 4916 4917 MaybeAlign Alignment = I.getRetAlign(); 4918 4919 // Insert `assertalign` node if there's an alignment. 4920 if (InsertAssertAlign && Alignment) { 4921 Result = 4922 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4923 } 4924 4925 setValue(&I, Result); 4926 } 4927 } 4928 4929 /// GetSignificand - Get the significand and build it into a floating-point 4930 /// number with exponent of 1: 4931 /// 4932 /// Op = (Op & 0x007fffff) | 0x3f800000; 4933 /// 4934 /// where Op is the hexadecimal representation of floating point value. 4935 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4936 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4937 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4938 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4939 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4940 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4941 } 4942 4943 /// GetExponent - Get the exponent: 4944 /// 4945 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4946 /// 4947 /// where Op is the hexadecimal representation of floating point value. 4948 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4949 const TargetLowering &TLI, const SDLoc &dl) { 4950 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4951 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4952 SDValue t1 = DAG.getNode( 4953 ISD::SRL, dl, MVT::i32, t0, 4954 DAG.getConstant(23, dl, 4955 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4956 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4957 DAG.getConstant(127, dl, MVT::i32)); 4958 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4959 } 4960 4961 /// getF32Constant - Get 32-bit floating point constant. 4962 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4963 const SDLoc &dl) { 4964 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4965 MVT::f32); 4966 } 4967 4968 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4969 SelectionDAG &DAG) { 4970 // TODO: What fast-math-flags should be set on the floating-point nodes? 4971 4972 // IntegerPartOfX = ((int32_t)(t0); 4973 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4974 4975 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4976 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4977 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4978 4979 // IntegerPartOfX <<= 23; 4980 IntegerPartOfX = 4981 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4982 DAG.getConstant(23, dl, 4983 DAG.getTargetLoweringInfo().getShiftAmountTy( 4984 MVT::i32, DAG.getDataLayout()))); 4985 4986 SDValue TwoToFractionalPartOfX; 4987 if (LimitFloatPrecision <= 6) { 4988 // For floating-point precision of 6: 4989 // 4990 // TwoToFractionalPartOfX = 4991 // 0.997535578f + 4992 // (0.735607626f + 0.252464424f * x) * x; 4993 // 4994 // error 0.0144103317, which is 6 bits 4995 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4996 getF32Constant(DAG, 0x3e814304, dl)); 4997 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4998 getF32Constant(DAG, 0x3f3c50c8, dl)); 4999 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5000 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5001 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5002 } else if (LimitFloatPrecision <= 12) { 5003 // For floating-point precision of 12: 5004 // 5005 // TwoToFractionalPartOfX = 5006 // 0.999892986f + 5007 // (0.696457318f + 5008 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5009 // 5010 // error 0.000107046256, which is 13 to 14 bits 5011 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5012 getF32Constant(DAG, 0x3da235e3, dl)); 5013 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5014 getF32Constant(DAG, 0x3e65b8f3, dl)); 5015 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5016 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5017 getF32Constant(DAG, 0x3f324b07, dl)); 5018 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5019 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5020 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5021 } else { // LimitFloatPrecision <= 18 5022 // For floating-point precision of 18: 5023 // 5024 // TwoToFractionalPartOfX = 5025 // 0.999999982f + 5026 // (0.693148872f + 5027 // (0.240227044f + 5028 // (0.554906021e-1f + 5029 // (0.961591928e-2f + 5030 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5031 // error 2.47208000*10^(-7), which is better than 18 bits 5032 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5033 getF32Constant(DAG, 0x3924b03e, dl)); 5034 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5035 getF32Constant(DAG, 0x3ab24b87, dl)); 5036 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5037 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5038 getF32Constant(DAG, 0x3c1d8c17, dl)); 5039 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5040 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5041 getF32Constant(DAG, 0x3d634a1d, dl)); 5042 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5043 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5044 getF32Constant(DAG, 0x3e75fe14, dl)); 5045 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5046 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5047 getF32Constant(DAG, 0x3f317234, dl)); 5048 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5049 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5050 getF32Constant(DAG, 0x3f800000, dl)); 5051 } 5052 5053 // Add the exponent into the result in integer domain. 5054 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5055 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5056 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5057 } 5058 5059 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5060 /// limited-precision mode. 5061 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5062 const TargetLowering &TLI, SDNodeFlags Flags) { 5063 if (Op.getValueType() == MVT::f32 && 5064 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5065 5066 // Put the exponent in the right bit position for later addition to the 5067 // final result: 5068 // 5069 // t0 = Op * log2(e) 5070 5071 // TODO: What fast-math-flags should be set here? 5072 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5073 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5074 return getLimitedPrecisionExp2(t0, dl, DAG); 5075 } 5076 5077 // No special expansion. 5078 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5079 } 5080 5081 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5082 /// limited-precision mode. 5083 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5084 const TargetLowering &TLI, SDNodeFlags Flags) { 5085 // TODO: What fast-math-flags should be set on the floating-point nodes? 5086 5087 if (Op.getValueType() == MVT::f32 && 5088 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5089 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5090 5091 // Scale the exponent by log(2). 5092 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5093 SDValue LogOfExponent = 5094 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5095 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5096 5097 // Get the significand and build it into a floating-point number with 5098 // exponent of 1. 5099 SDValue X = GetSignificand(DAG, Op1, dl); 5100 5101 SDValue LogOfMantissa; 5102 if (LimitFloatPrecision <= 6) { 5103 // For floating-point precision of 6: 5104 // 5105 // LogofMantissa = 5106 // -1.1609546f + 5107 // (1.4034025f - 0.23903021f * x) * x; 5108 // 5109 // error 0.0034276066, which is better than 8 bits 5110 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5111 getF32Constant(DAG, 0xbe74c456, dl)); 5112 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5113 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5114 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5115 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5116 getF32Constant(DAG, 0x3f949a29, dl)); 5117 } else if (LimitFloatPrecision <= 12) { 5118 // For floating-point precision of 12: 5119 // 5120 // LogOfMantissa = 5121 // -1.7417939f + 5122 // (2.8212026f + 5123 // (-1.4699568f + 5124 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5125 // 5126 // error 0.000061011436, which is 14 bits 5127 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5128 getF32Constant(DAG, 0xbd67b6d6, dl)); 5129 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5130 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5131 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5132 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5133 getF32Constant(DAG, 0x3fbc278b, dl)); 5134 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5135 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5136 getF32Constant(DAG, 0x40348e95, dl)); 5137 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5138 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5139 getF32Constant(DAG, 0x3fdef31a, dl)); 5140 } else { // LimitFloatPrecision <= 18 5141 // For floating-point precision of 18: 5142 // 5143 // LogOfMantissa = 5144 // -2.1072184f + 5145 // (4.2372794f + 5146 // (-3.7029485f + 5147 // (2.2781945f + 5148 // (-0.87823314f + 5149 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5150 // 5151 // error 0.0000023660568, which is better than 18 bits 5152 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5153 getF32Constant(DAG, 0xbc91e5ac, dl)); 5154 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5155 getF32Constant(DAG, 0x3e4350aa, dl)); 5156 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5157 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5158 getF32Constant(DAG, 0x3f60d3e3, dl)); 5159 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5160 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5161 getF32Constant(DAG, 0x4011cdf0, dl)); 5162 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5163 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5164 getF32Constant(DAG, 0x406cfd1c, dl)); 5165 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5166 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5167 getF32Constant(DAG, 0x408797cb, dl)); 5168 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5169 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5170 getF32Constant(DAG, 0x4006dcab, dl)); 5171 } 5172 5173 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5174 } 5175 5176 // No special expansion. 5177 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5178 } 5179 5180 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5181 /// limited-precision mode. 5182 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5183 const TargetLowering &TLI, SDNodeFlags Flags) { 5184 // TODO: What fast-math-flags should be set on the floating-point nodes? 5185 5186 if (Op.getValueType() == MVT::f32 && 5187 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5188 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5189 5190 // Get the exponent. 5191 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5192 5193 // Get the significand and build it into a floating-point number with 5194 // exponent of 1. 5195 SDValue X = GetSignificand(DAG, Op1, dl); 5196 5197 // Different possible minimax approximations of significand in 5198 // floating-point for various degrees of accuracy over [1,2]. 5199 SDValue Log2ofMantissa; 5200 if (LimitFloatPrecision <= 6) { 5201 // For floating-point precision of 6: 5202 // 5203 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5204 // 5205 // error 0.0049451742, which is more than 7 bits 5206 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5207 getF32Constant(DAG, 0xbeb08fe0, dl)); 5208 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5209 getF32Constant(DAG, 0x40019463, dl)); 5210 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5211 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5212 getF32Constant(DAG, 0x3fd6633d, dl)); 5213 } else if (LimitFloatPrecision <= 12) { 5214 // For floating-point precision of 12: 5215 // 5216 // Log2ofMantissa = 5217 // -2.51285454f + 5218 // (4.07009056f + 5219 // (-2.12067489f + 5220 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5221 // 5222 // error 0.0000876136000, which is better than 13 bits 5223 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5224 getF32Constant(DAG, 0xbda7262e, dl)); 5225 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5226 getF32Constant(DAG, 0x3f25280b, dl)); 5227 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5228 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5229 getF32Constant(DAG, 0x4007b923, dl)); 5230 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5231 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5232 getF32Constant(DAG, 0x40823e2f, dl)); 5233 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5234 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5235 getF32Constant(DAG, 0x4020d29c, dl)); 5236 } else { // LimitFloatPrecision <= 18 5237 // For floating-point precision of 18: 5238 // 5239 // Log2ofMantissa = 5240 // -3.0400495f + 5241 // (6.1129976f + 5242 // (-5.3420409f + 5243 // (3.2865683f + 5244 // (-1.2669343f + 5245 // (0.27515199f - 5246 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5247 // 5248 // error 0.0000018516, which is better than 18 bits 5249 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5250 getF32Constant(DAG, 0xbcd2769e, dl)); 5251 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5252 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5253 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5254 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5255 getF32Constant(DAG, 0x3fa22ae7, dl)); 5256 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5257 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5258 getF32Constant(DAG, 0x40525723, dl)); 5259 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5260 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5261 getF32Constant(DAG, 0x40aaf200, dl)); 5262 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5263 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5264 getF32Constant(DAG, 0x40c39dad, dl)); 5265 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5266 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5267 getF32Constant(DAG, 0x4042902c, dl)); 5268 } 5269 5270 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5271 } 5272 5273 // No special expansion. 5274 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5275 } 5276 5277 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5278 /// limited-precision mode. 5279 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5280 const TargetLowering &TLI, SDNodeFlags Flags) { 5281 // TODO: What fast-math-flags should be set on the floating-point nodes? 5282 5283 if (Op.getValueType() == MVT::f32 && 5284 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5285 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5286 5287 // Scale the exponent by log10(2) [0.30102999f]. 5288 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5289 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5290 getF32Constant(DAG, 0x3e9a209a, dl)); 5291 5292 // Get the significand and build it into a floating-point number with 5293 // exponent of 1. 5294 SDValue X = GetSignificand(DAG, Op1, dl); 5295 5296 SDValue Log10ofMantissa; 5297 if (LimitFloatPrecision <= 6) { 5298 // For floating-point precision of 6: 5299 // 5300 // Log10ofMantissa = 5301 // -0.50419619f + 5302 // (0.60948995f - 0.10380950f * x) * x; 5303 // 5304 // error 0.0014886165, which is 6 bits 5305 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5306 getF32Constant(DAG, 0xbdd49a13, dl)); 5307 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5308 getF32Constant(DAG, 0x3f1c0789, dl)); 5309 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5310 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5311 getF32Constant(DAG, 0x3f011300, dl)); 5312 } else if (LimitFloatPrecision <= 12) { 5313 // For floating-point precision of 12: 5314 // 5315 // Log10ofMantissa = 5316 // -0.64831180f + 5317 // (0.91751397f + 5318 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5319 // 5320 // error 0.00019228036, which is better than 12 bits 5321 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5322 getF32Constant(DAG, 0x3d431f31, dl)); 5323 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5324 getF32Constant(DAG, 0x3ea21fb2, dl)); 5325 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5326 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5327 getF32Constant(DAG, 0x3f6ae232, dl)); 5328 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5329 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5330 getF32Constant(DAG, 0x3f25f7c3, dl)); 5331 } else { // LimitFloatPrecision <= 18 5332 // For floating-point precision of 18: 5333 // 5334 // Log10ofMantissa = 5335 // -0.84299375f + 5336 // (1.5327582f + 5337 // (-1.0688956f + 5338 // (0.49102474f + 5339 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5340 // 5341 // error 0.0000037995730, which is better than 18 bits 5342 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5343 getF32Constant(DAG, 0x3c5d51ce, dl)); 5344 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5345 getF32Constant(DAG, 0x3e00685a, dl)); 5346 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5347 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5348 getF32Constant(DAG, 0x3efb6798, dl)); 5349 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5350 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5351 getF32Constant(DAG, 0x3f88d192, dl)); 5352 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5353 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5354 getF32Constant(DAG, 0x3fc4316c, dl)); 5355 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5356 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5357 getF32Constant(DAG, 0x3f57ce70, dl)); 5358 } 5359 5360 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5361 } 5362 5363 // No special expansion. 5364 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5365 } 5366 5367 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5368 /// limited-precision mode. 5369 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5370 const TargetLowering &TLI, SDNodeFlags Flags) { 5371 if (Op.getValueType() == MVT::f32 && 5372 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5373 return getLimitedPrecisionExp2(Op, dl, DAG); 5374 5375 // No special expansion. 5376 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5377 } 5378 5379 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5380 /// limited-precision mode with x == 10.0f. 5381 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5382 SelectionDAG &DAG, const TargetLowering &TLI, 5383 SDNodeFlags Flags) { 5384 bool IsExp10 = false; 5385 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5386 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5387 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5388 APFloat Ten(10.0f); 5389 IsExp10 = LHSC->isExactlyValue(Ten); 5390 } 5391 } 5392 5393 // TODO: What fast-math-flags should be set on the FMUL node? 5394 if (IsExp10) { 5395 // Put the exponent in the right bit position for later addition to the 5396 // final result: 5397 // 5398 // #define LOG2OF10 3.3219281f 5399 // t0 = Op * LOG2OF10; 5400 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5401 getF32Constant(DAG, 0x40549a78, dl)); 5402 return getLimitedPrecisionExp2(t0, dl, DAG); 5403 } 5404 5405 // No special expansion. 5406 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5407 } 5408 5409 /// ExpandPowI - Expand a llvm.powi intrinsic. 5410 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5411 SelectionDAG &DAG) { 5412 // If RHS is a constant, we can expand this out to a multiplication tree if 5413 // it's beneficial on the target, otherwise we end up lowering to a call to 5414 // __powidf2 (for example). 5415 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5416 unsigned Val = RHSC->getSExtValue(); 5417 5418 // powi(x, 0) -> 1.0 5419 if (Val == 0) 5420 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5421 5422 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5423 Val, DAG.shouldOptForSize())) { 5424 // Get the exponent as a positive value. 5425 if ((int)Val < 0) 5426 Val = -Val; 5427 // We use the simple binary decomposition method to generate the multiply 5428 // sequence. There are more optimal ways to do this (for example, 5429 // powi(x,15) generates one more multiply than it should), but this has 5430 // the benefit of being both really simple and much better than a libcall. 5431 SDValue Res; // Logically starts equal to 1.0 5432 SDValue CurSquare = LHS; 5433 // TODO: Intrinsics should have fast-math-flags that propagate to these 5434 // nodes. 5435 while (Val) { 5436 if (Val & 1) { 5437 if (Res.getNode()) 5438 Res = 5439 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5440 else 5441 Res = CurSquare; // 1.0*CurSquare. 5442 } 5443 5444 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5445 CurSquare, CurSquare); 5446 Val >>= 1; 5447 } 5448 5449 // If the original was negative, invert the result, producing 1/(x*x*x). 5450 if (RHSC->getSExtValue() < 0) 5451 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5452 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5453 return Res; 5454 } 5455 } 5456 5457 // Otherwise, expand to a libcall. 5458 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5459 } 5460 5461 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5462 SDValue LHS, SDValue RHS, SDValue Scale, 5463 SelectionDAG &DAG, const TargetLowering &TLI) { 5464 EVT VT = LHS.getValueType(); 5465 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5466 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5467 LLVMContext &Ctx = *DAG.getContext(); 5468 5469 // If the type is legal but the operation isn't, this node might survive all 5470 // the way to operation legalization. If we end up there and we do not have 5471 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5472 // node. 5473 5474 // Coax the legalizer into expanding the node during type legalization instead 5475 // by bumping the size by one bit. This will force it to Promote, enabling the 5476 // early expansion and avoiding the need to expand later. 5477 5478 // We don't have to do this if Scale is 0; that can always be expanded, unless 5479 // it's a saturating signed operation. Those can experience true integer 5480 // division overflow, a case which we must avoid. 5481 5482 // FIXME: We wouldn't have to do this (or any of the early 5483 // expansion/promotion) if it was possible to expand a libcall of an 5484 // illegal type during operation legalization. But it's not, so things 5485 // get a bit hacky. 5486 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5487 if ((ScaleInt > 0 || (Saturating && Signed)) && 5488 (TLI.isTypeLegal(VT) || 5489 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5490 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5491 Opcode, VT, ScaleInt); 5492 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5493 EVT PromVT; 5494 if (VT.isScalarInteger()) 5495 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5496 else if (VT.isVector()) { 5497 PromVT = VT.getVectorElementType(); 5498 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5499 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5500 } else 5501 llvm_unreachable("Wrong VT for DIVFIX?"); 5502 if (Signed) { 5503 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5504 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5505 } else { 5506 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5507 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5508 } 5509 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5510 // For saturating operations, we need to shift up the LHS to get the 5511 // proper saturation width, and then shift down again afterwards. 5512 if (Saturating) 5513 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5514 DAG.getConstant(1, DL, ShiftTy)); 5515 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5516 if (Saturating) 5517 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5518 DAG.getConstant(1, DL, ShiftTy)); 5519 return DAG.getZExtOrTrunc(Res, DL, VT); 5520 } 5521 } 5522 5523 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5524 } 5525 5526 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5527 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5528 static void 5529 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5530 const SDValue &N) { 5531 switch (N.getOpcode()) { 5532 case ISD::CopyFromReg: { 5533 SDValue Op = N.getOperand(1); 5534 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5535 Op.getValueType().getSizeInBits()); 5536 return; 5537 } 5538 case ISD::BITCAST: 5539 case ISD::AssertZext: 5540 case ISD::AssertSext: 5541 case ISD::TRUNCATE: 5542 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5543 return; 5544 case ISD::BUILD_PAIR: 5545 case ISD::BUILD_VECTOR: 5546 case ISD::CONCAT_VECTORS: 5547 for (SDValue Op : N->op_values()) 5548 getUnderlyingArgRegs(Regs, Op); 5549 return; 5550 default: 5551 return; 5552 } 5553 } 5554 5555 /// If the DbgValueInst is a dbg_value of a function argument, create the 5556 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5557 /// instruction selection, they will be inserted to the entry BB. 5558 /// We don't currently support this for variadic dbg_values, as they shouldn't 5559 /// appear for function arguments or in the prologue. 5560 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5561 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5562 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5563 const Argument *Arg = dyn_cast<Argument>(V); 5564 if (!Arg) 5565 return false; 5566 5567 MachineFunction &MF = DAG.getMachineFunction(); 5568 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5569 5570 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5571 // we've been asked to pursue. 5572 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5573 bool Indirect) { 5574 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5575 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5576 // pointing at the VReg, which will be patched up later. 5577 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5578 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5579 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5580 /* isKill */ false, /* isDead */ false, 5581 /* isUndef */ false, /* isEarlyClobber */ false, 5582 /* SubReg */ 0, /* isDebug */ true)}); 5583 5584 auto *NewDIExpr = FragExpr; 5585 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5586 // the DIExpression. 5587 if (Indirect) 5588 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5589 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5590 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5591 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5592 } else { 5593 // Create a completely standard DBG_VALUE. 5594 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5595 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5596 } 5597 }; 5598 5599 if (Kind == FuncArgumentDbgValueKind::Value) { 5600 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5601 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5602 // the entry block. 5603 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5604 if (!IsInEntryBlock) 5605 return false; 5606 5607 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5608 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5609 // variable that also is a param. 5610 // 5611 // Although, if we are at the top of the entry block already, we can still 5612 // emit using ArgDbgValue. This might catch some situations when the 5613 // dbg.value refers to an argument that isn't used in the entry block, so 5614 // any CopyToReg node would be optimized out and the only way to express 5615 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5616 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5617 // we should only emit as ArgDbgValue if the Variable is an argument to the 5618 // current function, and the dbg.value intrinsic is found in the entry 5619 // block. 5620 bool VariableIsFunctionInputArg = Variable->isParameter() && 5621 !DL->getInlinedAt(); 5622 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5623 if (!IsInPrologue && !VariableIsFunctionInputArg) 5624 return false; 5625 5626 // Here we assume that a function argument on IR level only can be used to 5627 // describe one input parameter on source level. If we for example have 5628 // source code like this 5629 // 5630 // struct A { long x, y; }; 5631 // void foo(struct A a, long b) { 5632 // ... 5633 // b = a.x; 5634 // ... 5635 // } 5636 // 5637 // and IR like this 5638 // 5639 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5640 // entry: 5641 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5642 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5643 // call void @llvm.dbg.value(metadata i32 %b, "b", 5644 // ... 5645 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5646 // ... 5647 // 5648 // then the last dbg.value is describing a parameter "b" using a value that 5649 // is an argument. But since we already has used %a1 to describe a parameter 5650 // we should not handle that last dbg.value here (that would result in an 5651 // incorrect hoisting of the DBG_VALUE to the function entry). 5652 // Notice that we allow one dbg.value per IR level argument, to accommodate 5653 // for the situation with fragments above. 5654 if (VariableIsFunctionInputArg) { 5655 unsigned ArgNo = Arg->getArgNo(); 5656 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5657 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5658 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5659 return false; 5660 FuncInfo.DescribedArgs.set(ArgNo); 5661 } 5662 } 5663 5664 bool IsIndirect = false; 5665 std::optional<MachineOperand> Op; 5666 // Some arguments' frame index is recorded during argument lowering. 5667 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5668 if (FI != std::numeric_limits<int>::max()) 5669 Op = MachineOperand::CreateFI(FI); 5670 5671 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5672 if (!Op && N.getNode()) { 5673 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5674 Register Reg; 5675 if (ArgRegsAndSizes.size() == 1) 5676 Reg = ArgRegsAndSizes.front().first; 5677 5678 if (Reg && Reg.isVirtual()) { 5679 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5680 Register PR = RegInfo.getLiveInPhysReg(Reg); 5681 if (PR) 5682 Reg = PR; 5683 } 5684 if (Reg) { 5685 Op = MachineOperand::CreateReg(Reg, false); 5686 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5687 } 5688 } 5689 5690 if (!Op && N.getNode()) { 5691 // Check if frame index is available. 5692 SDValue LCandidate = peekThroughBitcasts(N); 5693 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5694 if (FrameIndexSDNode *FINode = 5695 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5696 Op = MachineOperand::CreateFI(FINode->getIndex()); 5697 } 5698 5699 if (!Op) { 5700 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5701 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5702 SplitRegs) { 5703 unsigned Offset = 0; 5704 for (const auto &RegAndSize : SplitRegs) { 5705 // If the expression is already a fragment, the current register 5706 // offset+size might extend beyond the fragment. In this case, only 5707 // the register bits that are inside the fragment are relevant. 5708 int RegFragmentSizeInBits = RegAndSize.second; 5709 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5710 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5711 // The register is entirely outside the expression fragment, 5712 // so is irrelevant for debug info. 5713 if (Offset >= ExprFragmentSizeInBits) 5714 break; 5715 // The register is partially outside the expression fragment, only 5716 // the low bits within the fragment are relevant for debug info. 5717 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5718 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5719 } 5720 } 5721 5722 auto FragmentExpr = DIExpression::createFragmentExpression( 5723 Expr, Offset, RegFragmentSizeInBits); 5724 Offset += RegAndSize.second; 5725 // If a valid fragment expression cannot be created, the variable's 5726 // correct value cannot be determined and so it is set as Undef. 5727 if (!FragmentExpr) { 5728 SDDbgValue *SDV = DAG.getConstantDbgValue( 5729 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5730 DAG.AddDbgValue(SDV, false); 5731 continue; 5732 } 5733 MachineInstr *NewMI = 5734 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5735 Kind != FuncArgumentDbgValueKind::Value); 5736 FuncInfo.ArgDbgValues.push_back(NewMI); 5737 } 5738 }; 5739 5740 // Check if ValueMap has reg number. 5741 DenseMap<const Value *, Register>::const_iterator 5742 VMI = FuncInfo.ValueMap.find(V); 5743 if (VMI != FuncInfo.ValueMap.end()) { 5744 const auto &TLI = DAG.getTargetLoweringInfo(); 5745 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5746 V->getType(), std::nullopt); 5747 if (RFV.occupiesMultipleRegs()) { 5748 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5749 return true; 5750 } 5751 5752 Op = MachineOperand::CreateReg(VMI->second, false); 5753 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5754 } else if (ArgRegsAndSizes.size() > 1) { 5755 // This was split due to the calling convention, and no virtual register 5756 // mapping exists for the value. 5757 splitMultiRegDbgValue(ArgRegsAndSizes); 5758 return true; 5759 } 5760 } 5761 5762 if (!Op) 5763 return false; 5764 5765 assert(Variable->isValidLocationForIntrinsic(DL) && 5766 "Expected inlined-at fields to agree"); 5767 MachineInstr *NewMI = nullptr; 5768 5769 if (Op->isReg()) 5770 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5771 else 5772 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5773 Variable, Expr); 5774 5775 // Otherwise, use ArgDbgValues. 5776 FuncInfo.ArgDbgValues.push_back(NewMI); 5777 return true; 5778 } 5779 5780 /// Return the appropriate SDDbgValue based on N. 5781 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5782 DILocalVariable *Variable, 5783 DIExpression *Expr, 5784 const DebugLoc &dl, 5785 unsigned DbgSDNodeOrder) { 5786 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5787 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5788 // stack slot locations. 5789 // 5790 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5791 // debug values here after optimization: 5792 // 5793 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5794 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5795 // 5796 // Both describe the direct values of their associated variables. 5797 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5798 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5799 } 5800 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5801 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5802 } 5803 5804 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5805 switch (Intrinsic) { 5806 case Intrinsic::smul_fix: 5807 return ISD::SMULFIX; 5808 case Intrinsic::umul_fix: 5809 return ISD::UMULFIX; 5810 case Intrinsic::smul_fix_sat: 5811 return ISD::SMULFIXSAT; 5812 case Intrinsic::umul_fix_sat: 5813 return ISD::UMULFIXSAT; 5814 case Intrinsic::sdiv_fix: 5815 return ISD::SDIVFIX; 5816 case Intrinsic::udiv_fix: 5817 return ISD::UDIVFIX; 5818 case Intrinsic::sdiv_fix_sat: 5819 return ISD::SDIVFIXSAT; 5820 case Intrinsic::udiv_fix_sat: 5821 return ISD::UDIVFIXSAT; 5822 default: 5823 llvm_unreachable("Unhandled fixed point intrinsic"); 5824 } 5825 } 5826 5827 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5828 const char *FunctionName) { 5829 assert(FunctionName && "FunctionName must not be nullptr"); 5830 SDValue Callee = DAG.getExternalSymbol( 5831 FunctionName, 5832 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5833 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5834 } 5835 5836 /// Given a @llvm.call.preallocated.setup, return the corresponding 5837 /// preallocated call. 5838 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5839 assert(cast<CallBase>(PreallocatedSetup) 5840 ->getCalledFunction() 5841 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5842 "expected call_preallocated_setup Value"); 5843 for (const auto *U : PreallocatedSetup->users()) { 5844 auto *UseCall = cast<CallBase>(U); 5845 const Function *Fn = UseCall->getCalledFunction(); 5846 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5847 return UseCall; 5848 } 5849 } 5850 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5851 } 5852 5853 /// Lower the call to the specified intrinsic function. 5854 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5855 unsigned Intrinsic) { 5856 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5857 SDLoc sdl = getCurSDLoc(); 5858 DebugLoc dl = getCurDebugLoc(); 5859 SDValue Res; 5860 5861 SDNodeFlags Flags; 5862 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5863 Flags.copyFMF(*FPOp); 5864 5865 switch (Intrinsic) { 5866 default: 5867 // By default, turn this into a target intrinsic node. 5868 visitTargetIntrinsic(I, Intrinsic); 5869 return; 5870 case Intrinsic::vscale: { 5871 match(&I, m_VScale(DAG.getDataLayout())); 5872 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5873 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5874 return; 5875 } 5876 case Intrinsic::vastart: visitVAStart(I); return; 5877 case Intrinsic::vaend: visitVAEnd(I); return; 5878 case Intrinsic::vacopy: visitVACopy(I); return; 5879 case Intrinsic::returnaddress: 5880 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5881 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5882 getValue(I.getArgOperand(0)))); 5883 return; 5884 case Intrinsic::addressofreturnaddress: 5885 setValue(&I, 5886 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5887 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5888 return; 5889 case Intrinsic::sponentry: 5890 setValue(&I, 5891 DAG.getNode(ISD::SPONENTRY, sdl, 5892 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5893 return; 5894 case Intrinsic::frameaddress: 5895 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5896 TLI.getFrameIndexTy(DAG.getDataLayout()), 5897 getValue(I.getArgOperand(0)))); 5898 return; 5899 case Intrinsic::read_volatile_register: 5900 case Intrinsic::read_register: { 5901 Value *Reg = I.getArgOperand(0); 5902 SDValue Chain = getRoot(); 5903 SDValue RegName = 5904 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5905 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5906 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5907 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5908 setValue(&I, Res); 5909 DAG.setRoot(Res.getValue(1)); 5910 return; 5911 } 5912 case Intrinsic::write_register: { 5913 Value *Reg = I.getArgOperand(0); 5914 Value *RegValue = I.getArgOperand(1); 5915 SDValue Chain = getRoot(); 5916 SDValue RegName = 5917 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5918 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5919 RegName, getValue(RegValue))); 5920 return; 5921 } 5922 case Intrinsic::memcpy: { 5923 const auto &MCI = cast<MemCpyInst>(I); 5924 SDValue Op1 = getValue(I.getArgOperand(0)); 5925 SDValue Op2 = getValue(I.getArgOperand(1)); 5926 SDValue Op3 = getValue(I.getArgOperand(2)); 5927 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5928 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5929 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5930 Align Alignment = std::min(DstAlign, SrcAlign); 5931 bool isVol = MCI.isVolatile(); 5932 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5933 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5934 // node. 5935 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5936 SDValue MC = DAG.getMemcpy( 5937 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5938 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5939 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5940 updateDAGForMaybeTailCall(MC); 5941 return; 5942 } 5943 case Intrinsic::memcpy_inline: { 5944 const auto &MCI = cast<MemCpyInlineInst>(I); 5945 SDValue Dst = getValue(I.getArgOperand(0)); 5946 SDValue Src = getValue(I.getArgOperand(1)); 5947 SDValue Size = getValue(I.getArgOperand(2)); 5948 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5949 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5950 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5951 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5952 Align Alignment = std::min(DstAlign, SrcAlign); 5953 bool isVol = MCI.isVolatile(); 5954 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5955 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5956 // node. 5957 SDValue MC = DAG.getMemcpy( 5958 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5959 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5960 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5961 updateDAGForMaybeTailCall(MC); 5962 return; 5963 } 5964 case Intrinsic::memset: { 5965 const auto &MSI = cast<MemSetInst>(I); 5966 SDValue Op1 = getValue(I.getArgOperand(0)); 5967 SDValue Op2 = getValue(I.getArgOperand(1)); 5968 SDValue Op3 = getValue(I.getArgOperand(2)); 5969 // @llvm.memset defines 0 and 1 to both mean no alignment. 5970 Align Alignment = MSI.getDestAlign().valueOrOne(); 5971 bool isVol = MSI.isVolatile(); 5972 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5973 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5974 SDValue MS = DAG.getMemset( 5975 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 5976 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 5977 updateDAGForMaybeTailCall(MS); 5978 return; 5979 } 5980 case Intrinsic::memset_inline: { 5981 const auto &MSII = cast<MemSetInlineInst>(I); 5982 SDValue Dst = getValue(I.getArgOperand(0)); 5983 SDValue Value = getValue(I.getArgOperand(1)); 5984 SDValue Size = getValue(I.getArgOperand(2)); 5985 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 5986 // @llvm.memset defines 0 and 1 to both mean no alignment. 5987 Align DstAlign = MSII.getDestAlign().valueOrOne(); 5988 bool isVol = MSII.isVolatile(); 5989 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5990 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5991 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 5992 /* AlwaysInline */ true, isTC, 5993 MachinePointerInfo(I.getArgOperand(0)), 5994 I.getAAMetadata()); 5995 updateDAGForMaybeTailCall(MC); 5996 return; 5997 } 5998 case Intrinsic::memmove: { 5999 const auto &MMI = cast<MemMoveInst>(I); 6000 SDValue Op1 = getValue(I.getArgOperand(0)); 6001 SDValue Op2 = getValue(I.getArgOperand(1)); 6002 SDValue Op3 = getValue(I.getArgOperand(2)); 6003 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6004 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6005 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6006 Align Alignment = std::min(DstAlign, SrcAlign); 6007 bool isVol = MMI.isVolatile(); 6008 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6009 // FIXME: Support passing different dest/src alignments to the memmove DAG 6010 // node. 6011 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6012 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6013 isTC, MachinePointerInfo(I.getArgOperand(0)), 6014 MachinePointerInfo(I.getArgOperand(1)), 6015 I.getAAMetadata(), AA); 6016 updateDAGForMaybeTailCall(MM); 6017 return; 6018 } 6019 case Intrinsic::memcpy_element_unordered_atomic: { 6020 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6021 SDValue Dst = getValue(MI.getRawDest()); 6022 SDValue Src = getValue(MI.getRawSource()); 6023 SDValue Length = getValue(MI.getLength()); 6024 6025 Type *LengthTy = MI.getLength()->getType(); 6026 unsigned ElemSz = MI.getElementSizeInBytes(); 6027 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6028 SDValue MC = 6029 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6030 isTC, MachinePointerInfo(MI.getRawDest()), 6031 MachinePointerInfo(MI.getRawSource())); 6032 updateDAGForMaybeTailCall(MC); 6033 return; 6034 } 6035 case Intrinsic::memmove_element_unordered_atomic: { 6036 auto &MI = cast<AtomicMemMoveInst>(I); 6037 SDValue Dst = getValue(MI.getRawDest()); 6038 SDValue Src = getValue(MI.getRawSource()); 6039 SDValue Length = getValue(MI.getLength()); 6040 6041 Type *LengthTy = MI.getLength()->getType(); 6042 unsigned ElemSz = MI.getElementSizeInBytes(); 6043 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6044 SDValue MC = 6045 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6046 isTC, MachinePointerInfo(MI.getRawDest()), 6047 MachinePointerInfo(MI.getRawSource())); 6048 updateDAGForMaybeTailCall(MC); 6049 return; 6050 } 6051 case Intrinsic::memset_element_unordered_atomic: { 6052 auto &MI = cast<AtomicMemSetInst>(I); 6053 SDValue Dst = getValue(MI.getRawDest()); 6054 SDValue Val = getValue(MI.getValue()); 6055 SDValue Length = getValue(MI.getLength()); 6056 6057 Type *LengthTy = MI.getLength()->getType(); 6058 unsigned ElemSz = MI.getElementSizeInBytes(); 6059 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6060 SDValue MC = 6061 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6062 isTC, MachinePointerInfo(MI.getRawDest())); 6063 updateDAGForMaybeTailCall(MC); 6064 return; 6065 } 6066 case Intrinsic::call_preallocated_setup: { 6067 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6068 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6069 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6070 getRoot(), SrcValue); 6071 setValue(&I, Res); 6072 DAG.setRoot(Res); 6073 return; 6074 } 6075 case Intrinsic::call_preallocated_arg: { 6076 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6077 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6078 SDValue Ops[3]; 6079 Ops[0] = getRoot(); 6080 Ops[1] = SrcValue; 6081 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6082 MVT::i32); // arg index 6083 SDValue Res = DAG.getNode( 6084 ISD::PREALLOCATED_ARG, sdl, 6085 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6086 setValue(&I, Res); 6087 DAG.setRoot(Res.getValue(1)); 6088 return; 6089 } 6090 case Intrinsic::dbg_addr: 6091 case Intrinsic::dbg_declare: { 6092 // Debug intrinsics are handled seperately in assignment tracking mode. 6093 if (isAssignmentTrackingEnabled(*I.getFunction()->getParent())) 6094 return; 6095 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6096 // they are non-variadic. 6097 const auto &DI = cast<DbgVariableIntrinsic>(I); 6098 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6099 DILocalVariable *Variable = DI.getVariable(); 6100 DIExpression *Expression = DI.getExpression(); 6101 dropDanglingDebugInfo(Variable, Expression); 6102 assert(Variable && "Missing variable"); 6103 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6104 << "\n"); 6105 // Check if address has undef value. 6106 const Value *Address = DI.getVariableLocationOp(0); 6107 if (!Address || isa<UndefValue>(Address) || 6108 (Address->use_empty() && !isa<Argument>(Address))) { 6109 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6110 << " (bad/undef/unused-arg address)\n"); 6111 return; 6112 } 6113 6114 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6115 6116 // Check if this variable can be described by a frame index, typically 6117 // either as a static alloca or a byval parameter. 6118 int FI = std::numeric_limits<int>::max(); 6119 if (const auto *AI = 6120 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6121 if (AI->isStaticAlloca()) { 6122 auto I = FuncInfo.StaticAllocaMap.find(AI); 6123 if (I != FuncInfo.StaticAllocaMap.end()) 6124 FI = I->second; 6125 } 6126 } else if (const auto *Arg = dyn_cast<Argument>( 6127 Address->stripInBoundsConstantOffsets())) { 6128 FI = FuncInfo.getArgumentFrameIndex(Arg); 6129 } 6130 6131 // llvm.dbg.addr is control dependent and always generates indirect 6132 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6133 // the MachineFunction variable table. 6134 if (FI != std::numeric_limits<int>::max()) { 6135 if (Intrinsic == Intrinsic::dbg_addr) { 6136 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6137 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6138 dl, SDNodeOrder); 6139 DAG.AddDbgValue(SDV, isParameter); 6140 } else { 6141 LLVM_DEBUG(dbgs() << "Skipping " << DI 6142 << " (variable info stashed in MF side table)\n"); 6143 } 6144 return; 6145 } 6146 6147 SDValue &N = NodeMap[Address]; 6148 if (!N.getNode() && isa<Argument>(Address)) 6149 // Check unused arguments map. 6150 N = UnusedArgNodeMap[Address]; 6151 SDDbgValue *SDV; 6152 if (N.getNode()) { 6153 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6154 Address = BCI->getOperand(0); 6155 // Parameters are handled specially. 6156 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6157 if (isParameter && FINode) { 6158 // Byval parameter. We have a frame index at this point. 6159 SDV = 6160 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6161 /*IsIndirect*/ true, dl, SDNodeOrder); 6162 } else if (isa<Argument>(Address)) { 6163 // Address is an argument, so try to emit its dbg value using 6164 // virtual register info from the FuncInfo.ValueMap. 6165 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6166 FuncArgumentDbgValueKind::Declare, N); 6167 return; 6168 } else { 6169 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6170 true, dl, SDNodeOrder); 6171 } 6172 DAG.AddDbgValue(SDV, isParameter); 6173 } else { 6174 // If Address is an argument then try to emit its dbg value using 6175 // virtual register info from the FuncInfo.ValueMap. 6176 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6177 FuncArgumentDbgValueKind::Declare, N)) { 6178 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6179 << " (could not emit func-arg dbg_value)\n"); 6180 } 6181 } 6182 return; 6183 } 6184 case Intrinsic::dbg_label: { 6185 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6186 DILabel *Label = DI.getLabel(); 6187 assert(Label && "Missing label"); 6188 6189 SDDbgLabel *SDV; 6190 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6191 DAG.AddDbgLabel(SDV); 6192 return; 6193 } 6194 case Intrinsic::dbg_assign: { 6195 // Debug intrinsics are handled seperately in assignment tracking mode. 6196 assert(isAssignmentTrackingEnabled(*I.getFunction()->getParent()) && 6197 "expected assignment tracking to be enabled"); 6198 return; 6199 } 6200 case Intrinsic::dbg_value: { 6201 // Debug intrinsics are handled seperately in assignment tracking mode. 6202 if (isAssignmentTrackingEnabled(*I.getFunction()->getParent())) 6203 return; 6204 const DbgValueInst &DI = cast<DbgValueInst>(I); 6205 assert(DI.getVariable() && "Missing variable"); 6206 6207 DILocalVariable *Variable = DI.getVariable(); 6208 DIExpression *Expression = DI.getExpression(); 6209 dropDanglingDebugInfo(Variable, Expression); 6210 SmallVector<Value *, 4> Values(DI.getValues()); 6211 if (Values.empty()) 6212 return; 6213 6214 if (llvm::is_contained(Values, nullptr)) 6215 return; 6216 6217 bool IsVariadic = DI.hasArgList(); 6218 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6219 SDNodeOrder, IsVariadic)) 6220 addDanglingDebugInfo(&DI, SDNodeOrder); 6221 return; 6222 } 6223 6224 case Intrinsic::eh_typeid_for: { 6225 // Find the type id for the given typeinfo. 6226 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6227 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6228 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6229 setValue(&I, Res); 6230 return; 6231 } 6232 6233 case Intrinsic::eh_return_i32: 6234 case Intrinsic::eh_return_i64: 6235 DAG.getMachineFunction().setCallsEHReturn(true); 6236 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6237 MVT::Other, 6238 getControlRoot(), 6239 getValue(I.getArgOperand(0)), 6240 getValue(I.getArgOperand(1)))); 6241 return; 6242 case Intrinsic::eh_unwind_init: 6243 DAG.getMachineFunction().setCallsUnwindInit(true); 6244 return; 6245 case Intrinsic::eh_dwarf_cfa: 6246 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6247 TLI.getPointerTy(DAG.getDataLayout()), 6248 getValue(I.getArgOperand(0)))); 6249 return; 6250 case Intrinsic::eh_sjlj_callsite: { 6251 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6252 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6253 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6254 6255 MMI.setCurrentCallSite(CI->getZExtValue()); 6256 return; 6257 } 6258 case Intrinsic::eh_sjlj_functioncontext: { 6259 // Get and store the index of the function context. 6260 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6261 AllocaInst *FnCtx = 6262 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6263 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6264 MFI.setFunctionContextIndex(FI); 6265 return; 6266 } 6267 case Intrinsic::eh_sjlj_setjmp: { 6268 SDValue Ops[2]; 6269 Ops[0] = getRoot(); 6270 Ops[1] = getValue(I.getArgOperand(0)); 6271 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6272 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6273 setValue(&I, Op.getValue(0)); 6274 DAG.setRoot(Op.getValue(1)); 6275 return; 6276 } 6277 case Intrinsic::eh_sjlj_longjmp: 6278 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6279 getRoot(), getValue(I.getArgOperand(0)))); 6280 return; 6281 case Intrinsic::eh_sjlj_setup_dispatch: 6282 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6283 getRoot())); 6284 return; 6285 case Intrinsic::masked_gather: 6286 visitMaskedGather(I); 6287 return; 6288 case Intrinsic::masked_load: 6289 visitMaskedLoad(I); 6290 return; 6291 case Intrinsic::masked_scatter: 6292 visitMaskedScatter(I); 6293 return; 6294 case Intrinsic::masked_store: 6295 visitMaskedStore(I); 6296 return; 6297 case Intrinsic::masked_expandload: 6298 visitMaskedLoad(I, true /* IsExpanding */); 6299 return; 6300 case Intrinsic::masked_compressstore: 6301 visitMaskedStore(I, true /* IsCompressing */); 6302 return; 6303 case Intrinsic::powi: 6304 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6305 getValue(I.getArgOperand(1)), DAG)); 6306 return; 6307 case Intrinsic::log: 6308 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6309 return; 6310 case Intrinsic::log2: 6311 setValue(&I, 6312 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6313 return; 6314 case Intrinsic::log10: 6315 setValue(&I, 6316 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6317 return; 6318 case Intrinsic::exp: 6319 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6320 return; 6321 case Intrinsic::exp2: 6322 setValue(&I, 6323 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6324 return; 6325 case Intrinsic::pow: 6326 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6327 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6328 return; 6329 case Intrinsic::sqrt: 6330 case Intrinsic::fabs: 6331 case Intrinsic::sin: 6332 case Intrinsic::cos: 6333 case Intrinsic::floor: 6334 case Intrinsic::ceil: 6335 case Intrinsic::trunc: 6336 case Intrinsic::rint: 6337 case Intrinsic::nearbyint: 6338 case Intrinsic::round: 6339 case Intrinsic::roundeven: 6340 case Intrinsic::canonicalize: { 6341 unsigned Opcode; 6342 switch (Intrinsic) { 6343 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6344 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6345 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6346 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6347 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6348 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6349 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6350 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6351 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6352 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6353 case Intrinsic::round: Opcode = ISD::FROUND; break; 6354 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6355 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6356 } 6357 6358 setValue(&I, DAG.getNode(Opcode, sdl, 6359 getValue(I.getArgOperand(0)).getValueType(), 6360 getValue(I.getArgOperand(0)), Flags)); 6361 return; 6362 } 6363 case Intrinsic::lround: 6364 case Intrinsic::llround: 6365 case Intrinsic::lrint: 6366 case Intrinsic::llrint: { 6367 unsigned Opcode; 6368 switch (Intrinsic) { 6369 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6370 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6371 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6372 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6373 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6374 } 6375 6376 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6377 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6378 getValue(I.getArgOperand(0)))); 6379 return; 6380 } 6381 case Intrinsic::minnum: 6382 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6383 getValue(I.getArgOperand(0)).getValueType(), 6384 getValue(I.getArgOperand(0)), 6385 getValue(I.getArgOperand(1)), Flags)); 6386 return; 6387 case Intrinsic::maxnum: 6388 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6389 getValue(I.getArgOperand(0)).getValueType(), 6390 getValue(I.getArgOperand(0)), 6391 getValue(I.getArgOperand(1)), Flags)); 6392 return; 6393 case Intrinsic::minimum: 6394 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6395 getValue(I.getArgOperand(0)).getValueType(), 6396 getValue(I.getArgOperand(0)), 6397 getValue(I.getArgOperand(1)), Flags)); 6398 return; 6399 case Intrinsic::maximum: 6400 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6401 getValue(I.getArgOperand(0)).getValueType(), 6402 getValue(I.getArgOperand(0)), 6403 getValue(I.getArgOperand(1)), Flags)); 6404 return; 6405 case Intrinsic::copysign: 6406 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6407 getValue(I.getArgOperand(0)).getValueType(), 6408 getValue(I.getArgOperand(0)), 6409 getValue(I.getArgOperand(1)), Flags)); 6410 return; 6411 case Intrinsic::arithmetic_fence: { 6412 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6413 getValue(I.getArgOperand(0)).getValueType(), 6414 getValue(I.getArgOperand(0)), Flags)); 6415 return; 6416 } 6417 case Intrinsic::fma: 6418 setValue(&I, DAG.getNode( 6419 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6420 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6421 getValue(I.getArgOperand(2)), Flags)); 6422 return; 6423 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6424 case Intrinsic::INTRINSIC: 6425 #include "llvm/IR/ConstrainedOps.def" 6426 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6427 return; 6428 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6429 #include "llvm/IR/VPIntrinsics.def" 6430 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6431 return; 6432 case Intrinsic::fptrunc_round: { 6433 // Get the last argument, the metadata and convert it to an integer in the 6434 // call 6435 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6436 std::optional<RoundingMode> RoundMode = 6437 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6438 6439 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6440 6441 // Propagate fast-math-flags from IR to node(s). 6442 SDNodeFlags Flags; 6443 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6444 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6445 6446 SDValue Result; 6447 Result = DAG.getNode( 6448 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6449 DAG.getTargetConstant((int)*RoundMode, sdl, 6450 TLI.getPointerTy(DAG.getDataLayout()))); 6451 setValue(&I, Result); 6452 6453 return; 6454 } 6455 case Intrinsic::fmuladd: { 6456 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6457 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6458 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6459 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6460 getValue(I.getArgOperand(0)).getValueType(), 6461 getValue(I.getArgOperand(0)), 6462 getValue(I.getArgOperand(1)), 6463 getValue(I.getArgOperand(2)), Flags)); 6464 } else { 6465 // TODO: Intrinsic calls should have fast-math-flags. 6466 SDValue Mul = DAG.getNode( 6467 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6468 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6469 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6470 getValue(I.getArgOperand(0)).getValueType(), 6471 Mul, getValue(I.getArgOperand(2)), Flags); 6472 setValue(&I, Add); 6473 } 6474 return; 6475 } 6476 case Intrinsic::convert_to_fp16: 6477 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6478 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6479 getValue(I.getArgOperand(0)), 6480 DAG.getTargetConstant(0, sdl, 6481 MVT::i32)))); 6482 return; 6483 case Intrinsic::convert_from_fp16: 6484 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6485 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6486 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6487 getValue(I.getArgOperand(0))))); 6488 return; 6489 case Intrinsic::fptosi_sat: { 6490 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6491 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6492 getValue(I.getArgOperand(0)), 6493 DAG.getValueType(VT.getScalarType()))); 6494 return; 6495 } 6496 case Intrinsic::fptoui_sat: { 6497 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6498 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6499 getValue(I.getArgOperand(0)), 6500 DAG.getValueType(VT.getScalarType()))); 6501 return; 6502 } 6503 case Intrinsic::set_rounding: 6504 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6505 {getRoot(), getValue(I.getArgOperand(0))}); 6506 setValue(&I, Res); 6507 DAG.setRoot(Res.getValue(0)); 6508 return; 6509 case Intrinsic::is_fpclass: { 6510 const DataLayout DLayout = DAG.getDataLayout(); 6511 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6512 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6513 unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6514 MachineFunction &MF = DAG.getMachineFunction(); 6515 const Function &F = MF.getFunction(); 6516 SDValue Op = getValue(I.getArgOperand(0)); 6517 SDNodeFlags Flags; 6518 Flags.setNoFPExcept( 6519 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6520 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6521 // expansion can use illegal types. Making expansion early allows 6522 // legalizing these types prior to selection. 6523 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6524 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6525 setValue(&I, Result); 6526 return; 6527 } 6528 6529 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6530 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6531 setValue(&I, V); 6532 return; 6533 } 6534 case Intrinsic::pcmarker: { 6535 SDValue Tmp = getValue(I.getArgOperand(0)); 6536 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6537 return; 6538 } 6539 case Intrinsic::readcyclecounter: { 6540 SDValue Op = getRoot(); 6541 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6542 DAG.getVTList(MVT::i64, MVT::Other), Op); 6543 setValue(&I, Res); 6544 DAG.setRoot(Res.getValue(1)); 6545 return; 6546 } 6547 case Intrinsic::bitreverse: 6548 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6549 getValue(I.getArgOperand(0)).getValueType(), 6550 getValue(I.getArgOperand(0)))); 6551 return; 6552 case Intrinsic::bswap: 6553 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6554 getValue(I.getArgOperand(0)).getValueType(), 6555 getValue(I.getArgOperand(0)))); 6556 return; 6557 case Intrinsic::cttz: { 6558 SDValue Arg = getValue(I.getArgOperand(0)); 6559 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6560 EVT Ty = Arg.getValueType(); 6561 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6562 sdl, Ty, Arg)); 6563 return; 6564 } 6565 case Intrinsic::ctlz: { 6566 SDValue Arg = getValue(I.getArgOperand(0)); 6567 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6568 EVT Ty = Arg.getValueType(); 6569 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6570 sdl, Ty, Arg)); 6571 return; 6572 } 6573 case Intrinsic::ctpop: { 6574 SDValue Arg = getValue(I.getArgOperand(0)); 6575 EVT Ty = Arg.getValueType(); 6576 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6577 return; 6578 } 6579 case Intrinsic::fshl: 6580 case Intrinsic::fshr: { 6581 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6582 SDValue X = getValue(I.getArgOperand(0)); 6583 SDValue Y = getValue(I.getArgOperand(1)); 6584 SDValue Z = getValue(I.getArgOperand(2)); 6585 EVT VT = X.getValueType(); 6586 6587 if (X == Y) { 6588 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6589 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6590 } else { 6591 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6592 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6593 } 6594 return; 6595 } 6596 case Intrinsic::sadd_sat: { 6597 SDValue Op1 = getValue(I.getArgOperand(0)); 6598 SDValue Op2 = getValue(I.getArgOperand(1)); 6599 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6600 return; 6601 } 6602 case Intrinsic::uadd_sat: { 6603 SDValue Op1 = getValue(I.getArgOperand(0)); 6604 SDValue Op2 = getValue(I.getArgOperand(1)); 6605 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6606 return; 6607 } 6608 case Intrinsic::ssub_sat: { 6609 SDValue Op1 = getValue(I.getArgOperand(0)); 6610 SDValue Op2 = getValue(I.getArgOperand(1)); 6611 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6612 return; 6613 } 6614 case Intrinsic::usub_sat: { 6615 SDValue Op1 = getValue(I.getArgOperand(0)); 6616 SDValue Op2 = getValue(I.getArgOperand(1)); 6617 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6618 return; 6619 } 6620 case Intrinsic::sshl_sat: { 6621 SDValue Op1 = getValue(I.getArgOperand(0)); 6622 SDValue Op2 = getValue(I.getArgOperand(1)); 6623 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6624 return; 6625 } 6626 case Intrinsic::ushl_sat: { 6627 SDValue Op1 = getValue(I.getArgOperand(0)); 6628 SDValue Op2 = getValue(I.getArgOperand(1)); 6629 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6630 return; 6631 } 6632 case Intrinsic::smul_fix: 6633 case Intrinsic::umul_fix: 6634 case Intrinsic::smul_fix_sat: 6635 case Intrinsic::umul_fix_sat: { 6636 SDValue Op1 = getValue(I.getArgOperand(0)); 6637 SDValue Op2 = getValue(I.getArgOperand(1)); 6638 SDValue Op3 = getValue(I.getArgOperand(2)); 6639 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6640 Op1.getValueType(), Op1, Op2, Op3)); 6641 return; 6642 } 6643 case Intrinsic::sdiv_fix: 6644 case Intrinsic::udiv_fix: 6645 case Intrinsic::sdiv_fix_sat: 6646 case Intrinsic::udiv_fix_sat: { 6647 SDValue Op1 = getValue(I.getArgOperand(0)); 6648 SDValue Op2 = getValue(I.getArgOperand(1)); 6649 SDValue Op3 = getValue(I.getArgOperand(2)); 6650 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6651 Op1, Op2, Op3, DAG, TLI)); 6652 return; 6653 } 6654 case Intrinsic::smax: { 6655 SDValue Op1 = getValue(I.getArgOperand(0)); 6656 SDValue Op2 = getValue(I.getArgOperand(1)); 6657 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6658 return; 6659 } 6660 case Intrinsic::smin: { 6661 SDValue Op1 = getValue(I.getArgOperand(0)); 6662 SDValue Op2 = getValue(I.getArgOperand(1)); 6663 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6664 return; 6665 } 6666 case Intrinsic::umax: { 6667 SDValue Op1 = getValue(I.getArgOperand(0)); 6668 SDValue Op2 = getValue(I.getArgOperand(1)); 6669 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6670 return; 6671 } 6672 case Intrinsic::umin: { 6673 SDValue Op1 = getValue(I.getArgOperand(0)); 6674 SDValue Op2 = getValue(I.getArgOperand(1)); 6675 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6676 return; 6677 } 6678 case Intrinsic::abs: { 6679 // TODO: Preserve "int min is poison" arg in SDAG? 6680 SDValue Op1 = getValue(I.getArgOperand(0)); 6681 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6682 return; 6683 } 6684 case Intrinsic::stacksave: { 6685 SDValue Op = getRoot(); 6686 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6687 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6688 setValue(&I, Res); 6689 DAG.setRoot(Res.getValue(1)); 6690 return; 6691 } 6692 case Intrinsic::stackrestore: 6693 Res = getValue(I.getArgOperand(0)); 6694 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6695 return; 6696 case Intrinsic::get_dynamic_area_offset: { 6697 SDValue Op = getRoot(); 6698 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6699 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6700 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6701 // target. 6702 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6703 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6704 " intrinsic!"); 6705 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6706 Op); 6707 DAG.setRoot(Op); 6708 setValue(&I, Res); 6709 return; 6710 } 6711 case Intrinsic::stackguard: { 6712 MachineFunction &MF = DAG.getMachineFunction(); 6713 const Module &M = *MF.getFunction().getParent(); 6714 SDValue Chain = getRoot(); 6715 if (TLI.useLoadStackGuardNode()) { 6716 Res = getLoadStackGuard(DAG, sdl, Chain); 6717 } else { 6718 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6719 const Value *Global = TLI.getSDagStackGuard(M); 6720 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6721 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6722 MachinePointerInfo(Global, 0), Align, 6723 MachineMemOperand::MOVolatile); 6724 } 6725 if (TLI.useStackGuardXorFP()) 6726 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6727 DAG.setRoot(Chain); 6728 setValue(&I, Res); 6729 return; 6730 } 6731 case Intrinsic::stackprotector: { 6732 // Emit code into the DAG to store the stack guard onto the stack. 6733 MachineFunction &MF = DAG.getMachineFunction(); 6734 MachineFrameInfo &MFI = MF.getFrameInfo(); 6735 SDValue Src, Chain = getRoot(); 6736 6737 if (TLI.useLoadStackGuardNode()) 6738 Src = getLoadStackGuard(DAG, sdl, Chain); 6739 else 6740 Src = getValue(I.getArgOperand(0)); // The guard's value. 6741 6742 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6743 6744 int FI = FuncInfo.StaticAllocaMap[Slot]; 6745 MFI.setStackProtectorIndex(FI); 6746 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6747 6748 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6749 6750 // Store the stack protector onto the stack. 6751 Res = DAG.getStore( 6752 Chain, sdl, Src, FIN, 6753 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6754 MaybeAlign(), MachineMemOperand::MOVolatile); 6755 setValue(&I, Res); 6756 DAG.setRoot(Res); 6757 return; 6758 } 6759 case Intrinsic::objectsize: 6760 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6761 6762 case Intrinsic::is_constant: 6763 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6764 6765 case Intrinsic::annotation: 6766 case Intrinsic::ptr_annotation: 6767 case Intrinsic::launder_invariant_group: 6768 case Intrinsic::strip_invariant_group: 6769 // Drop the intrinsic, but forward the value 6770 setValue(&I, getValue(I.getOperand(0))); 6771 return; 6772 6773 case Intrinsic::assume: 6774 case Intrinsic::experimental_noalias_scope_decl: 6775 case Intrinsic::var_annotation: 6776 case Intrinsic::sideeffect: 6777 // Discard annotate attributes, noalias scope declarations, assumptions, and 6778 // artificial side-effects. 6779 return; 6780 6781 case Intrinsic::codeview_annotation: { 6782 // Emit a label associated with this metadata. 6783 MachineFunction &MF = DAG.getMachineFunction(); 6784 MCSymbol *Label = 6785 MF.getMMI().getContext().createTempSymbol("annotation", true); 6786 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6787 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6788 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6789 DAG.setRoot(Res); 6790 return; 6791 } 6792 6793 case Intrinsic::init_trampoline: { 6794 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6795 6796 SDValue Ops[6]; 6797 Ops[0] = getRoot(); 6798 Ops[1] = getValue(I.getArgOperand(0)); 6799 Ops[2] = getValue(I.getArgOperand(1)); 6800 Ops[3] = getValue(I.getArgOperand(2)); 6801 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6802 Ops[5] = DAG.getSrcValue(F); 6803 6804 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6805 6806 DAG.setRoot(Res); 6807 return; 6808 } 6809 case Intrinsic::adjust_trampoline: 6810 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6811 TLI.getPointerTy(DAG.getDataLayout()), 6812 getValue(I.getArgOperand(0)))); 6813 return; 6814 case Intrinsic::gcroot: { 6815 assert(DAG.getMachineFunction().getFunction().hasGC() && 6816 "only valid in functions with gc specified, enforced by Verifier"); 6817 assert(GFI && "implied by previous"); 6818 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6819 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6820 6821 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6822 GFI->addStackRoot(FI->getIndex(), TypeMap); 6823 return; 6824 } 6825 case Intrinsic::gcread: 6826 case Intrinsic::gcwrite: 6827 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6828 case Intrinsic::get_rounding: 6829 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6830 setValue(&I, Res); 6831 DAG.setRoot(Res.getValue(1)); 6832 return; 6833 6834 case Intrinsic::expect: 6835 // Just replace __builtin_expect(exp, c) with EXP. 6836 setValue(&I, getValue(I.getArgOperand(0))); 6837 return; 6838 6839 case Intrinsic::ubsantrap: 6840 case Intrinsic::debugtrap: 6841 case Intrinsic::trap: { 6842 StringRef TrapFuncName = 6843 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6844 if (TrapFuncName.empty()) { 6845 switch (Intrinsic) { 6846 case Intrinsic::trap: 6847 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6848 break; 6849 case Intrinsic::debugtrap: 6850 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6851 break; 6852 case Intrinsic::ubsantrap: 6853 DAG.setRoot(DAG.getNode( 6854 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6855 DAG.getTargetConstant( 6856 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6857 MVT::i32))); 6858 break; 6859 default: llvm_unreachable("unknown trap intrinsic"); 6860 } 6861 return; 6862 } 6863 TargetLowering::ArgListTy Args; 6864 if (Intrinsic == Intrinsic::ubsantrap) { 6865 Args.push_back(TargetLoweringBase::ArgListEntry()); 6866 Args[0].Val = I.getArgOperand(0); 6867 Args[0].Node = getValue(Args[0].Val); 6868 Args[0].Ty = Args[0].Val->getType(); 6869 } 6870 6871 TargetLowering::CallLoweringInfo CLI(DAG); 6872 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6873 CallingConv::C, I.getType(), 6874 DAG.getExternalSymbol(TrapFuncName.data(), 6875 TLI.getPointerTy(DAG.getDataLayout())), 6876 std::move(Args)); 6877 6878 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6879 DAG.setRoot(Result.second); 6880 return; 6881 } 6882 6883 case Intrinsic::uadd_with_overflow: 6884 case Intrinsic::sadd_with_overflow: 6885 case Intrinsic::usub_with_overflow: 6886 case Intrinsic::ssub_with_overflow: 6887 case Intrinsic::umul_with_overflow: 6888 case Intrinsic::smul_with_overflow: { 6889 ISD::NodeType Op; 6890 switch (Intrinsic) { 6891 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6892 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6893 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6894 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6895 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6896 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6897 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6898 } 6899 SDValue Op1 = getValue(I.getArgOperand(0)); 6900 SDValue Op2 = getValue(I.getArgOperand(1)); 6901 6902 EVT ResultVT = Op1.getValueType(); 6903 EVT OverflowVT = MVT::i1; 6904 if (ResultVT.isVector()) 6905 OverflowVT = EVT::getVectorVT( 6906 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6907 6908 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6909 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6910 return; 6911 } 6912 case Intrinsic::prefetch: { 6913 SDValue Ops[5]; 6914 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6915 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6916 Ops[0] = DAG.getRoot(); 6917 Ops[1] = getValue(I.getArgOperand(0)); 6918 Ops[2] = getValue(I.getArgOperand(1)); 6919 Ops[3] = getValue(I.getArgOperand(2)); 6920 Ops[4] = getValue(I.getArgOperand(3)); 6921 SDValue Result = DAG.getMemIntrinsicNode( 6922 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6923 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6924 /* align */ std::nullopt, Flags); 6925 6926 // Chain the prefetch in parallell with any pending loads, to stay out of 6927 // the way of later optimizations. 6928 PendingLoads.push_back(Result); 6929 Result = getRoot(); 6930 DAG.setRoot(Result); 6931 return; 6932 } 6933 case Intrinsic::lifetime_start: 6934 case Intrinsic::lifetime_end: { 6935 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6936 // Stack coloring is not enabled in O0, discard region information. 6937 if (TM.getOptLevel() == CodeGenOpt::None) 6938 return; 6939 6940 const int64_t ObjectSize = 6941 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6942 Value *const ObjectPtr = I.getArgOperand(1); 6943 SmallVector<const Value *, 4> Allocas; 6944 getUnderlyingObjects(ObjectPtr, Allocas); 6945 6946 for (const Value *Alloca : Allocas) { 6947 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6948 6949 // Could not find an Alloca. 6950 if (!LifetimeObject) 6951 continue; 6952 6953 // First check that the Alloca is static, otherwise it won't have a 6954 // valid frame index. 6955 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6956 if (SI == FuncInfo.StaticAllocaMap.end()) 6957 return; 6958 6959 const int FrameIndex = SI->second; 6960 int64_t Offset; 6961 if (GetPointerBaseWithConstantOffset( 6962 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6963 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6964 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6965 Offset); 6966 DAG.setRoot(Res); 6967 } 6968 return; 6969 } 6970 case Intrinsic::pseudoprobe: { 6971 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6972 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6973 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6974 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6975 DAG.setRoot(Res); 6976 return; 6977 } 6978 case Intrinsic::invariant_start: 6979 // Discard region information. 6980 setValue(&I, 6981 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6982 return; 6983 case Intrinsic::invariant_end: 6984 // Discard region information. 6985 return; 6986 case Intrinsic::clear_cache: 6987 /// FunctionName may be null. 6988 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6989 lowerCallToExternalSymbol(I, FunctionName); 6990 return; 6991 case Intrinsic::donothing: 6992 case Intrinsic::seh_try_begin: 6993 case Intrinsic::seh_scope_begin: 6994 case Intrinsic::seh_try_end: 6995 case Intrinsic::seh_scope_end: 6996 // ignore 6997 return; 6998 case Intrinsic::experimental_stackmap: 6999 visitStackmap(I); 7000 return; 7001 case Intrinsic::experimental_patchpoint_void: 7002 case Intrinsic::experimental_patchpoint_i64: 7003 visitPatchpoint(I); 7004 return; 7005 case Intrinsic::experimental_gc_statepoint: 7006 LowerStatepoint(cast<GCStatepointInst>(I)); 7007 return; 7008 case Intrinsic::experimental_gc_result: 7009 visitGCResult(cast<GCResultInst>(I)); 7010 return; 7011 case Intrinsic::experimental_gc_relocate: 7012 visitGCRelocate(cast<GCRelocateInst>(I)); 7013 return; 7014 case Intrinsic::instrprof_cover: 7015 llvm_unreachable("instrprof failed to lower a cover"); 7016 case Intrinsic::instrprof_increment: 7017 llvm_unreachable("instrprof failed to lower an increment"); 7018 case Intrinsic::instrprof_value_profile: 7019 llvm_unreachable("instrprof failed to lower a value profiling call"); 7020 case Intrinsic::localescape: { 7021 MachineFunction &MF = DAG.getMachineFunction(); 7022 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7023 7024 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7025 // is the same on all targets. 7026 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7027 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7028 if (isa<ConstantPointerNull>(Arg)) 7029 continue; // Skip null pointers. They represent a hole in index space. 7030 AllocaInst *Slot = cast<AllocaInst>(Arg); 7031 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7032 "can only escape static allocas"); 7033 int FI = FuncInfo.StaticAllocaMap[Slot]; 7034 MCSymbol *FrameAllocSym = 7035 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7036 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7037 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7038 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7039 .addSym(FrameAllocSym) 7040 .addFrameIndex(FI); 7041 } 7042 7043 return; 7044 } 7045 7046 case Intrinsic::localrecover: { 7047 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7048 MachineFunction &MF = DAG.getMachineFunction(); 7049 7050 // Get the symbol that defines the frame offset. 7051 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7052 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7053 unsigned IdxVal = 7054 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7055 MCSymbol *FrameAllocSym = 7056 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7057 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7058 7059 Value *FP = I.getArgOperand(1); 7060 SDValue FPVal = getValue(FP); 7061 EVT PtrVT = FPVal.getValueType(); 7062 7063 // Create a MCSymbol for the label to avoid any target lowering 7064 // that would make this PC relative. 7065 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7066 SDValue OffsetVal = 7067 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7068 7069 // Add the offset to the FP. 7070 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7071 setValue(&I, Add); 7072 7073 return; 7074 } 7075 7076 case Intrinsic::eh_exceptionpointer: 7077 case Intrinsic::eh_exceptioncode: { 7078 // Get the exception pointer vreg, copy from it, and resize it to fit. 7079 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7080 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7081 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7082 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7083 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7084 if (Intrinsic == Intrinsic::eh_exceptioncode) 7085 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7086 setValue(&I, N); 7087 return; 7088 } 7089 case Intrinsic::xray_customevent: { 7090 // Here we want to make sure that the intrinsic behaves as if it has a 7091 // specific calling convention, and only for x86_64. 7092 // FIXME: Support other platforms later. 7093 const auto &Triple = DAG.getTarget().getTargetTriple(); 7094 if (Triple.getArch() != Triple::x86_64) 7095 return; 7096 7097 SmallVector<SDValue, 8> Ops; 7098 7099 // We want to say that we always want the arguments in registers. 7100 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7101 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7102 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7103 SDValue Chain = getRoot(); 7104 Ops.push_back(LogEntryVal); 7105 Ops.push_back(StrSizeVal); 7106 Ops.push_back(Chain); 7107 7108 // We need to enforce the calling convention for the callsite, so that 7109 // argument ordering is enforced correctly, and that register allocation can 7110 // see that some registers may be assumed clobbered and have to preserve 7111 // them across calls to the intrinsic. 7112 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7113 sdl, NodeTys, Ops); 7114 SDValue patchableNode = SDValue(MN, 0); 7115 DAG.setRoot(patchableNode); 7116 setValue(&I, patchableNode); 7117 return; 7118 } 7119 case Intrinsic::xray_typedevent: { 7120 // Here we want to make sure that the intrinsic behaves as if it has a 7121 // specific calling convention, and only for x86_64. 7122 // FIXME: Support other platforms later. 7123 const auto &Triple = DAG.getTarget().getTargetTriple(); 7124 if (Triple.getArch() != Triple::x86_64) 7125 return; 7126 7127 SmallVector<SDValue, 8> Ops; 7128 7129 // We want to say that we always want the arguments in registers. 7130 // It's unclear to me how manipulating the selection DAG here forces callers 7131 // to provide arguments in registers instead of on the stack. 7132 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7133 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7134 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7135 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7136 SDValue Chain = getRoot(); 7137 Ops.push_back(LogTypeId); 7138 Ops.push_back(LogEntryVal); 7139 Ops.push_back(StrSizeVal); 7140 Ops.push_back(Chain); 7141 7142 // We need to enforce the calling convention for the callsite, so that 7143 // argument ordering is enforced correctly, and that register allocation can 7144 // see that some registers may be assumed clobbered and have to preserve 7145 // them across calls to the intrinsic. 7146 MachineSDNode *MN = DAG.getMachineNode( 7147 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7148 SDValue patchableNode = SDValue(MN, 0); 7149 DAG.setRoot(patchableNode); 7150 setValue(&I, patchableNode); 7151 return; 7152 } 7153 case Intrinsic::experimental_deoptimize: 7154 LowerDeoptimizeCall(&I); 7155 return; 7156 case Intrinsic::experimental_stepvector: 7157 visitStepVector(I); 7158 return; 7159 case Intrinsic::vector_reduce_fadd: 7160 case Intrinsic::vector_reduce_fmul: 7161 case Intrinsic::vector_reduce_add: 7162 case Intrinsic::vector_reduce_mul: 7163 case Intrinsic::vector_reduce_and: 7164 case Intrinsic::vector_reduce_or: 7165 case Intrinsic::vector_reduce_xor: 7166 case Intrinsic::vector_reduce_smax: 7167 case Intrinsic::vector_reduce_smin: 7168 case Intrinsic::vector_reduce_umax: 7169 case Intrinsic::vector_reduce_umin: 7170 case Intrinsic::vector_reduce_fmax: 7171 case Intrinsic::vector_reduce_fmin: 7172 visitVectorReduce(I, Intrinsic); 7173 return; 7174 7175 case Intrinsic::icall_branch_funnel: { 7176 SmallVector<SDValue, 16> Ops; 7177 Ops.push_back(getValue(I.getArgOperand(0))); 7178 7179 int64_t Offset; 7180 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7181 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7182 if (!Base) 7183 report_fatal_error( 7184 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7185 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7186 7187 struct BranchFunnelTarget { 7188 int64_t Offset; 7189 SDValue Target; 7190 }; 7191 SmallVector<BranchFunnelTarget, 8> Targets; 7192 7193 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7194 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7195 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7196 if (ElemBase != Base) 7197 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7198 "to the same GlobalValue"); 7199 7200 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7201 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7202 if (!GA) 7203 report_fatal_error( 7204 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7205 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7206 GA->getGlobal(), sdl, Val.getValueType(), 7207 GA->getOffset())}); 7208 } 7209 llvm::sort(Targets, 7210 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7211 return T1.Offset < T2.Offset; 7212 }); 7213 7214 for (auto &T : Targets) { 7215 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7216 Ops.push_back(T.Target); 7217 } 7218 7219 Ops.push_back(DAG.getRoot()); // Chain 7220 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7221 MVT::Other, Ops), 7222 0); 7223 DAG.setRoot(N); 7224 setValue(&I, N); 7225 HasTailCall = true; 7226 return; 7227 } 7228 7229 case Intrinsic::wasm_landingpad_index: 7230 // Information this intrinsic contained has been transferred to 7231 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7232 // delete it now. 7233 return; 7234 7235 case Intrinsic::aarch64_settag: 7236 case Intrinsic::aarch64_settag_zero: { 7237 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7238 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7239 SDValue Val = TSI.EmitTargetCodeForSetTag( 7240 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7241 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7242 ZeroMemory); 7243 DAG.setRoot(Val); 7244 setValue(&I, Val); 7245 return; 7246 } 7247 case Intrinsic::ptrmask: { 7248 SDValue Ptr = getValue(I.getOperand(0)); 7249 SDValue Const = getValue(I.getOperand(1)); 7250 7251 EVT PtrVT = Ptr.getValueType(); 7252 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7253 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7254 return; 7255 } 7256 case Intrinsic::threadlocal_address: { 7257 setValue(&I, getValue(I.getOperand(0))); 7258 return; 7259 } 7260 case Intrinsic::get_active_lane_mask: { 7261 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7262 SDValue Index = getValue(I.getOperand(0)); 7263 EVT ElementVT = Index.getValueType(); 7264 7265 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7266 visitTargetIntrinsic(I, Intrinsic); 7267 return; 7268 } 7269 7270 SDValue TripCount = getValue(I.getOperand(1)); 7271 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7272 7273 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7274 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7275 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7276 SDValue VectorInduction = DAG.getNode( 7277 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7278 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7279 VectorTripCount, ISD::CondCode::SETULT); 7280 setValue(&I, SetCC); 7281 return; 7282 } 7283 case Intrinsic::vector_insert: { 7284 SDValue Vec = getValue(I.getOperand(0)); 7285 SDValue SubVec = getValue(I.getOperand(1)); 7286 SDValue Index = getValue(I.getOperand(2)); 7287 7288 // The intrinsic's index type is i64, but the SDNode requires an index type 7289 // suitable for the target. Convert the index as required. 7290 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7291 if (Index.getValueType() != VectorIdxTy) 7292 Index = DAG.getVectorIdxConstant( 7293 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7294 7295 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7296 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7297 Index)); 7298 return; 7299 } 7300 case Intrinsic::vector_extract: { 7301 SDValue Vec = getValue(I.getOperand(0)); 7302 SDValue Index = getValue(I.getOperand(1)); 7303 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7304 7305 // The intrinsic's index type is i64, but the SDNode requires an index type 7306 // suitable for the target. Convert the index as required. 7307 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7308 if (Index.getValueType() != VectorIdxTy) 7309 Index = DAG.getVectorIdxConstant( 7310 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7311 7312 setValue(&I, 7313 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7314 return; 7315 } 7316 case Intrinsic::experimental_vector_reverse: 7317 visitVectorReverse(I); 7318 return; 7319 case Intrinsic::experimental_vector_splice: 7320 visitVectorSplice(I); 7321 return; 7322 case Intrinsic::callbr_landingpad: 7323 visitCallBrLandingPad(I); 7324 return; 7325 case Intrinsic::experimental_vector_interleave2: 7326 visitVectorInterleave(I); 7327 return; 7328 case Intrinsic::experimental_vector_deinterleave2: 7329 visitVectorDeinterleave(I); 7330 return; 7331 } 7332 } 7333 7334 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7335 const ConstrainedFPIntrinsic &FPI) { 7336 SDLoc sdl = getCurSDLoc(); 7337 7338 // We do not need to serialize constrained FP intrinsics against 7339 // each other or against (nonvolatile) loads, so they can be 7340 // chained like loads. 7341 SDValue Chain = DAG.getRoot(); 7342 SmallVector<SDValue, 4> Opers; 7343 Opers.push_back(Chain); 7344 if (FPI.isUnaryOp()) { 7345 Opers.push_back(getValue(FPI.getArgOperand(0))); 7346 } else if (FPI.isTernaryOp()) { 7347 Opers.push_back(getValue(FPI.getArgOperand(0))); 7348 Opers.push_back(getValue(FPI.getArgOperand(1))); 7349 Opers.push_back(getValue(FPI.getArgOperand(2))); 7350 } else { 7351 Opers.push_back(getValue(FPI.getArgOperand(0))); 7352 Opers.push_back(getValue(FPI.getArgOperand(1))); 7353 } 7354 7355 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7356 assert(Result.getNode()->getNumValues() == 2); 7357 7358 // Push node to the appropriate list so that future instructions can be 7359 // chained up correctly. 7360 SDValue OutChain = Result.getValue(1); 7361 switch (EB) { 7362 case fp::ExceptionBehavior::ebIgnore: 7363 // The only reason why ebIgnore nodes still need to be chained is that 7364 // they might depend on the current rounding mode, and therefore must 7365 // not be moved across instruction that may change that mode. 7366 [[fallthrough]]; 7367 case fp::ExceptionBehavior::ebMayTrap: 7368 // These must not be moved across calls or instructions that may change 7369 // floating-point exception masks. 7370 PendingConstrainedFP.push_back(OutChain); 7371 break; 7372 case fp::ExceptionBehavior::ebStrict: 7373 // These must not be moved across calls or instructions that may change 7374 // floating-point exception masks or read floating-point exception flags. 7375 // In addition, they cannot be optimized out even if unused. 7376 PendingConstrainedFPStrict.push_back(OutChain); 7377 break; 7378 } 7379 }; 7380 7381 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7382 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7383 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7384 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7385 7386 SDNodeFlags Flags; 7387 if (EB == fp::ExceptionBehavior::ebIgnore) 7388 Flags.setNoFPExcept(true); 7389 7390 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7391 Flags.copyFMF(*FPOp); 7392 7393 unsigned Opcode; 7394 switch (FPI.getIntrinsicID()) { 7395 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7396 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7397 case Intrinsic::INTRINSIC: \ 7398 Opcode = ISD::STRICT_##DAGN; \ 7399 break; 7400 #include "llvm/IR/ConstrainedOps.def" 7401 case Intrinsic::experimental_constrained_fmuladd: { 7402 Opcode = ISD::STRICT_FMA; 7403 // Break fmuladd into fmul and fadd. 7404 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7405 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7406 Opers.pop_back(); 7407 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7408 pushOutChain(Mul, EB); 7409 Opcode = ISD::STRICT_FADD; 7410 Opers.clear(); 7411 Opers.push_back(Mul.getValue(1)); 7412 Opers.push_back(Mul.getValue(0)); 7413 Opers.push_back(getValue(FPI.getArgOperand(2))); 7414 } 7415 break; 7416 } 7417 } 7418 7419 // A few strict DAG nodes carry additional operands that are not 7420 // set up by the default code above. 7421 switch (Opcode) { 7422 default: break; 7423 case ISD::STRICT_FP_ROUND: 7424 Opers.push_back( 7425 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7426 break; 7427 case ISD::STRICT_FSETCC: 7428 case ISD::STRICT_FSETCCS: { 7429 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7430 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7431 if (TM.Options.NoNaNsFPMath) 7432 Condition = getFCmpCodeWithoutNaN(Condition); 7433 Opers.push_back(DAG.getCondCode(Condition)); 7434 break; 7435 } 7436 } 7437 7438 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7439 pushOutChain(Result, EB); 7440 7441 SDValue FPResult = Result.getValue(0); 7442 setValue(&FPI, FPResult); 7443 } 7444 7445 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7446 std::optional<unsigned> ResOPC; 7447 switch (VPIntrin.getIntrinsicID()) { 7448 case Intrinsic::vp_ctlz: { 7449 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(3))->isOne(); 7450 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7451 break; 7452 } 7453 case Intrinsic::vp_cttz: { 7454 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(3))->isOne(); 7455 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7456 break; 7457 } 7458 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7459 case Intrinsic::VPID: \ 7460 ResOPC = ISD::VPSD; \ 7461 break; 7462 #include "llvm/IR/VPIntrinsics.def" 7463 } 7464 7465 if (!ResOPC) 7466 llvm_unreachable( 7467 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7468 7469 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7470 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7471 if (VPIntrin.getFastMathFlags().allowReassoc()) 7472 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7473 : ISD::VP_REDUCE_FMUL; 7474 } 7475 7476 return *ResOPC; 7477 } 7478 7479 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT, 7480 SmallVector<SDValue, 7> &OpValues) { 7481 SDLoc DL = getCurSDLoc(); 7482 Value *PtrOperand = VPIntrin.getArgOperand(0); 7483 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7484 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7485 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7486 SDValue LD; 7487 bool AddToChain = true; 7488 // Do not serialize variable-length loads of constant memory with 7489 // anything. 7490 if (!Alignment) 7491 Alignment = DAG.getEVTAlign(VT); 7492 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7493 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7494 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7495 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7496 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7497 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7498 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7499 MMO, false /*IsExpanding */); 7500 if (AddToChain) 7501 PendingLoads.push_back(LD.getValue(1)); 7502 setValue(&VPIntrin, LD); 7503 } 7504 7505 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT, 7506 SmallVector<SDValue, 7> &OpValues) { 7507 SDLoc DL = getCurSDLoc(); 7508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7509 Value *PtrOperand = VPIntrin.getArgOperand(0); 7510 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7511 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7512 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7513 SDValue LD; 7514 if (!Alignment) 7515 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7516 unsigned AS = 7517 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7518 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7519 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7520 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7521 SDValue Base, Index, Scale; 7522 ISD::MemIndexType IndexType; 7523 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7524 this, VPIntrin.getParent(), 7525 VT.getScalarStoreSize()); 7526 if (!UniformBase) { 7527 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7528 Index = getValue(PtrOperand); 7529 IndexType = ISD::SIGNED_SCALED; 7530 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7531 } 7532 EVT IdxVT = Index.getValueType(); 7533 EVT EltTy = IdxVT.getVectorElementType(); 7534 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7535 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7536 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7537 } 7538 LD = DAG.getGatherVP( 7539 DAG.getVTList(VT, MVT::Other), VT, DL, 7540 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7541 IndexType); 7542 PendingLoads.push_back(LD.getValue(1)); 7543 setValue(&VPIntrin, LD); 7544 } 7545 7546 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin, 7547 SmallVector<SDValue, 7> &OpValues) { 7548 SDLoc DL = getCurSDLoc(); 7549 Value *PtrOperand = VPIntrin.getArgOperand(1); 7550 EVT VT = OpValues[0].getValueType(); 7551 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7552 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7553 SDValue ST; 7554 if (!Alignment) 7555 Alignment = DAG.getEVTAlign(VT); 7556 SDValue Ptr = OpValues[1]; 7557 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7558 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7559 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7560 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7561 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7562 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7563 /* IsTruncating */ false, /*IsCompressing*/ false); 7564 DAG.setRoot(ST); 7565 setValue(&VPIntrin, ST); 7566 } 7567 7568 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin, 7569 SmallVector<SDValue, 7> &OpValues) { 7570 SDLoc DL = getCurSDLoc(); 7571 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7572 Value *PtrOperand = VPIntrin.getArgOperand(1); 7573 EVT VT = OpValues[0].getValueType(); 7574 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7575 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7576 SDValue ST; 7577 if (!Alignment) 7578 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7579 unsigned AS = 7580 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7581 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7582 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7583 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7584 SDValue Base, Index, Scale; 7585 ISD::MemIndexType IndexType; 7586 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7587 this, VPIntrin.getParent(), 7588 VT.getScalarStoreSize()); 7589 if (!UniformBase) { 7590 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7591 Index = getValue(PtrOperand); 7592 IndexType = ISD::SIGNED_SCALED; 7593 Scale = 7594 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7595 } 7596 EVT IdxVT = Index.getValueType(); 7597 EVT EltTy = IdxVT.getVectorElementType(); 7598 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7599 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7600 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7601 } 7602 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7603 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7604 OpValues[2], OpValues[3]}, 7605 MMO, IndexType); 7606 DAG.setRoot(ST); 7607 setValue(&VPIntrin, ST); 7608 } 7609 7610 void SelectionDAGBuilder::visitVPStridedLoad( 7611 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) { 7612 SDLoc DL = getCurSDLoc(); 7613 Value *PtrOperand = VPIntrin.getArgOperand(0); 7614 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7615 if (!Alignment) 7616 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7617 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7618 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7619 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7620 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7621 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7622 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7623 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7624 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7625 7626 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7627 OpValues[2], OpValues[3], MMO, 7628 false /*IsExpanding*/); 7629 7630 if (AddToChain) 7631 PendingLoads.push_back(LD.getValue(1)); 7632 setValue(&VPIntrin, LD); 7633 } 7634 7635 void SelectionDAGBuilder::visitVPStridedStore( 7636 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) { 7637 SDLoc DL = getCurSDLoc(); 7638 Value *PtrOperand = VPIntrin.getArgOperand(1); 7639 EVT VT = OpValues[0].getValueType(); 7640 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7641 if (!Alignment) 7642 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7643 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7644 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7645 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7646 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7647 7648 SDValue ST = DAG.getStridedStoreVP( 7649 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7650 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7651 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7652 /*IsCompressing*/ false); 7653 7654 DAG.setRoot(ST); 7655 setValue(&VPIntrin, ST); 7656 } 7657 7658 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7659 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7660 SDLoc DL = getCurSDLoc(); 7661 7662 ISD::CondCode Condition; 7663 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7664 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7665 if (IsFP) { 7666 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7667 // flags, but calls that don't return floating-point types can't be 7668 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7669 Condition = getFCmpCondCode(CondCode); 7670 if (TM.Options.NoNaNsFPMath) 7671 Condition = getFCmpCodeWithoutNaN(Condition); 7672 } else { 7673 Condition = getICmpCondCode(CondCode); 7674 } 7675 7676 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7677 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7678 // #2 is the condition code 7679 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7680 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7681 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7682 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7683 "Unexpected target EVL type"); 7684 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7685 7686 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7687 VPIntrin.getType()); 7688 setValue(&VPIntrin, 7689 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7690 } 7691 7692 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7693 const VPIntrinsic &VPIntrin) { 7694 SDLoc DL = getCurSDLoc(); 7695 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7696 7697 auto IID = VPIntrin.getIntrinsicID(); 7698 7699 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7700 return visitVPCmp(*CmpI); 7701 7702 SmallVector<EVT, 4> ValueVTs; 7703 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7704 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7705 SDVTList VTs = DAG.getVTList(ValueVTs); 7706 7707 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7708 7709 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7710 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7711 "Unexpected target EVL type"); 7712 7713 // Request operands. 7714 SmallVector<SDValue, 7> OpValues; 7715 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7716 auto Op = getValue(VPIntrin.getArgOperand(I)); 7717 if (I == EVLParamPos) 7718 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7719 OpValues.push_back(Op); 7720 } 7721 7722 switch (Opcode) { 7723 default: { 7724 SDNodeFlags SDFlags; 7725 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7726 SDFlags.copyFMF(*FPMO); 7727 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7728 setValue(&VPIntrin, Result); 7729 break; 7730 } 7731 case ISD::VP_LOAD: 7732 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7733 break; 7734 case ISD::VP_GATHER: 7735 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7736 break; 7737 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7738 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7739 break; 7740 case ISD::VP_STORE: 7741 visitVPStore(VPIntrin, OpValues); 7742 break; 7743 case ISD::VP_SCATTER: 7744 visitVPScatter(VPIntrin, OpValues); 7745 break; 7746 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7747 visitVPStridedStore(VPIntrin, OpValues); 7748 break; 7749 case ISD::VP_FMULADD: { 7750 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7751 SDNodeFlags SDFlags; 7752 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7753 SDFlags.copyFMF(*FPMO); 7754 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7755 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7756 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7757 } else { 7758 SDValue Mul = DAG.getNode( 7759 ISD::VP_FMUL, DL, VTs, 7760 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7761 SDValue Add = 7762 DAG.getNode(ISD::VP_FADD, DL, VTs, 7763 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7764 setValue(&VPIntrin, Add); 7765 } 7766 break; 7767 } 7768 case ISD::VP_INTTOPTR: { 7769 SDValue N = OpValues[0]; 7770 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7771 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7772 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7773 OpValues[2]); 7774 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7775 OpValues[2]); 7776 setValue(&VPIntrin, N); 7777 break; 7778 } 7779 case ISD::VP_PTRTOINT: { 7780 SDValue N = OpValues[0]; 7781 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7782 VPIntrin.getType()); 7783 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7784 VPIntrin.getOperand(0)->getType()); 7785 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7786 OpValues[2]); 7787 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7788 OpValues[2]); 7789 setValue(&VPIntrin, N); 7790 break; 7791 } 7792 case ISD::VP_ABS: 7793 case ISD::VP_CTLZ: 7794 case ISD::VP_CTLZ_ZERO_UNDEF: 7795 case ISD::VP_CTTZ: 7796 case ISD::VP_CTTZ_ZERO_UNDEF: { 7797 // Pop is_zero_poison operand for cp.ctlz/cttz or 7798 // is_int_min_poison operand for vp.abs. 7799 OpValues.pop_back(); 7800 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7801 setValue(&VPIntrin, Result); 7802 break; 7803 } 7804 } 7805 } 7806 7807 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7808 const BasicBlock *EHPadBB, 7809 MCSymbol *&BeginLabel) { 7810 MachineFunction &MF = DAG.getMachineFunction(); 7811 MachineModuleInfo &MMI = MF.getMMI(); 7812 7813 // Insert a label before the invoke call to mark the try range. This can be 7814 // used to detect deletion of the invoke via the MachineModuleInfo. 7815 BeginLabel = MMI.getContext().createTempSymbol(); 7816 7817 // For SjLj, keep track of which landing pads go with which invokes 7818 // so as to maintain the ordering of pads in the LSDA. 7819 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7820 if (CallSiteIndex) { 7821 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7822 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7823 7824 // Now that the call site is handled, stop tracking it. 7825 MMI.setCurrentCallSite(0); 7826 } 7827 7828 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7829 } 7830 7831 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7832 const BasicBlock *EHPadBB, 7833 MCSymbol *BeginLabel) { 7834 assert(BeginLabel && "BeginLabel should've been set"); 7835 7836 MachineFunction &MF = DAG.getMachineFunction(); 7837 MachineModuleInfo &MMI = MF.getMMI(); 7838 7839 // Insert a label at the end of the invoke call to mark the try range. This 7840 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7841 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7842 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7843 7844 // Inform MachineModuleInfo of range. 7845 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7846 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7847 // actually use outlined funclets and their LSDA info style. 7848 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7849 assert(II && "II should've been set"); 7850 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7851 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7852 } else if (!isScopedEHPersonality(Pers)) { 7853 assert(EHPadBB); 7854 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7855 } 7856 7857 return Chain; 7858 } 7859 7860 std::pair<SDValue, SDValue> 7861 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7862 const BasicBlock *EHPadBB) { 7863 MCSymbol *BeginLabel = nullptr; 7864 7865 if (EHPadBB) { 7866 // Both PendingLoads and PendingExports must be flushed here; 7867 // this call might not return. 7868 (void)getRoot(); 7869 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7870 CLI.setChain(getRoot()); 7871 } 7872 7873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7874 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7875 7876 assert((CLI.IsTailCall || Result.second.getNode()) && 7877 "Non-null chain expected with non-tail call!"); 7878 assert((Result.second.getNode() || !Result.first.getNode()) && 7879 "Null value expected with tail call!"); 7880 7881 if (!Result.second.getNode()) { 7882 // As a special case, a null chain means that a tail call has been emitted 7883 // and the DAG root is already updated. 7884 HasTailCall = true; 7885 7886 // Since there's no actual continuation from this block, nothing can be 7887 // relying on us setting vregs for them. 7888 PendingExports.clear(); 7889 } else { 7890 DAG.setRoot(Result.second); 7891 } 7892 7893 if (EHPadBB) { 7894 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7895 BeginLabel)); 7896 } 7897 7898 return Result; 7899 } 7900 7901 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7902 bool isTailCall, 7903 bool isMustTailCall, 7904 const BasicBlock *EHPadBB) { 7905 auto &DL = DAG.getDataLayout(); 7906 FunctionType *FTy = CB.getFunctionType(); 7907 Type *RetTy = CB.getType(); 7908 7909 TargetLowering::ArgListTy Args; 7910 Args.reserve(CB.arg_size()); 7911 7912 const Value *SwiftErrorVal = nullptr; 7913 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7914 7915 if (isTailCall) { 7916 // Avoid emitting tail calls in functions with the disable-tail-calls 7917 // attribute. 7918 auto *Caller = CB.getParent()->getParent(); 7919 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7920 "true" && !isMustTailCall) 7921 isTailCall = false; 7922 7923 // We can't tail call inside a function with a swifterror argument. Lowering 7924 // does not support this yet. It would have to move into the swifterror 7925 // register before the call. 7926 if (TLI.supportSwiftError() && 7927 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7928 isTailCall = false; 7929 } 7930 7931 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7932 TargetLowering::ArgListEntry Entry; 7933 const Value *V = *I; 7934 7935 // Skip empty types 7936 if (V->getType()->isEmptyTy()) 7937 continue; 7938 7939 SDValue ArgNode = getValue(V); 7940 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7941 7942 Entry.setAttributes(&CB, I - CB.arg_begin()); 7943 7944 // Use swifterror virtual register as input to the call. 7945 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7946 SwiftErrorVal = V; 7947 // We find the virtual register for the actual swifterror argument. 7948 // Instead of using the Value, we use the virtual register instead. 7949 Entry.Node = 7950 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7951 EVT(TLI.getPointerTy(DL))); 7952 } 7953 7954 Args.push_back(Entry); 7955 7956 // If we have an explicit sret argument that is an Instruction, (i.e., it 7957 // might point to function-local memory), we can't meaningfully tail-call. 7958 if (Entry.IsSRet && isa<Instruction>(V)) 7959 isTailCall = false; 7960 } 7961 7962 // If call site has a cfguardtarget operand bundle, create and add an 7963 // additional ArgListEntry. 7964 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7965 TargetLowering::ArgListEntry Entry; 7966 Value *V = Bundle->Inputs[0]; 7967 SDValue ArgNode = getValue(V); 7968 Entry.Node = ArgNode; 7969 Entry.Ty = V->getType(); 7970 Entry.IsCFGuardTarget = true; 7971 Args.push_back(Entry); 7972 } 7973 7974 // Check if target-independent constraints permit a tail call here. 7975 // Target-dependent constraints are checked within TLI->LowerCallTo. 7976 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7977 isTailCall = false; 7978 7979 // Disable tail calls if there is an swifterror argument. Targets have not 7980 // been updated to support tail calls. 7981 if (TLI.supportSwiftError() && SwiftErrorVal) 7982 isTailCall = false; 7983 7984 ConstantInt *CFIType = nullptr; 7985 if (CB.isIndirectCall()) { 7986 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 7987 if (!TLI.supportKCFIBundles()) 7988 report_fatal_error( 7989 "Target doesn't support calls with kcfi operand bundles."); 7990 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 7991 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 7992 } 7993 } 7994 7995 TargetLowering::CallLoweringInfo CLI(DAG); 7996 CLI.setDebugLoc(getCurSDLoc()) 7997 .setChain(getRoot()) 7998 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7999 .setTailCall(isTailCall) 8000 .setConvergent(CB.isConvergent()) 8001 .setIsPreallocated( 8002 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8003 .setCFIType(CFIType); 8004 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8005 8006 if (Result.first.getNode()) { 8007 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8008 setValue(&CB, Result.first); 8009 } 8010 8011 // The last element of CLI.InVals has the SDValue for swifterror return. 8012 // Here we copy it to a virtual register and update SwiftErrorMap for 8013 // book-keeping. 8014 if (SwiftErrorVal && TLI.supportSwiftError()) { 8015 // Get the last element of InVals. 8016 SDValue Src = CLI.InVals.back(); 8017 Register VReg = 8018 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8019 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8020 DAG.setRoot(CopyNode); 8021 } 8022 } 8023 8024 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8025 SelectionDAGBuilder &Builder) { 8026 // Check to see if this load can be trivially constant folded, e.g. if the 8027 // input is from a string literal. 8028 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8029 // Cast pointer to the type we really want to load. 8030 Type *LoadTy = 8031 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8032 if (LoadVT.isVector()) 8033 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8034 8035 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8036 PointerType::getUnqual(LoadTy)); 8037 8038 if (const Constant *LoadCst = 8039 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8040 LoadTy, Builder.DAG.getDataLayout())) 8041 return Builder.getValue(LoadCst); 8042 } 8043 8044 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8045 // still constant memory, the input chain can be the entry node. 8046 SDValue Root; 8047 bool ConstantMemory = false; 8048 8049 // Do not serialize (non-volatile) loads of constant memory with anything. 8050 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8051 Root = Builder.DAG.getEntryNode(); 8052 ConstantMemory = true; 8053 } else { 8054 // Do not serialize non-volatile loads against each other. 8055 Root = Builder.DAG.getRoot(); 8056 } 8057 8058 SDValue Ptr = Builder.getValue(PtrVal); 8059 SDValue LoadVal = 8060 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8061 MachinePointerInfo(PtrVal), Align(1)); 8062 8063 if (!ConstantMemory) 8064 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8065 return LoadVal; 8066 } 8067 8068 /// Record the value for an instruction that produces an integer result, 8069 /// converting the type where necessary. 8070 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8071 SDValue Value, 8072 bool IsSigned) { 8073 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8074 I.getType(), true); 8075 if (IsSigned) 8076 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8077 else 8078 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8079 setValue(&I, Value); 8080 } 8081 8082 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8083 /// true and lower it. Otherwise return false, and it will be lowered like a 8084 /// normal call. 8085 /// The caller already checked that \p I calls the appropriate LibFunc with a 8086 /// correct prototype. 8087 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8088 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8089 const Value *Size = I.getArgOperand(2); 8090 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8091 if (CSize && CSize->getZExtValue() == 0) { 8092 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8093 I.getType(), true); 8094 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8095 return true; 8096 } 8097 8098 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8099 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8100 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8101 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8102 if (Res.first.getNode()) { 8103 processIntegerCallValue(I, Res.first, true); 8104 PendingLoads.push_back(Res.second); 8105 return true; 8106 } 8107 8108 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8109 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8110 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8111 return false; 8112 8113 // If the target has a fast compare for the given size, it will return a 8114 // preferred load type for that size. Require that the load VT is legal and 8115 // that the target supports unaligned loads of that type. Otherwise, return 8116 // INVALID. 8117 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8118 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8119 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8120 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8121 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8122 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8123 // TODO: Check alignment of src and dest ptrs. 8124 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8125 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8126 if (!TLI.isTypeLegal(LVT) || 8127 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8128 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8129 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8130 } 8131 8132 return LVT; 8133 }; 8134 8135 // This turns into unaligned loads. We only do this if the target natively 8136 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8137 // we'll only produce a small number of byte loads. 8138 MVT LoadVT; 8139 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8140 switch (NumBitsToCompare) { 8141 default: 8142 return false; 8143 case 16: 8144 LoadVT = MVT::i16; 8145 break; 8146 case 32: 8147 LoadVT = MVT::i32; 8148 break; 8149 case 64: 8150 case 128: 8151 case 256: 8152 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8153 break; 8154 } 8155 8156 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8157 return false; 8158 8159 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8160 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8161 8162 // Bitcast to a wide integer type if the loads are vectors. 8163 if (LoadVT.isVector()) { 8164 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8165 LoadL = DAG.getBitcast(CmpVT, LoadL); 8166 LoadR = DAG.getBitcast(CmpVT, LoadR); 8167 } 8168 8169 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8170 processIntegerCallValue(I, Cmp, false); 8171 return true; 8172 } 8173 8174 /// See if we can lower a memchr call into an optimized form. If so, return 8175 /// true and lower it. Otherwise return false, and it will be lowered like a 8176 /// normal call. 8177 /// The caller already checked that \p I calls the appropriate LibFunc with a 8178 /// correct prototype. 8179 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8180 const Value *Src = I.getArgOperand(0); 8181 const Value *Char = I.getArgOperand(1); 8182 const Value *Length = I.getArgOperand(2); 8183 8184 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8185 std::pair<SDValue, SDValue> Res = 8186 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8187 getValue(Src), getValue(Char), getValue(Length), 8188 MachinePointerInfo(Src)); 8189 if (Res.first.getNode()) { 8190 setValue(&I, Res.first); 8191 PendingLoads.push_back(Res.second); 8192 return true; 8193 } 8194 8195 return false; 8196 } 8197 8198 /// See if we can lower a mempcpy call into an optimized form. If so, return 8199 /// true and lower it. Otherwise return false, and it will be lowered like a 8200 /// normal call. 8201 /// The caller already checked that \p I calls the appropriate LibFunc with a 8202 /// correct prototype. 8203 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8204 SDValue Dst = getValue(I.getArgOperand(0)); 8205 SDValue Src = getValue(I.getArgOperand(1)); 8206 SDValue Size = getValue(I.getArgOperand(2)); 8207 8208 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8209 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8210 // DAG::getMemcpy needs Alignment to be defined. 8211 Align Alignment = std::min(DstAlign, SrcAlign); 8212 8213 bool isVol = false; 8214 SDLoc sdl = getCurSDLoc(); 8215 8216 // In the mempcpy context we need to pass in a false value for isTailCall 8217 // because the return pointer needs to be adjusted by the size of 8218 // the copied memory. 8219 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8220 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8221 /*isTailCall=*/false, 8222 MachinePointerInfo(I.getArgOperand(0)), 8223 MachinePointerInfo(I.getArgOperand(1)), 8224 I.getAAMetadata()); 8225 assert(MC.getNode() != nullptr && 8226 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8227 DAG.setRoot(MC); 8228 8229 // Check if Size needs to be truncated or extended. 8230 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8231 8232 // Adjust return pointer to point just past the last dst byte. 8233 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8234 Dst, Size); 8235 setValue(&I, DstPlusSize); 8236 return true; 8237 } 8238 8239 /// See if we can lower a strcpy call into an optimized form. If so, return 8240 /// true and lower it, otherwise return false and it will be lowered like a 8241 /// normal call. 8242 /// The caller already checked that \p I calls the appropriate LibFunc with a 8243 /// correct prototype. 8244 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8245 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8246 8247 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8248 std::pair<SDValue, SDValue> Res = 8249 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8250 getValue(Arg0), getValue(Arg1), 8251 MachinePointerInfo(Arg0), 8252 MachinePointerInfo(Arg1), isStpcpy); 8253 if (Res.first.getNode()) { 8254 setValue(&I, Res.first); 8255 DAG.setRoot(Res.second); 8256 return true; 8257 } 8258 8259 return false; 8260 } 8261 8262 /// See if we can lower a strcmp call into an optimized form. If so, return 8263 /// true and lower it, otherwise return false and it will be lowered like a 8264 /// normal call. 8265 /// The caller already checked that \p I calls the appropriate LibFunc with a 8266 /// correct prototype. 8267 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8268 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8269 8270 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8271 std::pair<SDValue, SDValue> Res = 8272 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8273 getValue(Arg0), getValue(Arg1), 8274 MachinePointerInfo(Arg0), 8275 MachinePointerInfo(Arg1)); 8276 if (Res.first.getNode()) { 8277 processIntegerCallValue(I, Res.first, true); 8278 PendingLoads.push_back(Res.second); 8279 return true; 8280 } 8281 8282 return false; 8283 } 8284 8285 /// See if we can lower a strlen call into an optimized form. If so, return 8286 /// true and lower it, otherwise return false and it will be lowered like a 8287 /// normal call. 8288 /// The caller already checked that \p I calls the appropriate LibFunc with a 8289 /// correct prototype. 8290 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8291 const Value *Arg0 = I.getArgOperand(0); 8292 8293 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8294 std::pair<SDValue, SDValue> Res = 8295 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8296 getValue(Arg0), MachinePointerInfo(Arg0)); 8297 if (Res.first.getNode()) { 8298 processIntegerCallValue(I, Res.first, false); 8299 PendingLoads.push_back(Res.second); 8300 return true; 8301 } 8302 8303 return false; 8304 } 8305 8306 /// See if we can lower a strnlen call into an optimized form. If so, return 8307 /// true and lower it, otherwise return false and it will be lowered like a 8308 /// normal call. 8309 /// The caller already checked that \p I calls the appropriate LibFunc with a 8310 /// correct prototype. 8311 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8312 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8313 8314 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8315 std::pair<SDValue, SDValue> Res = 8316 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8317 getValue(Arg0), getValue(Arg1), 8318 MachinePointerInfo(Arg0)); 8319 if (Res.first.getNode()) { 8320 processIntegerCallValue(I, Res.first, false); 8321 PendingLoads.push_back(Res.second); 8322 return true; 8323 } 8324 8325 return false; 8326 } 8327 8328 /// See if we can lower a unary floating-point operation into an SDNode with 8329 /// the specified Opcode. If so, return true and lower it, otherwise return 8330 /// false and it will be lowered like a normal call. 8331 /// The caller already checked that \p I calls the appropriate LibFunc with a 8332 /// correct prototype. 8333 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8334 unsigned Opcode) { 8335 // We already checked this call's prototype; verify it doesn't modify errno. 8336 if (!I.onlyReadsMemory()) 8337 return false; 8338 8339 SDNodeFlags Flags; 8340 Flags.copyFMF(cast<FPMathOperator>(I)); 8341 8342 SDValue Tmp = getValue(I.getArgOperand(0)); 8343 setValue(&I, 8344 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8345 return true; 8346 } 8347 8348 /// See if we can lower a binary floating-point operation into an SDNode with 8349 /// the specified Opcode. If so, return true and lower it. Otherwise return 8350 /// false, and it will be lowered like a normal call. 8351 /// The caller already checked that \p I calls the appropriate LibFunc with a 8352 /// correct prototype. 8353 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8354 unsigned Opcode) { 8355 // We already checked this call's prototype; verify it doesn't modify errno. 8356 if (!I.onlyReadsMemory()) 8357 return false; 8358 8359 SDNodeFlags Flags; 8360 Flags.copyFMF(cast<FPMathOperator>(I)); 8361 8362 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8363 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8364 EVT VT = Tmp0.getValueType(); 8365 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8366 return true; 8367 } 8368 8369 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8370 // Handle inline assembly differently. 8371 if (I.isInlineAsm()) { 8372 visitInlineAsm(I); 8373 return; 8374 } 8375 8376 diagnoseDontCall(I); 8377 8378 if (Function *F = I.getCalledFunction()) { 8379 if (F->isDeclaration()) { 8380 // Is this an LLVM intrinsic or a target-specific intrinsic? 8381 unsigned IID = F->getIntrinsicID(); 8382 if (!IID) 8383 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8384 IID = II->getIntrinsicID(F); 8385 8386 if (IID) { 8387 visitIntrinsicCall(I, IID); 8388 return; 8389 } 8390 } 8391 8392 // Check for well-known libc/libm calls. If the function is internal, it 8393 // can't be a library call. Don't do the check if marked as nobuiltin for 8394 // some reason or the call site requires strict floating point semantics. 8395 LibFunc Func; 8396 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8397 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8398 LibInfo->hasOptimizedCodeGen(Func)) { 8399 switch (Func) { 8400 default: break; 8401 case LibFunc_bcmp: 8402 if (visitMemCmpBCmpCall(I)) 8403 return; 8404 break; 8405 case LibFunc_copysign: 8406 case LibFunc_copysignf: 8407 case LibFunc_copysignl: 8408 // We already checked this call's prototype; verify it doesn't modify 8409 // errno. 8410 if (I.onlyReadsMemory()) { 8411 SDValue LHS = getValue(I.getArgOperand(0)); 8412 SDValue RHS = getValue(I.getArgOperand(1)); 8413 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8414 LHS.getValueType(), LHS, RHS)); 8415 return; 8416 } 8417 break; 8418 case LibFunc_fabs: 8419 case LibFunc_fabsf: 8420 case LibFunc_fabsl: 8421 if (visitUnaryFloatCall(I, ISD::FABS)) 8422 return; 8423 break; 8424 case LibFunc_fmin: 8425 case LibFunc_fminf: 8426 case LibFunc_fminl: 8427 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8428 return; 8429 break; 8430 case LibFunc_fmax: 8431 case LibFunc_fmaxf: 8432 case LibFunc_fmaxl: 8433 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8434 return; 8435 break; 8436 case LibFunc_sin: 8437 case LibFunc_sinf: 8438 case LibFunc_sinl: 8439 if (visitUnaryFloatCall(I, ISD::FSIN)) 8440 return; 8441 break; 8442 case LibFunc_cos: 8443 case LibFunc_cosf: 8444 case LibFunc_cosl: 8445 if (visitUnaryFloatCall(I, ISD::FCOS)) 8446 return; 8447 break; 8448 case LibFunc_sqrt: 8449 case LibFunc_sqrtf: 8450 case LibFunc_sqrtl: 8451 case LibFunc_sqrt_finite: 8452 case LibFunc_sqrtf_finite: 8453 case LibFunc_sqrtl_finite: 8454 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8455 return; 8456 break; 8457 case LibFunc_floor: 8458 case LibFunc_floorf: 8459 case LibFunc_floorl: 8460 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8461 return; 8462 break; 8463 case LibFunc_nearbyint: 8464 case LibFunc_nearbyintf: 8465 case LibFunc_nearbyintl: 8466 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8467 return; 8468 break; 8469 case LibFunc_ceil: 8470 case LibFunc_ceilf: 8471 case LibFunc_ceill: 8472 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8473 return; 8474 break; 8475 case LibFunc_rint: 8476 case LibFunc_rintf: 8477 case LibFunc_rintl: 8478 if (visitUnaryFloatCall(I, ISD::FRINT)) 8479 return; 8480 break; 8481 case LibFunc_round: 8482 case LibFunc_roundf: 8483 case LibFunc_roundl: 8484 if (visitUnaryFloatCall(I, ISD::FROUND)) 8485 return; 8486 break; 8487 case LibFunc_trunc: 8488 case LibFunc_truncf: 8489 case LibFunc_truncl: 8490 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8491 return; 8492 break; 8493 case LibFunc_log2: 8494 case LibFunc_log2f: 8495 case LibFunc_log2l: 8496 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8497 return; 8498 break; 8499 case LibFunc_exp2: 8500 case LibFunc_exp2f: 8501 case LibFunc_exp2l: 8502 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8503 return; 8504 break; 8505 case LibFunc_memcmp: 8506 if (visitMemCmpBCmpCall(I)) 8507 return; 8508 break; 8509 case LibFunc_mempcpy: 8510 if (visitMemPCpyCall(I)) 8511 return; 8512 break; 8513 case LibFunc_memchr: 8514 if (visitMemChrCall(I)) 8515 return; 8516 break; 8517 case LibFunc_strcpy: 8518 if (visitStrCpyCall(I, false)) 8519 return; 8520 break; 8521 case LibFunc_stpcpy: 8522 if (visitStrCpyCall(I, true)) 8523 return; 8524 break; 8525 case LibFunc_strcmp: 8526 if (visitStrCmpCall(I)) 8527 return; 8528 break; 8529 case LibFunc_strlen: 8530 if (visitStrLenCall(I)) 8531 return; 8532 break; 8533 case LibFunc_strnlen: 8534 if (visitStrNLenCall(I)) 8535 return; 8536 break; 8537 } 8538 } 8539 } 8540 8541 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8542 // have to do anything here to lower funclet bundles. 8543 // CFGuardTarget bundles are lowered in LowerCallTo. 8544 assert(!I.hasOperandBundlesOtherThan( 8545 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8546 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8547 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8548 "Cannot lower calls with arbitrary operand bundles!"); 8549 8550 SDValue Callee = getValue(I.getCalledOperand()); 8551 8552 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8553 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8554 else 8555 // Check if we can potentially perform a tail call. More detailed checking 8556 // is be done within LowerCallTo, after more information about the call is 8557 // known. 8558 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8559 } 8560 8561 namespace { 8562 8563 /// AsmOperandInfo - This contains information for each constraint that we are 8564 /// lowering. 8565 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8566 public: 8567 /// CallOperand - If this is the result output operand or a clobber 8568 /// this is null, otherwise it is the incoming operand to the CallInst. 8569 /// This gets modified as the asm is processed. 8570 SDValue CallOperand; 8571 8572 /// AssignedRegs - If this is a register or register class operand, this 8573 /// contains the set of register corresponding to the operand. 8574 RegsForValue AssignedRegs; 8575 8576 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8577 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8578 } 8579 8580 /// Whether or not this operand accesses memory 8581 bool hasMemory(const TargetLowering &TLI) const { 8582 // Indirect operand accesses access memory. 8583 if (isIndirect) 8584 return true; 8585 8586 for (const auto &Code : Codes) 8587 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8588 return true; 8589 8590 return false; 8591 } 8592 }; 8593 8594 8595 } // end anonymous namespace 8596 8597 /// Make sure that the output operand \p OpInfo and its corresponding input 8598 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8599 /// out). 8600 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8601 SDISelAsmOperandInfo &MatchingOpInfo, 8602 SelectionDAG &DAG) { 8603 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8604 return; 8605 8606 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8607 const auto &TLI = DAG.getTargetLoweringInfo(); 8608 8609 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8610 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8611 OpInfo.ConstraintVT); 8612 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8613 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8614 MatchingOpInfo.ConstraintVT); 8615 if ((OpInfo.ConstraintVT.isInteger() != 8616 MatchingOpInfo.ConstraintVT.isInteger()) || 8617 (MatchRC.second != InputRC.second)) { 8618 // FIXME: error out in a more elegant fashion 8619 report_fatal_error("Unsupported asm: input constraint" 8620 " with a matching output constraint of" 8621 " incompatible type!"); 8622 } 8623 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8624 } 8625 8626 /// Get a direct memory input to behave well as an indirect operand. 8627 /// This may introduce stores, hence the need for a \p Chain. 8628 /// \return The (possibly updated) chain. 8629 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8630 SDISelAsmOperandInfo &OpInfo, 8631 SelectionDAG &DAG) { 8632 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8633 8634 // If we don't have an indirect input, put it in the constpool if we can, 8635 // otherwise spill it to a stack slot. 8636 // TODO: This isn't quite right. We need to handle these according to 8637 // the addressing mode that the constraint wants. Also, this may take 8638 // an additional register for the computation and we don't want that 8639 // either. 8640 8641 // If the operand is a float, integer, or vector constant, spill to a 8642 // constant pool entry to get its address. 8643 const Value *OpVal = OpInfo.CallOperandVal; 8644 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8645 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8646 OpInfo.CallOperand = DAG.getConstantPool( 8647 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8648 return Chain; 8649 } 8650 8651 // Otherwise, create a stack slot and emit a store to it before the asm. 8652 Type *Ty = OpVal->getType(); 8653 auto &DL = DAG.getDataLayout(); 8654 uint64_t TySize = DL.getTypeAllocSize(Ty); 8655 MachineFunction &MF = DAG.getMachineFunction(); 8656 int SSFI = MF.getFrameInfo().CreateStackObject( 8657 TySize, DL.getPrefTypeAlign(Ty), false); 8658 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8659 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8660 MachinePointerInfo::getFixedStack(MF, SSFI), 8661 TLI.getMemValueType(DL, Ty)); 8662 OpInfo.CallOperand = StackSlot; 8663 8664 return Chain; 8665 } 8666 8667 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8668 /// specified operand. We prefer to assign virtual registers, to allow the 8669 /// register allocator to handle the assignment process. However, if the asm 8670 /// uses features that we can't model on machineinstrs, we have SDISel do the 8671 /// allocation. This produces generally horrible, but correct, code. 8672 /// 8673 /// OpInfo describes the operand 8674 /// RefOpInfo describes the matching operand if any, the operand otherwise 8675 static std::optional<unsigned> 8676 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8677 SDISelAsmOperandInfo &OpInfo, 8678 SDISelAsmOperandInfo &RefOpInfo) { 8679 LLVMContext &Context = *DAG.getContext(); 8680 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8681 8682 MachineFunction &MF = DAG.getMachineFunction(); 8683 SmallVector<unsigned, 4> Regs; 8684 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8685 8686 // No work to do for memory/address operands. 8687 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8688 OpInfo.ConstraintType == TargetLowering::C_Address) 8689 return std::nullopt; 8690 8691 // If this is a constraint for a single physreg, or a constraint for a 8692 // register class, find it. 8693 unsigned AssignedReg; 8694 const TargetRegisterClass *RC; 8695 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8696 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8697 // RC is unset only on failure. Return immediately. 8698 if (!RC) 8699 return std::nullopt; 8700 8701 // Get the actual register value type. This is important, because the user 8702 // may have asked for (e.g.) the AX register in i32 type. We need to 8703 // remember that AX is actually i16 to get the right extension. 8704 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8705 8706 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8707 // If this is an FP operand in an integer register (or visa versa), or more 8708 // generally if the operand value disagrees with the register class we plan 8709 // to stick it in, fix the operand type. 8710 // 8711 // If this is an input value, the bitcast to the new type is done now. 8712 // Bitcast for output value is done at the end of visitInlineAsm(). 8713 if ((OpInfo.Type == InlineAsm::isOutput || 8714 OpInfo.Type == InlineAsm::isInput) && 8715 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8716 // Try to convert to the first EVT that the reg class contains. If the 8717 // types are identical size, use a bitcast to convert (e.g. two differing 8718 // vector types). Note: output bitcast is done at the end of 8719 // visitInlineAsm(). 8720 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8721 // Exclude indirect inputs while they are unsupported because the code 8722 // to perform the load is missing and thus OpInfo.CallOperand still 8723 // refers to the input address rather than the pointed-to value. 8724 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8725 OpInfo.CallOperand = 8726 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8727 OpInfo.ConstraintVT = RegVT; 8728 // If the operand is an FP value and we want it in integer registers, 8729 // use the corresponding integer type. This turns an f64 value into 8730 // i64, which can be passed with two i32 values on a 32-bit machine. 8731 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8732 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8733 if (OpInfo.Type == InlineAsm::isInput) 8734 OpInfo.CallOperand = 8735 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8736 OpInfo.ConstraintVT = VT; 8737 } 8738 } 8739 } 8740 8741 // No need to allocate a matching input constraint since the constraint it's 8742 // matching to has already been allocated. 8743 if (OpInfo.isMatchingInputConstraint()) 8744 return std::nullopt; 8745 8746 EVT ValueVT = OpInfo.ConstraintVT; 8747 if (OpInfo.ConstraintVT == MVT::Other) 8748 ValueVT = RegVT; 8749 8750 // Initialize NumRegs. 8751 unsigned NumRegs = 1; 8752 if (OpInfo.ConstraintVT != MVT::Other) 8753 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8754 8755 // If this is a constraint for a specific physical register, like {r17}, 8756 // assign it now. 8757 8758 // If this associated to a specific register, initialize iterator to correct 8759 // place. If virtual, make sure we have enough registers 8760 8761 // Initialize iterator if necessary 8762 TargetRegisterClass::iterator I = RC->begin(); 8763 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8764 8765 // Do not check for single registers. 8766 if (AssignedReg) { 8767 I = std::find(I, RC->end(), AssignedReg); 8768 if (I == RC->end()) { 8769 // RC does not contain the selected register, which indicates a 8770 // mismatch between the register and the required type/bitwidth. 8771 return {AssignedReg}; 8772 } 8773 } 8774 8775 for (; NumRegs; --NumRegs, ++I) { 8776 assert(I != RC->end() && "Ran out of registers to allocate!"); 8777 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8778 Regs.push_back(R); 8779 } 8780 8781 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8782 return std::nullopt; 8783 } 8784 8785 static unsigned 8786 findMatchingInlineAsmOperand(unsigned OperandNo, 8787 const std::vector<SDValue> &AsmNodeOperands) { 8788 // Scan until we find the definition we already emitted of this operand. 8789 unsigned CurOp = InlineAsm::Op_FirstOperand; 8790 for (; OperandNo; --OperandNo) { 8791 // Advance to the next operand. 8792 unsigned OpFlag = 8793 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8794 assert((InlineAsm::isRegDefKind(OpFlag) || 8795 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8796 InlineAsm::isMemKind(OpFlag)) && 8797 "Skipped past definitions?"); 8798 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8799 } 8800 return CurOp; 8801 } 8802 8803 namespace { 8804 8805 class ExtraFlags { 8806 unsigned Flags = 0; 8807 8808 public: 8809 explicit ExtraFlags(const CallBase &Call) { 8810 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8811 if (IA->hasSideEffects()) 8812 Flags |= InlineAsm::Extra_HasSideEffects; 8813 if (IA->isAlignStack()) 8814 Flags |= InlineAsm::Extra_IsAlignStack; 8815 if (Call.isConvergent()) 8816 Flags |= InlineAsm::Extra_IsConvergent; 8817 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8818 } 8819 8820 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8821 // Ideally, we would only check against memory constraints. However, the 8822 // meaning of an Other constraint can be target-specific and we can't easily 8823 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8824 // for Other constraints as well. 8825 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8826 OpInfo.ConstraintType == TargetLowering::C_Other) { 8827 if (OpInfo.Type == InlineAsm::isInput) 8828 Flags |= InlineAsm::Extra_MayLoad; 8829 else if (OpInfo.Type == InlineAsm::isOutput) 8830 Flags |= InlineAsm::Extra_MayStore; 8831 else if (OpInfo.Type == InlineAsm::isClobber) 8832 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8833 } 8834 } 8835 8836 unsigned get() const { return Flags; } 8837 }; 8838 8839 } // end anonymous namespace 8840 8841 static bool isFunction(SDValue Op) { 8842 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8843 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8844 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8845 8846 // In normal "call dllimport func" instruction (non-inlineasm) it force 8847 // indirect access by specifing call opcode. And usually specially print 8848 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8849 // not do in this way now. (In fact, this is similar with "Data Access" 8850 // action). So here we ignore dllimport function. 8851 if (Fn && !Fn->hasDLLImportStorageClass()) 8852 return true; 8853 } 8854 } 8855 return false; 8856 } 8857 8858 /// visitInlineAsm - Handle a call to an InlineAsm object. 8859 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8860 const BasicBlock *EHPadBB) { 8861 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8862 8863 /// ConstraintOperands - Information about all of the constraints. 8864 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8865 8866 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8867 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8868 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8869 8870 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8871 // AsmDialect, MayLoad, MayStore). 8872 bool HasSideEffect = IA->hasSideEffects(); 8873 ExtraFlags ExtraInfo(Call); 8874 8875 for (auto &T : TargetConstraints) { 8876 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8877 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8878 8879 if (OpInfo.CallOperandVal) 8880 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8881 8882 if (!HasSideEffect) 8883 HasSideEffect = OpInfo.hasMemory(TLI); 8884 8885 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8886 // FIXME: Could we compute this on OpInfo rather than T? 8887 8888 // Compute the constraint code and ConstraintType to use. 8889 TLI.ComputeConstraintToUse(T, SDValue()); 8890 8891 if (T.ConstraintType == TargetLowering::C_Immediate && 8892 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8893 // We've delayed emitting a diagnostic like the "n" constraint because 8894 // inlining could cause an integer showing up. 8895 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8896 "' expects an integer constant " 8897 "expression"); 8898 8899 ExtraInfo.update(T); 8900 } 8901 8902 // We won't need to flush pending loads if this asm doesn't touch 8903 // memory and is nonvolatile. 8904 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8905 8906 bool EmitEHLabels = isa<InvokeInst>(Call); 8907 if (EmitEHLabels) { 8908 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8909 } 8910 bool IsCallBr = isa<CallBrInst>(Call); 8911 8912 if (IsCallBr || EmitEHLabels) { 8913 // If this is a callbr or invoke we need to flush pending exports since 8914 // inlineasm_br and invoke are terminators. 8915 // We need to do this before nodes are glued to the inlineasm_br node. 8916 Chain = getControlRoot(); 8917 } 8918 8919 MCSymbol *BeginLabel = nullptr; 8920 if (EmitEHLabels) { 8921 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8922 } 8923 8924 int OpNo = -1; 8925 SmallVector<StringRef> AsmStrs; 8926 IA->collectAsmStrs(AsmStrs); 8927 8928 // Second pass over the constraints: compute which constraint option to use. 8929 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8930 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 8931 OpNo++; 8932 8933 // If this is an output operand with a matching input operand, look up the 8934 // matching input. If their types mismatch, e.g. one is an integer, the 8935 // other is floating point, or their sizes are different, flag it as an 8936 // error. 8937 if (OpInfo.hasMatchingInput()) { 8938 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8939 patchMatchingInput(OpInfo, Input, DAG); 8940 } 8941 8942 // Compute the constraint code and ConstraintType to use. 8943 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8944 8945 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8946 OpInfo.Type == InlineAsm::isClobber) || 8947 OpInfo.ConstraintType == TargetLowering::C_Address) 8948 continue; 8949 8950 // In Linux PIC model, there are 4 cases about value/label addressing: 8951 // 8952 // 1: Function call or Label jmp inside the module. 8953 // 2: Data access (such as global variable, static variable) inside module. 8954 // 3: Function call or Label jmp outside the module. 8955 // 4: Data access (such as global variable) outside the module. 8956 // 8957 // Due to current llvm inline asm architecture designed to not "recognize" 8958 // the asm code, there are quite troubles for us to treat mem addressing 8959 // differently for same value/adress used in different instuctions. 8960 // For example, in pic model, call a func may in plt way or direclty 8961 // pc-related, but lea/mov a function adress may use got. 8962 // 8963 // Here we try to "recognize" function call for the case 1 and case 3 in 8964 // inline asm. And try to adjust the constraint for them. 8965 // 8966 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 8967 // label, so here we don't handle jmp function label now, but we need to 8968 // enhance it (especilly in PIC model) if we meet meaningful requirements. 8969 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 8970 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 8971 TM.getCodeModel() != CodeModel::Large) { 8972 OpInfo.isIndirect = false; 8973 OpInfo.ConstraintType = TargetLowering::C_Address; 8974 } 8975 8976 // If this is a memory input, and if the operand is not indirect, do what we 8977 // need to provide an address for the memory input. 8978 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8979 !OpInfo.isIndirect) { 8980 assert((OpInfo.isMultipleAlternative || 8981 (OpInfo.Type == InlineAsm::isInput)) && 8982 "Can only indirectify direct input operands!"); 8983 8984 // Memory operands really want the address of the value. 8985 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8986 8987 // There is no longer a Value* corresponding to this operand. 8988 OpInfo.CallOperandVal = nullptr; 8989 8990 // It is now an indirect operand. 8991 OpInfo.isIndirect = true; 8992 } 8993 8994 } 8995 8996 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8997 std::vector<SDValue> AsmNodeOperands; 8998 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8999 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9000 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9001 9002 // If we have a !srcloc metadata node associated with it, we want to attach 9003 // this to the ultimately generated inline asm machineinstr. To do this, we 9004 // pass in the third operand as this (potentially null) inline asm MDNode. 9005 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9006 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9007 9008 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9009 // bits as operand 3. 9010 AsmNodeOperands.push_back(DAG.getTargetConstant( 9011 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9012 9013 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9014 // this, assign virtual and physical registers for inputs and otput. 9015 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9016 // Assign Registers. 9017 SDISelAsmOperandInfo &RefOpInfo = 9018 OpInfo.isMatchingInputConstraint() 9019 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9020 : OpInfo; 9021 const auto RegError = 9022 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9023 if (RegError) { 9024 const MachineFunction &MF = DAG.getMachineFunction(); 9025 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9026 const char *RegName = TRI.getName(*RegError); 9027 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9028 "' allocated for constraint '" + 9029 Twine(OpInfo.ConstraintCode) + 9030 "' does not match required type"); 9031 return; 9032 } 9033 9034 auto DetectWriteToReservedRegister = [&]() { 9035 const MachineFunction &MF = DAG.getMachineFunction(); 9036 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9037 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9038 if (Register::isPhysicalRegister(Reg) && 9039 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9040 const char *RegName = TRI.getName(Reg); 9041 emitInlineAsmError(Call, "write to reserved register '" + 9042 Twine(RegName) + "'"); 9043 return true; 9044 } 9045 } 9046 return false; 9047 }; 9048 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9049 (OpInfo.Type == InlineAsm::isInput && 9050 !OpInfo.isMatchingInputConstraint())) && 9051 "Only address as input operand is allowed."); 9052 9053 switch (OpInfo.Type) { 9054 case InlineAsm::isOutput: 9055 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9056 unsigned ConstraintID = 9057 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9058 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9059 "Failed to convert memory constraint code to constraint id."); 9060 9061 // Add information to the INLINEASM node to know about this output. 9062 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9063 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9064 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9065 MVT::i32)); 9066 AsmNodeOperands.push_back(OpInfo.CallOperand); 9067 } else { 9068 // Otherwise, this outputs to a register (directly for C_Register / 9069 // C_RegisterClass, and a target-defined fashion for 9070 // C_Immediate/C_Other). Find a register that we can use. 9071 if (OpInfo.AssignedRegs.Regs.empty()) { 9072 emitInlineAsmError( 9073 Call, "couldn't allocate output register for constraint '" + 9074 Twine(OpInfo.ConstraintCode) + "'"); 9075 return; 9076 } 9077 9078 if (DetectWriteToReservedRegister()) 9079 return; 9080 9081 // Add information to the INLINEASM node to know that this register is 9082 // set. 9083 OpInfo.AssignedRegs.AddInlineAsmOperands( 9084 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9085 : InlineAsm::Kind_RegDef, 9086 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9087 } 9088 break; 9089 9090 case InlineAsm::isInput: 9091 case InlineAsm::isLabel: { 9092 SDValue InOperandVal = OpInfo.CallOperand; 9093 9094 if (OpInfo.isMatchingInputConstraint()) { 9095 // If this is required to match an output register we have already set, 9096 // just use its register. 9097 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9098 AsmNodeOperands); 9099 unsigned OpFlag = 9100 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9101 if (InlineAsm::isRegDefKind(OpFlag) || 9102 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9103 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9104 if (OpInfo.isIndirect) { 9105 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9106 emitInlineAsmError(Call, "inline asm not supported yet: " 9107 "don't know how to handle tied " 9108 "indirect register inputs"); 9109 return; 9110 } 9111 9112 SmallVector<unsigned, 4> Regs; 9113 MachineFunction &MF = DAG.getMachineFunction(); 9114 MachineRegisterInfo &MRI = MF.getRegInfo(); 9115 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9116 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9117 Register TiedReg = R->getReg(); 9118 MVT RegVT = R->getSimpleValueType(0); 9119 const TargetRegisterClass *RC = 9120 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9121 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9122 : TRI.getMinimalPhysRegClass(TiedReg); 9123 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9124 for (unsigned i = 0; i != NumRegs; ++i) 9125 Regs.push_back(MRI.createVirtualRegister(RC)); 9126 9127 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9128 9129 SDLoc dl = getCurSDLoc(); 9130 // Use the produced MatchedRegs object to 9131 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 9132 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9133 true, OpInfo.getMatchedOperand(), dl, 9134 DAG, AsmNodeOperands); 9135 break; 9136 } 9137 9138 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9139 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9140 "Unexpected number of operands"); 9141 // Add information to the INLINEASM node to know about this input. 9142 // See InlineAsm.h isUseOperandTiedToDef. 9143 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9144 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9145 OpInfo.getMatchedOperand()); 9146 AsmNodeOperands.push_back(DAG.getTargetConstant( 9147 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9148 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9149 break; 9150 } 9151 9152 // Treat indirect 'X' constraint as memory. 9153 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9154 OpInfo.isIndirect) 9155 OpInfo.ConstraintType = TargetLowering::C_Memory; 9156 9157 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9158 OpInfo.ConstraintType == TargetLowering::C_Other) { 9159 std::vector<SDValue> Ops; 9160 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9161 Ops, DAG); 9162 if (Ops.empty()) { 9163 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9164 if (isa<ConstantSDNode>(InOperandVal)) { 9165 emitInlineAsmError(Call, "value out of range for constraint '" + 9166 Twine(OpInfo.ConstraintCode) + "'"); 9167 return; 9168 } 9169 9170 emitInlineAsmError(Call, 9171 "invalid operand for inline asm constraint '" + 9172 Twine(OpInfo.ConstraintCode) + "'"); 9173 return; 9174 } 9175 9176 // Add information to the INLINEASM node to know about this input. 9177 unsigned ResOpType = 9178 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9179 AsmNodeOperands.push_back(DAG.getTargetConstant( 9180 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9181 llvm::append_range(AsmNodeOperands, Ops); 9182 break; 9183 } 9184 9185 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9186 assert((OpInfo.isIndirect || 9187 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9188 "Operand must be indirect to be a mem!"); 9189 assert(InOperandVal.getValueType() == 9190 TLI.getPointerTy(DAG.getDataLayout()) && 9191 "Memory operands expect pointer values"); 9192 9193 unsigned ConstraintID = 9194 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9195 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9196 "Failed to convert memory constraint code to constraint id."); 9197 9198 // Add information to the INLINEASM node to know about this input. 9199 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9200 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9201 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9202 getCurSDLoc(), 9203 MVT::i32)); 9204 AsmNodeOperands.push_back(InOperandVal); 9205 break; 9206 } 9207 9208 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9209 assert(InOperandVal.getValueType() == 9210 TLI.getPointerTy(DAG.getDataLayout()) && 9211 "Address operands expect pointer values"); 9212 9213 unsigned ConstraintID = 9214 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9215 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9216 "Failed to convert memory constraint code to constraint id."); 9217 9218 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9219 9220 SDValue AsmOp = InOperandVal; 9221 if (isFunction(InOperandVal)) { 9222 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9223 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9224 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9225 InOperandVal.getValueType(), 9226 GA->getOffset()); 9227 } 9228 9229 // Add information to the INLINEASM node to know about this input. 9230 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9231 9232 AsmNodeOperands.push_back( 9233 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9234 9235 AsmNodeOperands.push_back(AsmOp); 9236 break; 9237 } 9238 9239 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9240 OpInfo.ConstraintType == TargetLowering::C_Register) && 9241 "Unknown constraint type!"); 9242 9243 // TODO: Support this. 9244 if (OpInfo.isIndirect) { 9245 emitInlineAsmError( 9246 Call, "Don't know how to handle indirect register inputs yet " 9247 "for constraint '" + 9248 Twine(OpInfo.ConstraintCode) + "'"); 9249 return; 9250 } 9251 9252 // Copy the input into the appropriate registers. 9253 if (OpInfo.AssignedRegs.Regs.empty()) { 9254 emitInlineAsmError(Call, 9255 "couldn't allocate input reg for constraint '" + 9256 Twine(OpInfo.ConstraintCode) + "'"); 9257 return; 9258 } 9259 9260 if (DetectWriteToReservedRegister()) 9261 return; 9262 9263 SDLoc dl = getCurSDLoc(); 9264 9265 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 9266 &Call); 9267 9268 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9269 dl, DAG, AsmNodeOperands); 9270 break; 9271 } 9272 case InlineAsm::isClobber: 9273 // Add the clobbered value to the operand list, so that the register 9274 // allocator is aware that the physreg got clobbered. 9275 if (!OpInfo.AssignedRegs.Regs.empty()) 9276 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9277 false, 0, getCurSDLoc(), DAG, 9278 AsmNodeOperands); 9279 break; 9280 } 9281 } 9282 9283 // Finish up input operands. Set the input chain and add the flag last. 9284 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9285 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 9286 9287 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9288 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9289 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9290 Flag = Chain.getValue(1); 9291 9292 // Do additional work to generate outputs. 9293 9294 SmallVector<EVT, 1> ResultVTs; 9295 SmallVector<SDValue, 1> ResultValues; 9296 SmallVector<SDValue, 8> OutChains; 9297 9298 llvm::Type *CallResultType = Call.getType(); 9299 ArrayRef<Type *> ResultTypes; 9300 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9301 ResultTypes = StructResult->elements(); 9302 else if (!CallResultType->isVoidTy()) 9303 ResultTypes = ArrayRef(CallResultType); 9304 9305 auto CurResultType = ResultTypes.begin(); 9306 auto handleRegAssign = [&](SDValue V) { 9307 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9308 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9309 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9310 ++CurResultType; 9311 // If the type of the inline asm call site return value is different but has 9312 // same size as the type of the asm output bitcast it. One example of this 9313 // is for vectors with different width / number of elements. This can 9314 // happen for register classes that can contain multiple different value 9315 // types. The preg or vreg allocated may not have the same VT as was 9316 // expected. 9317 // 9318 // This can also happen for a return value that disagrees with the register 9319 // class it is put in, eg. a double in a general-purpose register on a 9320 // 32-bit machine. 9321 if (ResultVT != V.getValueType() && 9322 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9323 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9324 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9325 V.getValueType().isInteger()) { 9326 // If a result value was tied to an input value, the computed result 9327 // may have a wider width than the expected result. Extract the 9328 // relevant portion. 9329 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9330 } 9331 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9332 ResultVTs.push_back(ResultVT); 9333 ResultValues.push_back(V); 9334 }; 9335 9336 // Deal with output operands. 9337 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9338 if (OpInfo.Type == InlineAsm::isOutput) { 9339 SDValue Val; 9340 // Skip trivial output operands. 9341 if (OpInfo.AssignedRegs.Regs.empty()) 9342 continue; 9343 9344 switch (OpInfo.ConstraintType) { 9345 case TargetLowering::C_Register: 9346 case TargetLowering::C_RegisterClass: 9347 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9348 Chain, &Flag, &Call); 9349 break; 9350 case TargetLowering::C_Immediate: 9351 case TargetLowering::C_Other: 9352 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9353 OpInfo, DAG); 9354 break; 9355 case TargetLowering::C_Memory: 9356 break; // Already handled. 9357 case TargetLowering::C_Address: 9358 break; // Silence warning. 9359 case TargetLowering::C_Unknown: 9360 assert(false && "Unexpected unknown constraint"); 9361 } 9362 9363 // Indirect output manifest as stores. Record output chains. 9364 if (OpInfo.isIndirect) { 9365 const Value *Ptr = OpInfo.CallOperandVal; 9366 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9367 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9368 MachinePointerInfo(Ptr)); 9369 OutChains.push_back(Store); 9370 } else { 9371 // generate CopyFromRegs to associated registers. 9372 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9373 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9374 for (const SDValue &V : Val->op_values()) 9375 handleRegAssign(V); 9376 } else 9377 handleRegAssign(Val); 9378 } 9379 } 9380 } 9381 9382 // Set results. 9383 if (!ResultValues.empty()) { 9384 assert(CurResultType == ResultTypes.end() && 9385 "Mismatch in number of ResultTypes"); 9386 assert(ResultValues.size() == ResultTypes.size() && 9387 "Mismatch in number of output operands in asm result"); 9388 9389 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9390 DAG.getVTList(ResultVTs), ResultValues); 9391 setValue(&Call, V); 9392 } 9393 9394 // Collect store chains. 9395 if (!OutChains.empty()) 9396 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9397 9398 if (EmitEHLabels) { 9399 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9400 } 9401 9402 // Only Update Root if inline assembly has a memory effect. 9403 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9404 EmitEHLabels) 9405 DAG.setRoot(Chain); 9406 } 9407 9408 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9409 const Twine &Message) { 9410 LLVMContext &Ctx = *DAG.getContext(); 9411 Ctx.emitError(&Call, Message); 9412 9413 // Make sure we leave the DAG in a valid state 9414 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9415 SmallVector<EVT, 1> ValueVTs; 9416 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9417 9418 if (ValueVTs.empty()) 9419 return; 9420 9421 SmallVector<SDValue, 1> Ops; 9422 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9423 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9424 9425 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9426 } 9427 9428 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9429 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9430 MVT::Other, getRoot(), 9431 getValue(I.getArgOperand(0)), 9432 DAG.getSrcValue(I.getArgOperand(0)))); 9433 } 9434 9435 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9437 const DataLayout &DL = DAG.getDataLayout(); 9438 SDValue V = DAG.getVAArg( 9439 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9440 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9441 DL.getABITypeAlign(I.getType()).value()); 9442 DAG.setRoot(V.getValue(1)); 9443 9444 if (I.getType()->isPointerTy()) 9445 V = DAG.getPtrExtOrTrunc( 9446 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9447 setValue(&I, V); 9448 } 9449 9450 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9451 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9452 MVT::Other, getRoot(), 9453 getValue(I.getArgOperand(0)), 9454 DAG.getSrcValue(I.getArgOperand(0)))); 9455 } 9456 9457 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9458 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9459 MVT::Other, getRoot(), 9460 getValue(I.getArgOperand(0)), 9461 getValue(I.getArgOperand(1)), 9462 DAG.getSrcValue(I.getArgOperand(0)), 9463 DAG.getSrcValue(I.getArgOperand(1)))); 9464 } 9465 9466 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9467 const Instruction &I, 9468 SDValue Op) { 9469 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9470 if (!Range) 9471 return Op; 9472 9473 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9474 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9475 return Op; 9476 9477 APInt Lo = CR.getUnsignedMin(); 9478 if (!Lo.isMinValue()) 9479 return Op; 9480 9481 APInt Hi = CR.getUnsignedMax(); 9482 unsigned Bits = std::max(Hi.getActiveBits(), 9483 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9484 9485 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9486 9487 SDLoc SL = getCurSDLoc(); 9488 9489 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9490 DAG.getValueType(SmallVT)); 9491 unsigned NumVals = Op.getNode()->getNumValues(); 9492 if (NumVals == 1) 9493 return ZExt; 9494 9495 SmallVector<SDValue, 4> Ops; 9496 9497 Ops.push_back(ZExt); 9498 for (unsigned I = 1; I != NumVals; ++I) 9499 Ops.push_back(Op.getValue(I)); 9500 9501 return DAG.getMergeValues(Ops, SL); 9502 } 9503 9504 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9505 /// the call being lowered. 9506 /// 9507 /// This is a helper for lowering intrinsics that follow a target calling 9508 /// convention or require stack pointer adjustment. Only a subset of the 9509 /// intrinsic's operands need to participate in the calling convention. 9510 void SelectionDAGBuilder::populateCallLoweringInfo( 9511 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9512 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9513 bool IsPatchPoint) { 9514 TargetLowering::ArgListTy Args; 9515 Args.reserve(NumArgs); 9516 9517 // Populate the argument list. 9518 // Attributes for args start at offset 1, after the return attribute. 9519 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9520 ArgI != ArgE; ++ArgI) { 9521 const Value *V = Call->getOperand(ArgI); 9522 9523 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9524 9525 TargetLowering::ArgListEntry Entry; 9526 Entry.Node = getValue(V); 9527 Entry.Ty = V->getType(); 9528 Entry.setAttributes(Call, ArgI); 9529 Args.push_back(Entry); 9530 } 9531 9532 CLI.setDebugLoc(getCurSDLoc()) 9533 .setChain(getRoot()) 9534 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9535 .setDiscardResult(Call->use_empty()) 9536 .setIsPatchPoint(IsPatchPoint) 9537 .setIsPreallocated( 9538 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9539 } 9540 9541 /// Add a stack map intrinsic call's live variable operands to a stackmap 9542 /// or patchpoint target node's operand list. 9543 /// 9544 /// Constants are converted to TargetConstants purely as an optimization to 9545 /// avoid constant materialization and register allocation. 9546 /// 9547 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9548 /// generate addess computation nodes, and so FinalizeISel can convert the 9549 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9550 /// address materialization and register allocation, but may also be required 9551 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9552 /// alloca in the entry block, then the runtime may assume that the alloca's 9553 /// StackMap location can be read immediately after compilation and that the 9554 /// location is valid at any point during execution (this is similar to the 9555 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9556 /// only available in a register, then the runtime would need to trap when 9557 /// execution reaches the StackMap in order to read the alloca's location. 9558 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9559 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9560 SelectionDAGBuilder &Builder) { 9561 SelectionDAG &DAG = Builder.DAG; 9562 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9563 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9564 9565 // Things on the stack are pointer-typed, meaning that they are already 9566 // legal and can be emitted directly to target nodes. 9567 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9568 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9569 } else { 9570 // Otherwise emit a target independent node to be legalised. 9571 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9572 } 9573 } 9574 } 9575 9576 /// Lower llvm.experimental.stackmap. 9577 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9578 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9579 // [live variables...]) 9580 9581 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9582 9583 SDValue Chain, InFlag, Callee; 9584 SmallVector<SDValue, 32> Ops; 9585 9586 SDLoc DL = getCurSDLoc(); 9587 Callee = getValue(CI.getCalledOperand()); 9588 9589 // The stackmap intrinsic only records the live variables (the arguments 9590 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9591 // intrinsic, this won't be lowered to a function call. This means we don't 9592 // have to worry about calling conventions and target specific lowering code. 9593 // Instead we perform the call lowering right here. 9594 // 9595 // chain, flag = CALLSEQ_START(chain, 0, 0) 9596 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9597 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9598 // 9599 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9600 InFlag = Chain.getValue(1); 9601 9602 // Add the STACKMAP operands, starting with DAG house-keeping. 9603 Ops.push_back(Chain); 9604 Ops.push_back(InFlag); 9605 9606 // Add the <id>, <numShadowBytes> operands. 9607 // 9608 // These do not require legalisation, and can be emitted directly to target 9609 // constant nodes. 9610 SDValue ID = getValue(CI.getArgOperand(0)); 9611 assert(ID.getValueType() == MVT::i64); 9612 SDValue IDConst = DAG.getTargetConstant( 9613 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9614 Ops.push_back(IDConst); 9615 9616 SDValue Shad = getValue(CI.getArgOperand(1)); 9617 assert(Shad.getValueType() == MVT::i32); 9618 SDValue ShadConst = DAG.getTargetConstant( 9619 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9620 Ops.push_back(ShadConst); 9621 9622 // Add the live variables. 9623 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9624 9625 // Create the STACKMAP node. 9626 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9627 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9628 InFlag = Chain.getValue(1); 9629 9630 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL); 9631 9632 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9633 9634 // Set the root to the target-lowered call chain. 9635 DAG.setRoot(Chain); 9636 9637 // Inform the Frame Information that we have a stackmap in this function. 9638 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9639 } 9640 9641 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9642 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9643 const BasicBlock *EHPadBB) { 9644 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9645 // i32 <numBytes>, 9646 // i8* <target>, 9647 // i32 <numArgs>, 9648 // [Args...], 9649 // [live variables...]) 9650 9651 CallingConv::ID CC = CB.getCallingConv(); 9652 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9653 bool HasDef = !CB.getType()->isVoidTy(); 9654 SDLoc dl = getCurSDLoc(); 9655 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9656 9657 // Handle immediate and symbolic callees. 9658 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9659 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9660 /*isTarget=*/true); 9661 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9662 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9663 SDLoc(SymbolicCallee), 9664 SymbolicCallee->getValueType(0)); 9665 9666 // Get the real number of arguments participating in the call <numArgs> 9667 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9668 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9669 9670 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9671 // Intrinsics include all meta-operands up to but not including CC. 9672 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9673 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9674 "Not enough arguments provided to the patchpoint intrinsic"); 9675 9676 // For AnyRegCC the arguments are lowered later on manually. 9677 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9678 Type *ReturnTy = 9679 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9680 9681 TargetLowering::CallLoweringInfo CLI(DAG); 9682 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9683 ReturnTy, true); 9684 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9685 9686 SDNode *CallEnd = Result.second.getNode(); 9687 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9688 CallEnd = CallEnd->getOperand(0).getNode(); 9689 9690 /// Get a call instruction from the call sequence chain. 9691 /// Tail calls are not allowed. 9692 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9693 "Expected a callseq node."); 9694 SDNode *Call = CallEnd->getOperand(0).getNode(); 9695 bool HasGlue = Call->getGluedNode(); 9696 9697 // Replace the target specific call node with the patchable intrinsic. 9698 SmallVector<SDValue, 8> Ops; 9699 9700 // Push the chain. 9701 Ops.push_back(*(Call->op_begin())); 9702 9703 // Optionally, push the glue (if any). 9704 if (HasGlue) 9705 Ops.push_back(*(Call->op_end() - 1)); 9706 9707 // Push the register mask info. 9708 if (HasGlue) 9709 Ops.push_back(*(Call->op_end() - 2)); 9710 else 9711 Ops.push_back(*(Call->op_end() - 1)); 9712 9713 // Add the <id> and <numBytes> constants. 9714 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9715 Ops.push_back(DAG.getTargetConstant( 9716 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9717 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9718 Ops.push_back(DAG.getTargetConstant( 9719 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9720 MVT::i32)); 9721 9722 // Add the callee. 9723 Ops.push_back(Callee); 9724 9725 // Adjust <numArgs> to account for any arguments that have been passed on the 9726 // stack instead. 9727 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9728 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9729 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9730 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9731 9732 // Add the calling convention 9733 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9734 9735 // Add the arguments we omitted previously. The register allocator should 9736 // place these in any free register. 9737 if (IsAnyRegCC) 9738 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9739 Ops.push_back(getValue(CB.getArgOperand(i))); 9740 9741 // Push the arguments from the call instruction. 9742 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9743 Ops.append(Call->op_begin() + 2, e); 9744 9745 // Push live variables for the stack map. 9746 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9747 9748 SDVTList NodeTys; 9749 if (IsAnyRegCC && HasDef) { 9750 // Create the return types based on the intrinsic definition 9751 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9752 SmallVector<EVT, 3> ValueVTs; 9753 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9754 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9755 9756 // There is always a chain and a glue type at the end 9757 ValueVTs.push_back(MVT::Other); 9758 ValueVTs.push_back(MVT::Glue); 9759 NodeTys = DAG.getVTList(ValueVTs); 9760 } else 9761 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9762 9763 // Replace the target specific call node with a PATCHPOINT node. 9764 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9765 9766 // Update the NodeMap. 9767 if (HasDef) { 9768 if (IsAnyRegCC) 9769 setValue(&CB, SDValue(PPV.getNode(), 0)); 9770 else 9771 setValue(&CB, Result.first); 9772 } 9773 9774 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9775 // call sequence. Furthermore the location of the chain and glue can change 9776 // when the AnyReg calling convention is used and the intrinsic returns a 9777 // value. 9778 if (IsAnyRegCC && HasDef) { 9779 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9780 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9781 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9782 } else 9783 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9784 DAG.DeleteNode(Call); 9785 9786 // Inform the Frame Information that we have a patchpoint in this function. 9787 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9788 } 9789 9790 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9791 unsigned Intrinsic) { 9792 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9793 SDValue Op1 = getValue(I.getArgOperand(0)); 9794 SDValue Op2; 9795 if (I.arg_size() > 1) 9796 Op2 = getValue(I.getArgOperand(1)); 9797 SDLoc dl = getCurSDLoc(); 9798 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9799 SDValue Res; 9800 SDNodeFlags SDFlags; 9801 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9802 SDFlags.copyFMF(*FPMO); 9803 9804 switch (Intrinsic) { 9805 case Intrinsic::vector_reduce_fadd: 9806 if (SDFlags.hasAllowReassociation()) 9807 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9808 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9809 SDFlags); 9810 else 9811 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9812 break; 9813 case Intrinsic::vector_reduce_fmul: 9814 if (SDFlags.hasAllowReassociation()) 9815 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9816 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9817 SDFlags); 9818 else 9819 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9820 break; 9821 case Intrinsic::vector_reduce_add: 9822 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9823 break; 9824 case Intrinsic::vector_reduce_mul: 9825 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9826 break; 9827 case Intrinsic::vector_reduce_and: 9828 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9829 break; 9830 case Intrinsic::vector_reduce_or: 9831 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9832 break; 9833 case Intrinsic::vector_reduce_xor: 9834 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9835 break; 9836 case Intrinsic::vector_reduce_smax: 9837 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9838 break; 9839 case Intrinsic::vector_reduce_smin: 9840 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9841 break; 9842 case Intrinsic::vector_reduce_umax: 9843 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9844 break; 9845 case Intrinsic::vector_reduce_umin: 9846 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9847 break; 9848 case Intrinsic::vector_reduce_fmax: 9849 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9850 break; 9851 case Intrinsic::vector_reduce_fmin: 9852 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9853 break; 9854 default: 9855 llvm_unreachable("Unhandled vector reduce intrinsic"); 9856 } 9857 setValue(&I, Res); 9858 } 9859 9860 /// Returns an AttributeList representing the attributes applied to the return 9861 /// value of the given call. 9862 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9863 SmallVector<Attribute::AttrKind, 2> Attrs; 9864 if (CLI.RetSExt) 9865 Attrs.push_back(Attribute::SExt); 9866 if (CLI.RetZExt) 9867 Attrs.push_back(Attribute::ZExt); 9868 if (CLI.IsInReg) 9869 Attrs.push_back(Attribute::InReg); 9870 9871 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9872 Attrs); 9873 } 9874 9875 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9876 /// implementation, which just calls LowerCall. 9877 /// FIXME: When all targets are 9878 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9879 std::pair<SDValue, SDValue> 9880 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9881 // Handle the incoming return values from the call. 9882 CLI.Ins.clear(); 9883 Type *OrigRetTy = CLI.RetTy; 9884 SmallVector<EVT, 4> RetTys; 9885 SmallVector<uint64_t, 4> Offsets; 9886 auto &DL = CLI.DAG.getDataLayout(); 9887 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9888 9889 if (CLI.IsPostTypeLegalization) { 9890 // If we are lowering a libcall after legalization, split the return type. 9891 SmallVector<EVT, 4> OldRetTys; 9892 SmallVector<uint64_t, 4> OldOffsets; 9893 RetTys.swap(OldRetTys); 9894 Offsets.swap(OldOffsets); 9895 9896 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9897 EVT RetVT = OldRetTys[i]; 9898 uint64_t Offset = OldOffsets[i]; 9899 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9900 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9901 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9902 RetTys.append(NumRegs, RegisterVT); 9903 for (unsigned j = 0; j != NumRegs; ++j) 9904 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9905 } 9906 } 9907 9908 SmallVector<ISD::OutputArg, 4> Outs; 9909 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9910 9911 bool CanLowerReturn = 9912 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9913 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9914 9915 SDValue DemoteStackSlot; 9916 int DemoteStackIdx = -100; 9917 if (!CanLowerReturn) { 9918 // FIXME: equivalent assert? 9919 // assert(!CS.hasInAllocaArgument() && 9920 // "sret demotion is incompatible with inalloca"); 9921 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9922 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9923 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9924 DemoteStackIdx = 9925 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9926 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9927 DL.getAllocaAddrSpace()); 9928 9929 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9930 ArgListEntry Entry; 9931 Entry.Node = DemoteStackSlot; 9932 Entry.Ty = StackSlotPtrType; 9933 Entry.IsSExt = false; 9934 Entry.IsZExt = false; 9935 Entry.IsInReg = false; 9936 Entry.IsSRet = true; 9937 Entry.IsNest = false; 9938 Entry.IsByVal = false; 9939 Entry.IsByRef = false; 9940 Entry.IsReturned = false; 9941 Entry.IsSwiftSelf = false; 9942 Entry.IsSwiftAsync = false; 9943 Entry.IsSwiftError = false; 9944 Entry.IsCFGuardTarget = false; 9945 Entry.Alignment = Alignment; 9946 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9947 CLI.NumFixedArgs += 1; 9948 CLI.getArgs()[0].IndirectType = CLI.RetTy; 9949 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9950 9951 // sret demotion isn't compatible with tail-calls, since the sret argument 9952 // points into the callers stack frame. 9953 CLI.IsTailCall = false; 9954 } else { 9955 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9956 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9957 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9958 ISD::ArgFlagsTy Flags; 9959 if (NeedsRegBlock) { 9960 Flags.setInConsecutiveRegs(); 9961 if (I == RetTys.size() - 1) 9962 Flags.setInConsecutiveRegsLast(); 9963 } 9964 EVT VT = RetTys[I]; 9965 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9966 CLI.CallConv, VT); 9967 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9968 CLI.CallConv, VT); 9969 for (unsigned i = 0; i != NumRegs; ++i) { 9970 ISD::InputArg MyFlags; 9971 MyFlags.Flags = Flags; 9972 MyFlags.VT = RegisterVT; 9973 MyFlags.ArgVT = VT; 9974 MyFlags.Used = CLI.IsReturnValueUsed; 9975 if (CLI.RetTy->isPointerTy()) { 9976 MyFlags.Flags.setPointer(); 9977 MyFlags.Flags.setPointerAddrSpace( 9978 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9979 } 9980 if (CLI.RetSExt) 9981 MyFlags.Flags.setSExt(); 9982 if (CLI.RetZExt) 9983 MyFlags.Flags.setZExt(); 9984 if (CLI.IsInReg) 9985 MyFlags.Flags.setInReg(); 9986 CLI.Ins.push_back(MyFlags); 9987 } 9988 } 9989 } 9990 9991 // We push in swifterror return as the last element of CLI.Ins. 9992 ArgListTy &Args = CLI.getArgs(); 9993 if (supportSwiftError()) { 9994 for (const ArgListEntry &Arg : Args) { 9995 if (Arg.IsSwiftError) { 9996 ISD::InputArg MyFlags; 9997 MyFlags.VT = getPointerTy(DL); 9998 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9999 MyFlags.Flags.setSwiftError(); 10000 CLI.Ins.push_back(MyFlags); 10001 } 10002 } 10003 } 10004 10005 // Handle all of the outgoing arguments. 10006 CLI.Outs.clear(); 10007 CLI.OutVals.clear(); 10008 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10009 SmallVector<EVT, 4> ValueVTs; 10010 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10011 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10012 Type *FinalType = Args[i].Ty; 10013 if (Args[i].IsByVal) 10014 FinalType = Args[i].IndirectType; 10015 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10016 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10017 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10018 ++Value) { 10019 EVT VT = ValueVTs[Value]; 10020 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10021 SDValue Op = SDValue(Args[i].Node.getNode(), 10022 Args[i].Node.getResNo() + Value); 10023 ISD::ArgFlagsTy Flags; 10024 10025 // Certain targets (such as MIPS), may have a different ABI alignment 10026 // for a type depending on the context. Give the target a chance to 10027 // specify the alignment it wants. 10028 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10029 Flags.setOrigAlign(OriginalAlignment); 10030 10031 if (Args[i].Ty->isPointerTy()) { 10032 Flags.setPointer(); 10033 Flags.setPointerAddrSpace( 10034 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10035 } 10036 if (Args[i].IsZExt) 10037 Flags.setZExt(); 10038 if (Args[i].IsSExt) 10039 Flags.setSExt(); 10040 if (Args[i].IsInReg) { 10041 // If we are using vectorcall calling convention, a structure that is 10042 // passed InReg - is surely an HVA 10043 if (CLI.CallConv == CallingConv::X86_VectorCall && 10044 isa<StructType>(FinalType)) { 10045 // The first value of a structure is marked 10046 if (0 == Value) 10047 Flags.setHvaStart(); 10048 Flags.setHva(); 10049 } 10050 // Set InReg Flag 10051 Flags.setInReg(); 10052 } 10053 if (Args[i].IsSRet) 10054 Flags.setSRet(); 10055 if (Args[i].IsSwiftSelf) 10056 Flags.setSwiftSelf(); 10057 if (Args[i].IsSwiftAsync) 10058 Flags.setSwiftAsync(); 10059 if (Args[i].IsSwiftError) 10060 Flags.setSwiftError(); 10061 if (Args[i].IsCFGuardTarget) 10062 Flags.setCFGuardTarget(); 10063 if (Args[i].IsByVal) 10064 Flags.setByVal(); 10065 if (Args[i].IsByRef) 10066 Flags.setByRef(); 10067 if (Args[i].IsPreallocated) { 10068 Flags.setPreallocated(); 10069 // Set the byval flag for CCAssignFn callbacks that don't know about 10070 // preallocated. This way we can know how many bytes we should've 10071 // allocated and how many bytes a callee cleanup function will pop. If 10072 // we port preallocated to more targets, we'll have to add custom 10073 // preallocated handling in the various CC lowering callbacks. 10074 Flags.setByVal(); 10075 } 10076 if (Args[i].IsInAlloca) { 10077 Flags.setInAlloca(); 10078 // Set the byval flag for CCAssignFn callbacks that don't know about 10079 // inalloca. This way we can know how many bytes we should've allocated 10080 // and how many bytes a callee cleanup function will pop. If we port 10081 // inalloca to more targets, we'll have to add custom inalloca handling 10082 // in the various CC lowering callbacks. 10083 Flags.setByVal(); 10084 } 10085 Align MemAlign; 10086 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10087 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10088 Flags.setByValSize(FrameSize); 10089 10090 // info is not there but there are cases it cannot get right. 10091 if (auto MA = Args[i].Alignment) 10092 MemAlign = *MA; 10093 else 10094 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10095 } else if (auto MA = Args[i].Alignment) { 10096 MemAlign = *MA; 10097 } else { 10098 MemAlign = OriginalAlignment; 10099 } 10100 Flags.setMemAlign(MemAlign); 10101 if (Args[i].IsNest) 10102 Flags.setNest(); 10103 if (NeedsRegBlock) 10104 Flags.setInConsecutiveRegs(); 10105 10106 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10107 CLI.CallConv, VT); 10108 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10109 CLI.CallConv, VT); 10110 SmallVector<SDValue, 4> Parts(NumParts); 10111 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10112 10113 if (Args[i].IsSExt) 10114 ExtendKind = ISD::SIGN_EXTEND; 10115 else if (Args[i].IsZExt) 10116 ExtendKind = ISD::ZERO_EXTEND; 10117 10118 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10119 // for now. 10120 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10121 CanLowerReturn) { 10122 assert((CLI.RetTy == Args[i].Ty || 10123 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10124 CLI.RetTy->getPointerAddressSpace() == 10125 Args[i].Ty->getPointerAddressSpace())) && 10126 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10127 // Before passing 'returned' to the target lowering code, ensure that 10128 // either the register MVT and the actual EVT are the same size or that 10129 // the return value and argument are extended in the same way; in these 10130 // cases it's safe to pass the argument register value unchanged as the 10131 // return register value (although it's at the target's option whether 10132 // to do so) 10133 // TODO: allow code generation to take advantage of partially preserved 10134 // registers rather than clobbering the entire register when the 10135 // parameter extension method is not compatible with the return 10136 // extension method 10137 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10138 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10139 CLI.RetZExt == Args[i].IsZExt)) 10140 Flags.setReturned(); 10141 } 10142 10143 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10144 CLI.CallConv, ExtendKind); 10145 10146 for (unsigned j = 0; j != NumParts; ++j) { 10147 // if it isn't first piece, alignment must be 1 10148 // For scalable vectors the scalable part is currently handled 10149 // by individual targets, so we just use the known minimum size here. 10150 ISD::OutputArg MyFlags( 10151 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10152 i < CLI.NumFixedArgs, i, 10153 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10154 if (NumParts > 1 && j == 0) 10155 MyFlags.Flags.setSplit(); 10156 else if (j != 0) { 10157 MyFlags.Flags.setOrigAlign(Align(1)); 10158 if (j == NumParts - 1) 10159 MyFlags.Flags.setSplitEnd(); 10160 } 10161 10162 CLI.Outs.push_back(MyFlags); 10163 CLI.OutVals.push_back(Parts[j]); 10164 } 10165 10166 if (NeedsRegBlock && Value == NumValues - 1) 10167 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10168 } 10169 } 10170 10171 SmallVector<SDValue, 4> InVals; 10172 CLI.Chain = LowerCall(CLI, InVals); 10173 10174 // Update CLI.InVals to use outside of this function. 10175 CLI.InVals = InVals; 10176 10177 // Verify that the target's LowerCall behaved as expected. 10178 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10179 "LowerCall didn't return a valid chain!"); 10180 assert((!CLI.IsTailCall || InVals.empty()) && 10181 "LowerCall emitted a return value for a tail call!"); 10182 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10183 "LowerCall didn't emit the correct number of values!"); 10184 10185 // For a tail call, the return value is merely live-out and there aren't 10186 // any nodes in the DAG representing it. Return a special value to 10187 // indicate that a tail call has been emitted and no more Instructions 10188 // should be processed in the current block. 10189 if (CLI.IsTailCall) { 10190 CLI.DAG.setRoot(CLI.Chain); 10191 return std::make_pair(SDValue(), SDValue()); 10192 } 10193 10194 #ifndef NDEBUG 10195 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10196 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10197 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10198 "LowerCall emitted a value with the wrong type!"); 10199 } 10200 #endif 10201 10202 SmallVector<SDValue, 4> ReturnValues; 10203 if (!CanLowerReturn) { 10204 // The instruction result is the result of loading from the 10205 // hidden sret parameter. 10206 SmallVector<EVT, 1> PVTs; 10207 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10208 10209 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10210 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10211 EVT PtrVT = PVTs[0]; 10212 10213 unsigned NumValues = RetTys.size(); 10214 ReturnValues.resize(NumValues); 10215 SmallVector<SDValue, 4> Chains(NumValues); 10216 10217 // An aggregate return value cannot wrap around the address space, so 10218 // offsets to its parts don't wrap either. 10219 SDNodeFlags Flags; 10220 Flags.setNoUnsignedWrap(true); 10221 10222 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10223 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10224 for (unsigned i = 0; i < NumValues; ++i) { 10225 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10226 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10227 PtrVT), Flags); 10228 SDValue L = CLI.DAG.getLoad( 10229 RetTys[i], CLI.DL, CLI.Chain, Add, 10230 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10231 DemoteStackIdx, Offsets[i]), 10232 HiddenSRetAlign); 10233 ReturnValues[i] = L; 10234 Chains[i] = L.getValue(1); 10235 } 10236 10237 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10238 } else { 10239 // Collect the legal value parts into potentially illegal values 10240 // that correspond to the original function's return values. 10241 std::optional<ISD::NodeType> AssertOp; 10242 if (CLI.RetSExt) 10243 AssertOp = ISD::AssertSext; 10244 else if (CLI.RetZExt) 10245 AssertOp = ISD::AssertZext; 10246 unsigned CurReg = 0; 10247 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10248 EVT VT = RetTys[I]; 10249 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10250 CLI.CallConv, VT); 10251 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10252 CLI.CallConv, VT); 10253 10254 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10255 NumRegs, RegisterVT, VT, nullptr, 10256 CLI.CallConv, AssertOp)); 10257 CurReg += NumRegs; 10258 } 10259 10260 // For a function returning void, there is no return value. We can't create 10261 // such a node, so we just return a null return value in that case. In 10262 // that case, nothing will actually look at the value. 10263 if (ReturnValues.empty()) 10264 return std::make_pair(SDValue(), CLI.Chain); 10265 } 10266 10267 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10268 CLI.DAG.getVTList(RetTys), ReturnValues); 10269 return std::make_pair(Res, CLI.Chain); 10270 } 10271 10272 /// Places new result values for the node in Results (their number 10273 /// and types must exactly match those of the original return values of 10274 /// the node), or leaves Results empty, which indicates that the node is not 10275 /// to be custom lowered after all. 10276 void TargetLowering::LowerOperationWrapper(SDNode *N, 10277 SmallVectorImpl<SDValue> &Results, 10278 SelectionDAG &DAG) const { 10279 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10280 10281 if (!Res.getNode()) 10282 return; 10283 10284 // If the original node has one result, take the return value from 10285 // LowerOperation as is. It might not be result number 0. 10286 if (N->getNumValues() == 1) { 10287 Results.push_back(Res); 10288 return; 10289 } 10290 10291 // If the original node has multiple results, then the return node should 10292 // have the same number of results. 10293 assert((N->getNumValues() == Res->getNumValues()) && 10294 "Lowering returned the wrong number of results!"); 10295 10296 // Places new result values base on N result number. 10297 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10298 Results.push_back(Res.getValue(I)); 10299 } 10300 10301 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10302 llvm_unreachable("LowerOperation not implemented for this target!"); 10303 } 10304 10305 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10306 unsigned Reg, 10307 ISD::NodeType ExtendType) { 10308 SDValue Op = getNonRegisterValue(V); 10309 assert((Op.getOpcode() != ISD::CopyFromReg || 10310 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10311 "Copy from a reg to the same reg!"); 10312 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10313 10314 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10315 // If this is an InlineAsm we have to match the registers required, not the 10316 // notional registers required by the type. 10317 10318 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10319 std::nullopt); // This is not an ABI copy. 10320 SDValue Chain = DAG.getEntryNode(); 10321 10322 if (ExtendType == ISD::ANY_EXTEND) { 10323 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10324 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10325 ExtendType = PreferredExtendIt->second; 10326 } 10327 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10328 PendingExports.push_back(Chain); 10329 } 10330 10331 #include "llvm/CodeGen/SelectionDAGISel.h" 10332 10333 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10334 /// entry block, return true. This includes arguments used by switches, since 10335 /// the switch may expand into multiple basic blocks. 10336 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10337 // With FastISel active, we may be splitting blocks, so force creation 10338 // of virtual registers for all non-dead arguments. 10339 if (FastISel) 10340 return A->use_empty(); 10341 10342 const BasicBlock &Entry = A->getParent()->front(); 10343 for (const User *U : A->users()) 10344 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10345 return false; // Use not in entry block. 10346 10347 return true; 10348 } 10349 10350 using ArgCopyElisionMapTy = 10351 DenseMap<const Argument *, 10352 std::pair<const AllocaInst *, const StoreInst *>>; 10353 10354 /// Scan the entry block of the function in FuncInfo for arguments that look 10355 /// like copies into a local alloca. Record any copied arguments in 10356 /// ArgCopyElisionCandidates. 10357 static void 10358 findArgumentCopyElisionCandidates(const DataLayout &DL, 10359 FunctionLoweringInfo *FuncInfo, 10360 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10361 // Record the state of every static alloca used in the entry block. Argument 10362 // allocas are all used in the entry block, so we need approximately as many 10363 // entries as we have arguments. 10364 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10365 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10366 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10367 StaticAllocas.reserve(NumArgs * 2); 10368 10369 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10370 if (!V) 10371 return nullptr; 10372 V = V->stripPointerCasts(); 10373 const auto *AI = dyn_cast<AllocaInst>(V); 10374 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10375 return nullptr; 10376 auto Iter = StaticAllocas.insert({AI, Unknown}); 10377 return &Iter.first->second; 10378 }; 10379 10380 // Look for stores of arguments to static allocas. Look through bitcasts and 10381 // GEPs to handle type coercions, as long as the alloca is fully initialized 10382 // by the store. Any non-store use of an alloca escapes it and any subsequent 10383 // unanalyzed store might write it. 10384 // FIXME: Handle structs initialized with multiple stores. 10385 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10386 // Look for stores, and handle non-store uses conservatively. 10387 const auto *SI = dyn_cast<StoreInst>(&I); 10388 if (!SI) { 10389 // We will look through cast uses, so ignore them completely. 10390 if (I.isCast()) 10391 continue; 10392 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10393 // to allocas. 10394 if (I.isDebugOrPseudoInst()) 10395 continue; 10396 // This is an unknown instruction. Assume it escapes or writes to all 10397 // static alloca operands. 10398 for (const Use &U : I.operands()) { 10399 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10400 *Info = StaticAllocaInfo::Clobbered; 10401 } 10402 continue; 10403 } 10404 10405 // If the stored value is a static alloca, mark it as escaped. 10406 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10407 *Info = StaticAllocaInfo::Clobbered; 10408 10409 // Check if the destination is a static alloca. 10410 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10411 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10412 if (!Info) 10413 continue; 10414 const AllocaInst *AI = cast<AllocaInst>(Dst); 10415 10416 // Skip allocas that have been initialized or clobbered. 10417 if (*Info != StaticAllocaInfo::Unknown) 10418 continue; 10419 10420 // Check if the stored value is an argument, and that this store fully 10421 // initializes the alloca. 10422 // If the argument type has padding bits we can't directly forward a pointer 10423 // as the upper bits may contain garbage. 10424 // Don't elide copies from the same argument twice. 10425 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10426 const auto *Arg = dyn_cast<Argument>(Val); 10427 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10428 Arg->getType()->isEmptyTy() || 10429 DL.getTypeStoreSize(Arg->getType()) != 10430 DL.getTypeAllocSize(AI->getAllocatedType()) || 10431 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10432 ArgCopyElisionCandidates.count(Arg)) { 10433 *Info = StaticAllocaInfo::Clobbered; 10434 continue; 10435 } 10436 10437 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10438 << '\n'); 10439 10440 // Mark this alloca and store for argument copy elision. 10441 *Info = StaticAllocaInfo::Elidable; 10442 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10443 10444 // Stop scanning if we've seen all arguments. This will happen early in -O0 10445 // builds, which is useful, because -O0 builds have large entry blocks and 10446 // many allocas. 10447 if (ArgCopyElisionCandidates.size() == NumArgs) 10448 break; 10449 } 10450 } 10451 10452 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10453 /// ArgVal is a load from a suitable fixed stack object. 10454 static void tryToElideArgumentCopy( 10455 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10456 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10457 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10458 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10459 SDValue ArgVal, bool &ArgHasUses) { 10460 // Check if this is a load from a fixed stack object. 10461 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10462 if (!LNode) 10463 return; 10464 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10465 if (!FINode) 10466 return; 10467 10468 // Check that the fixed stack object is the right size and alignment. 10469 // Look at the alignment that the user wrote on the alloca instead of looking 10470 // at the stack object. 10471 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10472 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10473 const AllocaInst *AI = ArgCopyIter->second.first; 10474 int FixedIndex = FINode->getIndex(); 10475 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10476 int OldIndex = AllocaIndex; 10477 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10478 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10479 LLVM_DEBUG( 10480 dbgs() << " argument copy elision failed due to bad fixed stack " 10481 "object size\n"); 10482 return; 10483 } 10484 Align RequiredAlignment = AI->getAlign(); 10485 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10486 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10487 "greater than stack argument alignment (" 10488 << DebugStr(RequiredAlignment) << " vs " 10489 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10490 return; 10491 } 10492 10493 // Perform the elision. Delete the old stack object and replace its only use 10494 // in the variable info map. Mark the stack object as mutable. 10495 LLVM_DEBUG({ 10496 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10497 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10498 << '\n'; 10499 }); 10500 MFI.RemoveStackObject(OldIndex); 10501 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10502 AllocaIndex = FixedIndex; 10503 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10504 Chains.push_back(ArgVal.getValue(1)); 10505 10506 // Avoid emitting code for the store implementing the copy. 10507 const StoreInst *SI = ArgCopyIter->second.second; 10508 ElidedArgCopyInstrs.insert(SI); 10509 10510 // Check for uses of the argument again so that we can avoid exporting ArgVal 10511 // if it is't used by anything other than the store. 10512 for (const Value *U : Arg.users()) { 10513 if (U != SI) { 10514 ArgHasUses = true; 10515 break; 10516 } 10517 } 10518 } 10519 10520 void SelectionDAGISel::LowerArguments(const Function &F) { 10521 SelectionDAG &DAG = SDB->DAG; 10522 SDLoc dl = SDB->getCurSDLoc(); 10523 const DataLayout &DL = DAG.getDataLayout(); 10524 SmallVector<ISD::InputArg, 16> Ins; 10525 10526 // In Naked functions we aren't going to save any registers. 10527 if (F.hasFnAttribute(Attribute::Naked)) 10528 return; 10529 10530 if (!FuncInfo->CanLowerReturn) { 10531 // Put in an sret pointer parameter before all the other parameters. 10532 SmallVector<EVT, 1> ValueVTs; 10533 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10534 F.getReturnType()->getPointerTo( 10535 DAG.getDataLayout().getAllocaAddrSpace()), 10536 ValueVTs); 10537 10538 // NOTE: Assuming that a pointer will never break down to more than one VT 10539 // or one register. 10540 ISD::ArgFlagsTy Flags; 10541 Flags.setSRet(); 10542 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10543 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10544 ISD::InputArg::NoArgIndex, 0); 10545 Ins.push_back(RetArg); 10546 } 10547 10548 // Look for stores of arguments to static allocas. Mark such arguments with a 10549 // flag to ask the target to give us the memory location of that argument if 10550 // available. 10551 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10552 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10553 ArgCopyElisionCandidates); 10554 10555 // Set up the incoming argument description vector. 10556 for (const Argument &Arg : F.args()) { 10557 unsigned ArgNo = Arg.getArgNo(); 10558 SmallVector<EVT, 4> ValueVTs; 10559 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10560 bool isArgValueUsed = !Arg.use_empty(); 10561 unsigned PartBase = 0; 10562 Type *FinalType = Arg.getType(); 10563 if (Arg.hasAttribute(Attribute::ByVal)) 10564 FinalType = Arg.getParamByValType(); 10565 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10566 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10567 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10568 Value != NumValues; ++Value) { 10569 EVT VT = ValueVTs[Value]; 10570 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10571 ISD::ArgFlagsTy Flags; 10572 10573 10574 if (Arg.getType()->isPointerTy()) { 10575 Flags.setPointer(); 10576 Flags.setPointerAddrSpace( 10577 cast<PointerType>(Arg.getType())->getAddressSpace()); 10578 } 10579 if (Arg.hasAttribute(Attribute::ZExt)) 10580 Flags.setZExt(); 10581 if (Arg.hasAttribute(Attribute::SExt)) 10582 Flags.setSExt(); 10583 if (Arg.hasAttribute(Attribute::InReg)) { 10584 // If we are using vectorcall calling convention, a structure that is 10585 // passed InReg - is surely an HVA 10586 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10587 isa<StructType>(Arg.getType())) { 10588 // The first value of a structure is marked 10589 if (0 == Value) 10590 Flags.setHvaStart(); 10591 Flags.setHva(); 10592 } 10593 // Set InReg Flag 10594 Flags.setInReg(); 10595 } 10596 if (Arg.hasAttribute(Attribute::StructRet)) 10597 Flags.setSRet(); 10598 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10599 Flags.setSwiftSelf(); 10600 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10601 Flags.setSwiftAsync(); 10602 if (Arg.hasAttribute(Attribute::SwiftError)) 10603 Flags.setSwiftError(); 10604 if (Arg.hasAttribute(Attribute::ByVal)) 10605 Flags.setByVal(); 10606 if (Arg.hasAttribute(Attribute::ByRef)) 10607 Flags.setByRef(); 10608 if (Arg.hasAttribute(Attribute::InAlloca)) { 10609 Flags.setInAlloca(); 10610 // Set the byval flag for CCAssignFn callbacks that don't know about 10611 // inalloca. This way we can know how many bytes we should've allocated 10612 // and how many bytes a callee cleanup function will pop. If we port 10613 // inalloca to more targets, we'll have to add custom inalloca handling 10614 // in the various CC lowering callbacks. 10615 Flags.setByVal(); 10616 } 10617 if (Arg.hasAttribute(Attribute::Preallocated)) { 10618 Flags.setPreallocated(); 10619 // Set the byval flag for CCAssignFn callbacks that don't know about 10620 // preallocated. This way we can know how many bytes we should've 10621 // allocated and how many bytes a callee cleanup function will pop. If 10622 // we port preallocated to more targets, we'll have to add custom 10623 // preallocated handling in the various CC lowering callbacks. 10624 Flags.setByVal(); 10625 } 10626 10627 // Certain targets (such as MIPS), may have a different ABI alignment 10628 // for a type depending on the context. Give the target a chance to 10629 // specify the alignment it wants. 10630 const Align OriginalAlignment( 10631 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10632 Flags.setOrigAlign(OriginalAlignment); 10633 10634 Align MemAlign; 10635 Type *ArgMemTy = nullptr; 10636 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10637 Flags.isByRef()) { 10638 if (!ArgMemTy) 10639 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10640 10641 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10642 10643 // For in-memory arguments, size and alignment should be passed from FE. 10644 // BE will guess if this info is not there but there are cases it cannot 10645 // get right. 10646 if (auto ParamAlign = Arg.getParamStackAlign()) 10647 MemAlign = *ParamAlign; 10648 else if ((ParamAlign = Arg.getParamAlign())) 10649 MemAlign = *ParamAlign; 10650 else 10651 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10652 if (Flags.isByRef()) 10653 Flags.setByRefSize(MemSize); 10654 else 10655 Flags.setByValSize(MemSize); 10656 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10657 MemAlign = *ParamAlign; 10658 } else { 10659 MemAlign = OriginalAlignment; 10660 } 10661 Flags.setMemAlign(MemAlign); 10662 10663 if (Arg.hasAttribute(Attribute::Nest)) 10664 Flags.setNest(); 10665 if (NeedsRegBlock) 10666 Flags.setInConsecutiveRegs(); 10667 if (ArgCopyElisionCandidates.count(&Arg)) 10668 Flags.setCopyElisionCandidate(); 10669 if (Arg.hasAttribute(Attribute::Returned)) 10670 Flags.setReturned(); 10671 10672 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10673 *CurDAG->getContext(), F.getCallingConv(), VT); 10674 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10675 *CurDAG->getContext(), F.getCallingConv(), VT); 10676 for (unsigned i = 0; i != NumRegs; ++i) { 10677 // For scalable vectors, use the minimum size; individual targets 10678 // are responsible for handling scalable vector arguments and 10679 // return values. 10680 ISD::InputArg MyFlags( 10681 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10682 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10683 if (NumRegs > 1 && i == 0) 10684 MyFlags.Flags.setSplit(); 10685 // if it isn't first piece, alignment must be 1 10686 else if (i > 0) { 10687 MyFlags.Flags.setOrigAlign(Align(1)); 10688 if (i == NumRegs - 1) 10689 MyFlags.Flags.setSplitEnd(); 10690 } 10691 Ins.push_back(MyFlags); 10692 } 10693 if (NeedsRegBlock && Value == NumValues - 1) 10694 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10695 PartBase += VT.getStoreSize().getKnownMinValue(); 10696 } 10697 } 10698 10699 // Call the target to set up the argument values. 10700 SmallVector<SDValue, 8> InVals; 10701 SDValue NewRoot = TLI->LowerFormalArguments( 10702 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10703 10704 // Verify that the target's LowerFormalArguments behaved as expected. 10705 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10706 "LowerFormalArguments didn't return a valid chain!"); 10707 assert(InVals.size() == Ins.size() && 10708 "LowerFormalArguments didn't emit the correct number of values!"); 10709 LLVM_DEBUG({ 10710 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10711 assert(InVals[i].getNode() && 10712 "LowerFormalArguments emitted a null value!"); 10713 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10714 "LowerFormalArguments emitted a value with the wrong type!"); 10715 } 10716 }); 10717 10718 // Update the DAG with the new chain value resulting from argument lowering. 10719 DAG.setRoot(NewRoot); 10720 10721 // Set up the argument values. 10722 unsigned i = 0; 10723 if (!FuncInfo->CanLowerReturn) { 10724 // Create a virtual register for the sret pointer, and put in a copy 10725 // from the sret argument into it. 10726 SmallVector<EVT, 1> ValueVTs; 10727 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10728 F.getReturnType()->getPointerTo( 10729 DAG.getDataLayout().getAllocaAddrSpace()), 10730 ValueVTs); 10731 MVT VT = ValueVTs[0].getSimpleVT(); 10732 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10733 std::optional<ISD::NodeType> AssertOp; 10734 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10735 nullptr, F.getCallingConv(), AssertOp); 10736 10737 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10738 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10739 Register SRetReg = 10740 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10741 FuncInfo->DemoteRegister = SRetReg; 10742 NewRoot = 10743 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10744 DAG.setRoot(NewRoot); 10745 10746 // i indexes lowered arguments. Bump it past the hidden sret argument. 10747 ++i; 10748 } 10749 10750 SmallVector<SDValue, 4> Chains; 10751 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10752 for (const Argument &Arg : F.args()) { 10753 SmallVector<SDValue, 4> ArgValues; 10754 SmallVector<EVT, 4> ValueVTs; 10755 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10756 unsigned NumValues = ValueVTs.size(); 10757 if (NumValues == 0) 10758 continue; 10759 10760 bool ArgHasUses = !Arg.use_empty(); 10761 10762 // Elide the copying store if the target loaded this argument from a 10763 // suitable fixed stack object. 10764 if (Ins[i].Flags.isCopyElisionCandidate()) { 10765 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10766 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10767 InVals[i], ArgHasUses); 10768 } 10769 10770 // If this argument is unused then remember its value. It is used to generate 10771 // debugging information. 10772 bool isSwiftErrorArg = 10773 TLI->supportSwiftError() && 10774 Arg.hasAttribute(Attribute::SwiftError); 10775 if (!ArgHasUses && !isSwiftErrorArg) { 10776 SDB->setUnusedArgValue(&Arg, InVals[i]); 10777 10778 // Also remember any frame index for use in FastISel. 10779 if (FrameIndexSDNode *FI = 10780 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10781 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10782 } 10783 10784 for (unsigned Val = 0; Val != NumValues; ++Val) { 10785 EVT VT = ValueVTs[Val]; 10786 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10787 F.getCallingConv(), VT); 10788 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10789 *CurDAG->getContext(), F.getCallingConv(), VT); 10790 10791 // Even an apparent 'unused' swifterror argument needs to be returned. So 10792 // we do generate a copy for it that can be used on return from the 10793 // function. 10794 if (ArgHasUses || isSwiftErrorArg) { 10795 std::optional<ISD::NodeType> AssertOp; 10796 if (Arg.hasAttribute(Attribute::SExt)) 10797 AssertOp = ISD::AssertSext; 10798 else if (Arg.hasAttribute(Attribute::ZExt)) 10799 AssertOp = ISD::AssertZext; 10800 10801 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10802 PartVT, VT, nullptr, 10803 F.getCallingConv(), AssertOp)); 10804 } 10805 10806 i += NumParts; 10807 } 10808 10809 // We don't need to do anything else for unused arguments. 10810 if (ArgValues.empty()) 10811 continue; 10812 10813 // Note down frame index. 10814 if (FrameIndexSDNode *FI = 10815 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10816 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10817 10818 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10819 SDB->getCurSDLoc()); 10820 10821 SDB->setValue(&Arg, Res); 10822 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10823 // We want to associate the argument with the frame index, among 10824 // involved operands, that correspond to the lowest address. The 10825 // getCopyFromParts function, called earlier, is swapping the order of 10826 // the operands to BUILD_PAIR depending on endianness. The result of 10827 // that swapping is that the least significant bits of the argument will 10828 // be in the first operand of the BUILD_PAIR node, and the most 10829 // significant bits will be in the second operand. 10830 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10831 if (LoadSDNode *LNode = 10832 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10833 if (FrameIndexSDNode *FI = 10834 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10835 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10836 } 10837 10838 // Analyses past this point are naive and don't expect an assertion. 10839 if (Res.getOpcode() == ISD::AssertZext) 10840 Res = Res.getOperand(0); 10841 10842 // Update the SwiftErrorVRegDefMap. 10843 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10844 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10845 if (Register::isVirtualRegister(Reg)) 10846 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10847 Reg); 10848 } 10849 10850 // If this argument is live outside of the entry block, insert a copy from 10851 // wherever we got it to the vreg that other BB's will reference it as. 10852 if (Res.getOpcode() == ISD::CopyFromReg) { 10853 // If we can, though, try to skip creating an unnecessary vreg. 10854 // FIXME: This isn't very clean... it would be nice to make this more 10855 // general. 10856 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10857 if (Register::isVirtualRegister(Reg)) { 10858 FuncInfo->ValueMap[&Arg] = Reg; 10859 continue; 10860 } 10861 } 10862 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10863 FuncInfo->InitializeRegForValue(&Arg); 10864 SDB->CopyToExportRegsIfNeeded(&Arg); 10865 } 10866 } 10867 10868 if (!Chains.empty()) { 10869 Chains.push_back(NewRoot); 10870 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10871 } 10872 10873 DAG.setRoot(NewRoot); 10874 10875 assert(i == InVals.size() && "Argument register count mismatch!"); 10876 10877 // If any argument copy elisions occurred and we have debug info, update the 10878 // stale frame indices used in the dbg.declare variable info table. 10879 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10880 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10881 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10882 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10883 if (I != ArgCopyElisionFrameIndexMap.end()) 10884 VI.Slot = I->second; 10885 } 10886 } 10887 10888 // Finally, if the target has anything special to do, allow it to do so. 10889 emitFunctionEntryCode(); 10890 } 10891 10892 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10893 /// ensure constants are generated when needed. Remember the virtual registers 10894 /// that need to be added to the Machine PHI nodes as input. We cannot just 10895 /// directly add them, because expansion might result in multiple MBB's for one 10896 /// BB. As such, the start of the BB might correspond to a different MBB than 10897 /// the end. 10898 void 10899 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10900 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10901 10902 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10903 10904 // Check PHI nodes in successors that expect a value to be available from this 10905 // block. 10906 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 10907 if (!isa<PHINode>(SuccBB->begin())) continue; 10908 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10909 10910 // If this terminator has multiple identical successors (common for 10911 // switches), only handle each succ once. 10912 if (!SuccsHandled.insert(SuccMBB).second) 10913 continue; 10914 10915 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10916 10917 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10918 // nodes and Machine PHI nodes, but the incoming operands have not been 10919 // emitted yet. 10920 for (const PHINode &PN : SuccBB->phis()) { 10921 // Ignore dead phi's. 10922 if (PN.use_empty()) 10923 continue; 10924 10925 // Skip empty types 10926 if (PN.getType()->isEmptyTy()) 10927 continue; 10928 10929 unsigned Reg; 10930 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10931 10932 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 10933 unsigned &RegOut = ConstantsOut[C]; 10934 if (RegOut == 0) { 10935 RegOut = FuncInfo.CreateRegs(C); 10936 // We need to zero/sign extend ConstantInt phi operands to match 10937 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10938 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10939 if (auto *CI = dyn_cast<ConstantInt>(C)) 10940 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10941 : ISD::ZERO_EXTEND; 10942 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10943 } 10944 Reg = RegOut; 10945 } else { 10946 DenseMap<const Value *, Register>::iterator I = 10947 FuncInfo.ValueMap.find(PHIOp); 10948 if (I != FuncInfo.ValueMap.end()) 10949 Reg = I->second; 10950 else { 10951 assert(isa<AllocaInst>(PHIOp) && 10952 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10953 "Didn't codegen value into a register!??"); 10954 Reg = FuncInfo.CreateRegs(PHIOp); 10955 CopyValueToVirtualRegister(PHIOp, Reg); 10956 } 10957 } 10958 10959 // Remember that this register needs to added to the machine PHI node as 10960 // the input for this MBB. 10961 SmallVector<EVT, 4> ValueVTs; 10962 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10963 for (EVT VT : ValueVTs) { 10964 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10965 for (unsigned i = 0; i != NumRegisters; ++i) 10966 FuncInfo.PHINodesToUpdate.push_back( 10967 std::make_pair(&*MBBI++, Reg + i)); 10968 Reg += NumRegisters; 10969 } 10970 } 10971 } 10972 10973 ConstantsOut.clear(); 10974 } 10975 10976 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10977 MachineFunction::iterator I(MBB); 10978 if (++I == FuncInfo.MF->end()) 10979 return nullptr; 10980 return &*I; 10981 } 10982 10983 /// During lowering new call nodes can be created (such as memset, etc.). 10984 /// Those will become new roots of the current DAG, but complications arise 10985 /// when they are tail calls. In such cases, the call lowering will update 10986 /// the root, but the builder still needs to know that a tail call has been 10987 /// lowered in order to avoid generating an additional return. 10988 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10989 // If the node is null, we do have a tail call. 10990 if (MaybeTC.getNode() != nullptr) 10991 DAG.setRoot(MaybeTC); 10992 else 10993 HasTailCall = true; 10994 } 10995 10996 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10997 MachineBasicBlock *SwitchMBB, 10998 MachineBasicBlock *DefaultMBB) { 10999 MachineFunction *CurMF = FuncInfo.MF; 11000 MachineBasicBlock *NextMBB = nullptr; 11001 MachineFunction::iterator BBI(W.MBB); 11002 if (++BBI != FuncInfo.MF->end()) 11003 NextMBB = &*BBI; 11004 11005 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11006 11007 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11008 11009 if (Size == 2 && W.MBB == SwitchMBB) { 11010 // If any two of the cases has the same destination, and if one value 11011 // is the same as the other, but has one bit unset that the other has set, 11012 // use bit manipulation to do two compares at once. For example: 11013 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11014 // TODO: This could be extended to merge any 2 cases in switches with 3 11015 // cases. 11016 // TODO: Handle cases where W.CaseBB != SwitchBB. 11017 CaseCluster &Small = *W.FirstCluster; 11018 CaseCluster &Big = *W.LastCluster; 11019 11020 if (Small.Low == Small.High && Big.Low == Big.High && 11021 Small.MBB == Big.MBB) { 11022 const APInt &SmallValue = Small.Low->getValue(); 11023 const APInt &BigValue = Big.Low->getValue(); 11024 11025 // Check that there is only one bit different. 11026 APInt CommonBit = BigValue ^ SmallValue; 11027 if (CommonBit.isPowerOf2()) { 11028 SDValue CondLHS = getValue(Cond); 11029 EVT VT = CondLHS.getValueType(); 11030 SDLoc DL = getCurSDLoc(); 11031 11032 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11033 DAG.getConstant(CommonBit, DL, VT)); 11034 SDValue Cond = DAG.getSetCC( 11035 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11036 ISD::SETEQ); 11037 11038 // Update successor info. 11039 // Both Small and Big will jump to Small.BB, so we sum up the 11040 // probabilities. 11041 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11042 if (BPI) 11043 addSuccessorWithProb( 11044 SwitchMBB, DefaultMBB, 11045 // The default destination is the first successor in IR. 11046 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11047 else 11048 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11049 11050 // Insert the true branch. 11051 SDValue BrCond = 11052 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11053 DAG.getBasicBlock(Small.MBB)); 11054 // Insert the false branch. 11055 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11056 DAG.getBasicBlock(DefaultMBB)); 11057 11058 DAG.setRoot(BrCond); 11059 return; 11060 } 11061 } 11062 } 11063 11064 if (TM.getOptLevel() != CodeGenOpt::None) { 11065 // Here, we order cases by probability so the most likely case will be 11066 // checked first. However, two clusters can have the same probability in 11067 // which case their relative ordering is non-deterministic. So we use Low 11068 // as a tie-breaker as clusters are guaranteed to never overlap. 11069 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11070 [](const CaseCluster &a, const CaseCluster &b) { 11071 return a.Prob != b.Prob ? 11072 a.Prob > b.Prob : 11073 a.Low->getValue().slt(b.Low->getValue()); 11074 }); 11075 11076 // Rearrange the case blocks so that the last one falls through if possible 11077 // without changing the order of probabilities. 11078 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11079 --I; 11080 if (I->Prob > W.LastCluster->Prob) 11081 break; 11082 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11083 std::swap(*I, *W.LastCluster); 11084 break; 11085 } 11086 } 11087 } 11088 11089 // Compute total probability. 11090 BranchProbability DefaultProb = W.DefaultProb; 11091 BranchProbability UnhandledProbs = DefaultProb; 11092 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11093 UnhandledProbs += I->Prob; 11094 11095 MachineBasicBlock *CurMBB = W.MBB; 11096 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11097 bool FallthroughUnreachable = false; 11098 MachineBasicBlock *Fallthrough; 11099 if (I == W.LastCluster) { 11100 // For the last cluster, fall through to the default destination. 11101 Fallthrough = DefaultMBB; 11102 FallthroughUnreachable = isa<UnreachableInst>( 11103 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11104 } else { 11105 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11106 CurMF->insert(BBI, Fallthrough); 11107 // Put Cond in a virtual register to make it available from the new blocks. 11108 ExportFromCurrentBlock(Cond); 11109 } 11110 UnhandledProbs -= I->Prob; 11111 11112 switch (I->Kind) { 11113 case CC_JumpTable: { 11114 // FIXME: Optimize away range check based on pivot comparisons. 11115 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11116 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11117 11118 // The jump block hasn't been inserted yet; insert it here. 11119 MachineBasicBlock *JumpMBB = JT->MBB; 11120 CurMF->insert(BBI, JumpMBB); 11121 11122 auto JumpProb = I->Prob; 11123 auto FallthroughProb = UnhandledProbs; 11124 11125 // If the default statement is a target of the jump table, we evenly 11126 // distribute the default probability to successors of CurMBB. Also 11127 // update the probability on the edge from JumpMBB to Fallthrough. 11128 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11129 SE = JumpMBB->succ_end(); 11130 SI != SE; ++SI) { 11131 if (*SI == DefaultMBB) { 11132 JumpProb += DefaultProb / 2; 11133 FallthroughProb -= DefaultProb / 2; 11134 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11135 JumpMBB->normalizeSuccProbs(); 11136 break; 11137 } 11138 } 11139 11140 if (FallthroughUnreachable) 11141 JTH->FallthroughUnreachable = true; 11142 11143 if (!JTH->FallthroughUnreachable) 11144 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11145 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11146 CurMBB->normalizeSuccProbs(); 11147 11148 // The jump table header will be inserted in our current block, do the 11149 // range check, and fall through to our fallthrough block. 11150 JTH->HeaderBB = CurMBB; 11151 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11152 11153 // If we're in the right place, emit the jump table header right now. 11154 if (CurMBB == SwitchMBB) { 11155 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11156 JTH->Emitted = true; 11157 } 11158 break; 11159 } 11160 case CC_BitTests: { 11161 // FIXME: Optimize away range check based on pivot comparisons. 11162 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11163 11164 // The bit test blocks haven't been inserted yet; insert them here. 11165 for (BitTestCase &BTC : BTB->Cases) 11166 CurMF->insert(BBI, BTC.ThisBB); 11167 11168 // Fill in fields of the BitTestBlock. 11169 BTB->Parent = CurMBB; 11170 BTB->Default = Fallthrough; 11171 11172 BTB->DefaultProb = UnhandledProbs; 11173 // If the cases in bit test don't form a contiguous range, we evenly 11174 // distribute the probability on the edge to Fallthrough to two 11175 // successors of CurMBB. 11176 if (!BTB->ContiguousRange) { 11177 BTB->Prob += DefaultProb / 2; 11178 BTB->DefaultProb -= DefaultProb / 2; 11179 } 11180 11181 if (FallthroughUnreachable) 11182 BTB->FallthroughUnreachable = true; 11183 11184 // If we're in the right place, emit the bit test header right now. 11185 if (CurMBB == SwitchMBB) { 11186 visitBitTestHeader(*BTB, SwitchMBB); 11187 BTB->Emitted = true; 11188 } 11189 break; 11190 } 11191 case CC_Range: { 11192 const Value *RHS, *LHS, *MHS; 11193 ISD::CondCode CC; 11194 if (I->Low == I->High) { 11195 // Check Cond == I->Low. 11196 CC = ISD::SETEQ; 11197 LHS = Cond; 11198 RHS=I->Low; 11199 MHS = nullptr; 11200 } else { 11201 // Check I->Low <= Cond <= I->High. 11202 CC = ISD::SETLE; 11203 LHS = I->Low; 11204 MHS = Cond; 11205 RHS = I->High; 11206 } 11207 11208 // If Fallthrough is unreachable, fold away the comparison. 11209 if (FallthroughUnreachable) 11210 CC = ISD::SETTRUE; 11211 11212 // The false probability is the sum of all unhandled cases. 11213 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11214 getCurSDLoc(), I->Prob, UnhandledProbs); 11215 11216 if (CurMBB == SwitchMBB) 11217 visitSwitchCase(CB, SwitchMBB); 11218 else 11219 SL->SwitchCases.push_back(CB); 11220 11221 break; 11222 } 11223 } 11224 CurMBB = Fallthrough; 11225 } 11226 } 11227 11228 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11229 CaseClusterIt First, 11230 CaseClusterIt Last) { 11231 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11232 if (X.Prob != CC.Prob) 11233 return X.Prob > CC.Prob; 11234 11235 // Ties are broken by comparing the case value. 11236 return X.Low->getValue().slt(CC.Low->getValue()); 11237 }); 11238 } 11239 11240 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11241 const SwitchWorkListItem &W, 11242 Value *Cond, 11243 MachineBasicBlock *SwitchMBB) { 11244 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11245 "Clusters not sorted?"); 11246 11247 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11248 11249 // Balance the tree based on branch probabilities to create a near-optimal (in 11250 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11251 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11252 CaseClusterIt LastLeft = W.FirstCluster; 11253 CaseClusterIt FirstRight = W.LastCluster; 11254 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11255 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11256 11257 // Move LastLeft and FirstRight towards each other from opposite directions to 11258 // find a partitioning of the clusters which balances the probability on both 11259 // sides. If LeftProb and RightProb are equal, alternate which side is 11260 // taken to ensure 0-probability nodes are distributed evenly. 11261 unsigned I = 0; 11262 while (LastLeft + 1 < FirstRight) { 11263 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11264 LeftProb += (++LastLeft)->Prob; 11265 else 11266 RightProb += (--FirstRight)->Prob; 11267 I++; 11268 } 11269 11270 while (true) { 11271 // Our binary search tree differs from a typical BST in that ours can have up 11272 // to three values in each leaf. The pivot selection above doesn't take that 11273 // into account, which means the tree might require more nodes and be less 11274 // efficient. We compensate for this here. 11275 11276 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11277 unsigned NumRight = W.LastCluster - FirstRight + 1; 11278 11279 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11280 // If one side has less than 3 clusters, and the other has more than 3, 11281 // consider taking a cluster from the other side. 11282 11283 if (NumLeft < NumRight) { 11284 // Consider moving the first cluster on the right to the left side. 11285 CaseCluster &CC = *FirstRight; 11286 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11287 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11288 if (LeftSideRank <= RightSideRank) { 11289 // Moving the cluster to the left does not demote it. 11290 ++LastLeft; 11291 ++FirstRight; 11292 continue; 11293 } 11294 } else { 11295 assert(NumRight < NumLeft); 11296 // Consider moving the last element on the left to the right side. 11297 CaseCluster &CC = *LastLeft; 11298 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11299 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11300 if (RightSideRank <= LeftSideRank) { 11301 // Moving the cluster to the right does not demot it. 11302 --LastLeft; 11303 --FirstRight; 11304 continue; 11305 } 11306 } 11307 } 11308 break; 11309 } 11310 11311 assert(LastLeft + 1 == FirstRight); 11312 assert(LastLeft >= W.FirstCluster); 11313 assert(FirstRight <= W.LastCluster); 11314 11315 // Use the first element on the right as pivot since we will make less-than 11316 // comparisons against it. 11317 CaseClusterIt PivotCluster = FirstRight; 11318 assert(PivotCluster > W.FirstCluster); 11319 assert(PivotCluster <= W.LastCluster); 11320 11321 CaseClusterIt FirstLeft = W.FirstCluster; 11322 CaseClusterIt LastRight = W.LastCluster; 11323 11324 const ConstantInt *Pivot = PivotCluster->Low; 11325 11326 // New blocks will be inserted immediately after the current one. 11327 MachineFunction::iterator BBI(W.MBB); 11328 ++BBI; 11329 11330 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11331 // we can branch to its destination directly if it's squeezed exactly in 11332 // between the known lower bound and Pivot - 1. 11333 MachineBasicBlock *LeftMBB; 11334 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11335 FirstLeft->Low == W.GE && 11336 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11337 LeftMBB = FirstLeft->MBB; 11338 } else { 11339 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11340 FuncInfo.MF->insert(BBI, LeftMBB); 11341 WorkList.push_back( 11342 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11343 // Put Cond in a virtual register to make it available from the new blocks. 11344 ExportFromCurrentBlock(Cond); 11345 } 11346 11347 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11348 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11349 // directly if RHS.High equals the current upper bound. 11350 MachineBasicBlock *RightMBB; 11351 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11352 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11353 RightMBB = FirstRight->MBB; 11354 } else { 11355 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11356 FuncInfo.MF->insert(BBI, RightMBB); 11357 WorkList.push_back( 11358 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11359 // Put Cond in a virtual register to make it available from the new blocks. 11360 ExportFromCurrentBlock(Cond); 11361 } 11362 11363 // Create the CaseBlock record that will be used to lower the branch. 11364 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11365 getCurSDLoc(), LeftProb, RightProb); 11366 11367 if (W.MBB == SwitchMBB) 11368 visitSwitchCase(CB, SwitchMBB); 11369 else 11370 SL->SwitchCases.push_back(CB); 11371 } 11372 11373 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11374 // from the swith statement. 11375 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11376 BranchProbability PeeledCaseProb) { 11377 if (PeeledCaseProb == BranchProbability::getOne()) 11378 return BranchProbability::getZero(); 11379 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11380 11381 uint32_t Numerator = CaseProb.getNumerator(); 11382 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11383 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11384 } 11385 11386 // Try to peel the top probability case if it exceeds the threshold. 11387 // Return current MachineBasicBlock for the switch statement if the peeling 11388 // does not occur. 11389 // If the peeling is performed, return the newly created MachineBasicBlock 11390 // for the peeled switch statement. Also update Clusters to remove the peeled 11391 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11392 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11393 const SwitchInst &SI, CaseClusterVector &Clusters, 11394 BranchProbability &PeeledCaseProb) { 11395 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11396 // Don't perform if there is only one cluster or optimizing for size. 11397 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11398 TM.getOptLevel() == CodeGenOpt::None || 11399 SwitchMBB->getParent()->getFunction().hasMinSize()) 11400 return SwitchMBB; 11401 11402 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11403 unsigned PeeledCaseIndex = 0; 11404 bool SwitchPeeled = false; 11405 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11406 CaseCluster &CC = Clusters[Index]; 11407 if (CC.Prob < TopCaseProb) 11408 continue; 11409 TopCaseProb = CC.Prob; 11410 PeeledCaseIndex = Index; 11411 SwitchPeeled = true; 11412 } 11413 if (!SwitchPeeled) 11414 return SwitchMBB; 11415 11416 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11417 << TopCaseProb << "\n"); 11418 11419 // Record the MBB for the peeled switch statement. 11420 MachineFunction::iterator BBI(SwitchMBB); 11421 ++BBI; 11422 MachineBasicBlock *PeeledSwitchMBB = 11423 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11424 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11425 11426 ExportFromCurrentBlock(SI.getCondition()); 11427 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11428 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11429 nullptr, nullptr, TopCaseProb.getCompl()}; 11430 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11431 11432 Clusters.erase(PeeledCaseIt); 11433 for (CaseCluster &CC : Clusters) { 11434 LLVM_DEBUG( 11435 dbgs() << "Scale the probablity for one cluster, before scaling: " 11436 << CC.Prob << "\n"); 11437 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11438 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11439 } 11440 PeeledCaseProb = TopCaseProb; 11441 return PeeledSwitchMBB; 11442 } 11443 11444 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11445 // Extract cases from the switch. 11446 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11447 CaseClusterVector Clusters; 11448 Clusters.reserve(SI.getNumCases()); 11449 for (auto I : SI.cases()) { 11450 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11451 const ConstantInt *CaseVal = I.getCaseValue(); 11452 BranchProbability Prob = 11453 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11454 : BranchProbability(1, SI.getNumCases() + 1); 11455 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11456 } 11457 11458 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11459 11460 // Cluster adjacent cases with the same destination. We do this at all 11461 // optimization levels because it's cheap to do and will make codegen faster 11462 // if there are many clusters. 11463 sortAndRangeify(Clusters); 11464 11465 // The branch probablity of the peeled case. 11466 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11467 MachineBasicBlock *PeeledSwitchMBB = 11468 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11469 11470 // If there is only the default destination, jump there directly. 11471 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11472 if (Clusters.empty()) { 11473 assert(PeeledSwitchMBB == SwitchMBB); 11474 SwitchMBB->addSuccessor(DefaultMBB); 11475 if (DefaultMBB != NextBlock(SwitchMBB)) { 11476 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11477 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11478 } 11479 return; 11480 } 11481 11482 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11483 SL->findBitTestClusters(Clusters, &SI); 11484 11485 LLVM_DEBUG({ 11486 dbgs() << "Case clusters: "; 11487 for (const CaseCluster &C : Clusters) { 11488 if (C.Kind == CC_JumpTable) 11489 dbgs() << "JT:"; 11490 if (C.Kind == CC_BitTests) 11491 dbgs() << "BT:"; 11492 11493 C.Low->getValue().print(dbgs(), true); 11494 if (C.Low != C.High) { 11495 dbgs() << '-'; 11496 C.High->getValue().print(dbgs(), true); 11497 } 11498 dbgs() << ' '; 11499 } 11500 dbgs() << '\n'; 11501 }); 11502 11503 assert(!Clusters.empty()); 11504 SwitchWorkList WorkList; 11505 CaseClusterIt First = Clusters.begin(); 11506 CaseClusterIt Last = Clusters.end() - 1; 11507 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11508 // Scale the branchprobability for DefaultMBB if the peel occurs and 11509 // DefaultMBB is not replaced. 11510 if (PeeledCaseProb != BranchProbability::getZero() && 11511 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11512 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11513 WorkList.push_back( 11514 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11515 11516 while (!WorkList.empty()) { 11517 SwitchWorkListItem W = WorkList.pop_back_val(); 11518 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11519 11520 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11521 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11522 // For optimized builds, lower large range as a balanced binary tree. 11523 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11524 continue; 11525 } 11526 11527 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11528 } 11529 } 11530 11531 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11532 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11533 auto DL = getCurSDLoc(); 11534 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11535 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11536 } 11537 11538 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11539 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11540 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11541 11542 SDLoc DL = getCurSDLoc(); 11543 SDValue V = getValue(I.getOperand(0)); 11544 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11545 11546 if (VT.isScalableVector()) { 11547 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11548 return; 11549 } 11550 11551 // Use VECTOR_SHUFFLE for the fixed-length vector 11552 // to maintain existing behavior. 11553 SmallVector<int, 8> Mask; 11554 unsigned NumElts = VT.getVectorMinNumElements(); 11555 for (unsigned i = 0; i != NumElts; ++i) 11556 Mask.push_back(NumElts - 1 - i); 11557 11558 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11559 } 11560 11561 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11562 auto DL = getCurSDLoc(); 11563 SDValue InVec = getValue(I.getOperand(0)); 11564 EVT OutVT = 11565 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11566 11567 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11568 11569 // ISD Node needs the input vectors split into two equal parts 11570 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11571 DAG.getVectorIdxConstant(0, DL)); 11572 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11573 DAG.getVectorIdxConstant(OutNumElts, DL)); 11574 11575 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11576 // legalisation and combines. 11577 if (OutVT.isFixedLengthVector()) { 11578 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11579 createStrideMask(0, 2, OutNumElts)); 11580 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11581 createStrideMask(1, 2, OutNumElts)); 11582 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11583 setValue(&I, Res); 11584 return; 11585 } 11586 11587 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11588 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11589 setValue(&I, Res); 11590 return; 11591 } 11592 11593 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11594 auto DL = getCurSDLoc(); 11595 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11596 SDValue InVec0 = getValue(I.getOperand(0)); 11597 SDValue InVec1 = getValue(I.getOperand(1)); 11598 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11599 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11600 11601 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11602 // legalisation and combines. 11603 if (OutVT.isFixedLengthVector()) { 11604 unsigned NumElts = InVT.getVectorMinNumElements(); 11605 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11606 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11607 createInterleaveMask(NumElts, 2))); 11608 return; 11609 } 11610 11611 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11612 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11613 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11614 Res.getValue(1)); 11615 setValue(&I, Res); 11616 return; 11617 } 11618 11619 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11620 SmallVector<EVT, 4> ValueVTs; 11621 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11622 ValueVTs); 11623 unsigned NumValues = ValueVTs.size(); 11624 if (NumValues == 0) return; 11625 11626 SmallVector<SDValue, 4> Values(NumValues); 11627 SDValue Op = getValue(I.getOperand(0)); 11628 11629 for (unsigned i = 0; i != NumValues; ++i) 11630 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11631 SDValue(Op.getNode(), Op.getResNo() + i)); 11632 11633 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11634 DAG.getVTList(ValueVTs), Values)); 11635 } 11636 11637 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11638 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11639 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11640 11641 SDLoc DL = getCurSDLoc(); 11642 SDValue V1 = getValue(I.getOperand(0)); 11643 SDValue V2 = getValue(I.getOperand(1)); 11644 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11645 11646 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11647 if (VT.isScalableVector()) { 11648 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11649 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11650 DAG.getConstant(Imm, DL, IdxVT))); 11651 return; 11652 } 11653 11654 unsigned NumElts = VT.getVectorNumElements(); 11655 11656 uint64_t Idx = (NumElts + Imm) % NumElts; 11657 11658 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11659 SmallVector<int, 8> Mask; 11660 for (unsigned i = 0; i < NumElts; ++i) 11661 Mask.push_back(Idx + i); 11662 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11663 } 11664 11665 // Consider the following MIR after SelectionDAG, which produces output in 11666 // phyregs in the first case or virtregs in the second case. 11667 // 11668 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 11669 // %5:gr32 = COPY $ebx 11670 // %6:gr32 = COPY $edx 11671 // %1:gr32 = COPY %6:gr32 11672 // %0:gr32 = COPY %5:gr32 11673 // 11674 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 11675 // %1:gr32 = COPY %6:gr32 11676 // %0:gr32 = COPY %5:gr32 11677 // 11678 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 11679 // Given %1, we'd like to return $edx in the first case and %6 in the second. 11680 // 11681 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 11682 // to a single virtreg (such as %0). The remaining outputs monotonically 11683 // increase in virtreg number from there. If a callbr has no outputs, then it 11684 // should not have a corresponding callbr landingpad; in fact, the callbr 11685 // landingpad would not even be able to refer to such a callbr. 11686 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 11687 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 11688 // There is definitely at least one copy. 11689 assert(MI->getOpcode() == TargetOpcode::COPY && 11690 "start of copy chain MUST be COPY"); 11691 Reg = MI->getOperand(1).getReg(); 11692 MI = MRI.def_begin(Reg)->getParent(); 11693 // There may be an optional second copy. 11694 if (MI->getOpcode() == TargetOpcode::COPY) { 11695 assert(Reg.isVirtual() && "expected COPY of virtual register"); 11696 Reg = MI->getOperand(1).getReg(); 11697 assert(Reg.isPhysical() && "expected COPY of physical register"); 11698 MI = MRI.def_begin(Reg)->getParent(); 11699 } 11700 // The start of the chain must be an INLINEASM_BR. 11701 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 11702 "end of copy chain MUST be INLINEASM_BR"); 11703 return Reg; 11704 } 11705 11706 // We must do this walk rather than the simpler 11707 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 11708 // otherwise we will end up with copies of virtregs only valid along direct 11709 // edges. 11710 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 11711 SmallVector<EVT, 8> ResultVTs; 11712 SmallVector<SDValue, 8> ResultValues; 11713 const auto *CBR = 11714 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 11715 11716 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11717 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 11718 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11719 11720 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 11721 SDValue Chain = DAG.getRoot(); 11722 11723 // Re-parse the asm constraints string. 11724 TargetLowering::AsmOperandInfoVector TargetConstraints = 11725 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 11726 for (auto &T : TargetConstraints) { 11727 SDISelAsmOperandInfo OpInfo(T); 11728 if (OpInfo.Type != InlineAsm::isOutput) 11729 continue; 11730 11731 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 11732 // individual constraint. 11733 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 11734 11735 switch (OpInfo.ConstraintType) { 11736 case TargetLowering::C_Register: 11737 case TargetLowering::C_RegisterClass: { 11738 // Fill in OpInfo.AssignedRegs.Regs. 11739 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 11740 11741 // getRegistersForValue may produce 1 to many registers based on whether 11742 // the OpInfo.ConstraintVT is legal on the target or not. 11743 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 11744 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 11745 if (Register::isPhysicalRegister(OriginalDef)) 11746 FuncInfo.MBB->addLiveIn(OriginalDef); 11747 // Update the assigned registers to use the original defs. 11748 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 11749 } 11750 11751 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 11752 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 11753 ResultValues.push_back(V); 11754 ResultVTs.push_back(OpInfo.ConstraintVT); 11755 break; 11756 } 11757 case TargetLowering::C_Other: { 11758 SDValue Flag; 11759 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 11760 OpInfo, DAG); 11761 ++InitialDef; 11762 ResultValues.push_back(V); 11763 ResultVTs.push_back(OpInfo.ConstraintVT); 11764 break; 11765 } 11766 default: 11767 break; 11768 } 11769 } 11770 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11771 DAG.getVTList(ResultVTs), ResultValues); 11772 setValue(&I, V); 11773 } 11774