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/TargetTransformInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/Analysis/VectorUtils.h" 32 #include "llvm/CodeGen/Analysis.h" 33 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 34 #include "llvm/CodeGen/CodeGenCommonISel.h" 35 #include "llvm/CodeGen/FunctionLoweringInfo.h" 36 #include "llvm/CodeGen/GCMetadata.h" 37 #include "llvm/CodeGen/ISDOpcodes.h" 38 #include "llvm/CodeGen/MachineBasicBlock.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineInstrBuilder.h" 42 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 43 #include "llvm/CodeGen/MachineMemOperand.h" 44 #include "llvm/CodeGen/MachineModuleInfo.h" 45 #include "llvm/CodeGen/MachineOperand.h" 46 #include "llvm/CodeGen/MachineRegisterInfo.h" 47 #include "llvm/CodeGen/SelectionDAG.h" 48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 49 #include "llvm/CodeGen/StackMaps.h" 50 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 51 #include "llvm/CodeGen/TargetFrameLowering.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetOpcodes.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/TargetSubtargetInfo.h" 56 #include "llvm/CodeGen/WinEHFuncInfo.h" 57 #include "llvm/IR/Argument.h" 58 #include "llvm/IR/Attributes.h" 59 #include "llvm/IR/BasicBlock.h" 60 #include "llvm/IR/CFG.h" 61 #include "llvm/IR/CallingConv.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/ConstantRange.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugInfo.h" 67 #include "llvm/IR/DebugInfoMetadata.h" 68 #include "llvm/IR/DerivedTypes.h" 69 #include "llvm/IR/DiagnosticInfo.h" 70 #include "llvm/IR/EHPersonalities.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GetElementPtrTypeIterator.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/IntrinsicsAArch64.h" 79 #include "llvm/IR/IntrinsicsAMDGPU.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/MemoryModelRelaxationAnnotations.h" 83 #include "llvm/IR/Metadata.h" 84 #include "llvm/IR/Module.h" 85 #include "llvm/IR/Operator.h" 86 #include "llvm/IR/PatternMatch.h" 87 #include "llvm/IR/Statepoint.h" 88 #include "llvm/IR/Type.h" 89 #include "llvm/IR/User.h" 90 #include "llvm/IR/Value.h" 91 #include "llvm/MC/MCContext.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/InstructionCost.h" 98 #include "llvm/Support/MathExtras.h" 99 #include "llvm/Support/raw_ostream.h" 100 #include "llvm/Target/TargetIntrinsicInfo.h" 101 #include "llvm/Target/TargetMachine.h" 102 #include "llvm/Target/TargetOptions.h" 103 #include "llvm/TargetParser/Triple.h" 104 #include "llvm/Transforms/Utils/Local.h" 105 #include <cstddef> 106 #include <limits> 107 #include <optional> 108 #include <tuple> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 using namespace SwitchCG; 113 114 #define DEBUG_TYPE "isel" 115 116 /// LimitFloatPrecision - Generate low-precision inline sequences for 117 /// some float libcalls (6, 8 or 12 bits). 118 static unsigned LimitFloatPrecision; 119 120 static cl::opt<bool> 121 InsertAssertAlign("insert-assert-align", cl::init(true), 122 cl::desc("Insert the experimental `assertalign` node."), 123 cl::ReallyHidden); 124 125 static cl::opt<unsigned, true> 126 LimitFPPrecision("limit-float-precision", 127 cl::desc("Generate low-precision inline sequences " 128 "for some float libcalls"), 129 cl::location(LimitFloatPrecision), cl::Hidden, 130 cl::init(0)); 131 132 static cl::opt<unsigned> SwitchPeelThreshold( 133 "switch-peel-threshold", cl::Hidden, cl::init(66), 134 cl::desc("Set the case probability threshold for peeling the case from a " 135 "switch statement. A value greater than 100 will void this " 136 "optimization")); 137 138 // Limit the width of DAG chains. This is important in general to prevent 139 // DAG-based analysis from blowing up. For example, alias analysis and 140 // load clustering may not complete in reasonable time. It is difficult to 141 // recognize and avoid this situation within each individual analysis, and 142 // future analyses are likely to have the same behavior. Limiting DAG width is 143 // the safe approach and will be especially important with global DAGs. 144 // 145 // MaxParallelChains default is arbitrarily high to avoid affecting 146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 147 // sequence over this should have been converted to llvm.memcpy by the 148 // frontend. It is easy to induce this behavior with .ll code such as: 149 // %buffer = alloca [4096 x i8] 150 // %data = load [4096 x i8]* %argPtr 151 // store [4096 x i8] %data, [4096 x i8]* %buffer 152 static const unsigned MaxParallelChains = 64; 153 154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 155 const SDValue *Parts, unsigned NumParts, 156 MVT PartVT, EVT ValueVT, const Value *V, 157 SDValue InChain, 158 std::optional<CallingConv::ID> CC); 159 160 /// getCopyFromParts - Create a value that contains the specified legal parts 161 /// combined into the value they represent. If the parts combine to a type 162 /// larger than ValueVT then AssertOp can be used to specify whether the extra 163 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 164 /// (ISD::AssertSext). 165 static SDValue 166 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 167 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 168 SDValue InChain, 169 std::optional<CallingConv::ID> CC = std::nullopt, 170 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 171 // Let the target assemble the parts if it wants to 172 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 173 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 174 PartVT, ValueVT, CC)) 175 return Val; 176 177 if (ValueVT.isVector()) 178 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 179 InChain, CC); 180 181 assert(NumParts > 0 && "No parts to assemble!"); 182 SDValue Val = Parts[0]; 183 184 if (NumParts > 1) { 185 // Assemble the value from multiple parts. 186 if (ValueVT.isInteger()) { 187 unsigned PartBits = PartVT.getSizeInBits(); 188 unsigned ValueBits = ValueVT.getSizeInBits(); 189 190 // Assemble the power of 2 part. 191 unsigned RoundParts = llvm::bit_floor(NumParts); 192 unsigned RoundBits = PartBits * RoundParts; 193 EVT RoundVT = RoundBits == ValueBits ? 194 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 195 SDValue Lo, Hi; 196 197 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 198 199 if (RoundParts > 2) { 200 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V, 201 InChain); 202 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2, 203 PartVT, HalfVT, V, InChain); 204 } else { 205 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 206 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 207 } 208 209 if (DAG.getDataLayout().isBigEndian()) 210 std::swap(Lo, Hi); 211 212 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 213 214 if (RoundParts < NumParts) { 215 // Assemble the trailing non-power-of-2 part. 216 unsigned OddParts = NumParts - RoundParts; 217 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 218 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 219 OddVT, V, InChain, CC); 220 221 // Combine the round and odd parts. 222 Lo = Val; 223 if (DAG.getDataLayout().isBigEndian()) 224 std::swap(Lo, Hi); 225 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 226 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 227 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 228 DAG.getConstant(Lo.getValueSizeInBits(), DL, 229 TLI.getShiftAmountTy( 230 TotalVT, DAG.getDataLayout()))); 231 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 232 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 233 } 234 } else if (PartVT.isFloatingPoint()) { 235 // FP split into multiple FP parts (for ppcf128) 236 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 237 "Unexpected split"); 238 SDValue Lo, Hi; 239 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 240 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 241 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 242 std::swap(Lo, Hi); 243 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 244 } else { 245 // FP split into integer parts (soft fp) 246 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 247 !PartVT.isVector() && "Unexpected split"); 248 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 249 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, 250 InChain, CC); 251 } 252 } 253 254 // There is now one part, held in Val. Correct it to match ValueVT. 255 // PartEVT is the type of the register class that holds the value. 256 // ValueVT is the type of the inline asm operation. 257 EVT PartEVT = Val.getValueType(); 258 259 if (PartEVT == ValueVT) 260 return Val; 261 262 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 263 ValueVT.bitsLT(PartEVT)) { 264 // For an FP value in an integer part, we need to truncate to the right 265 // width first. 266 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 267 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 268 } 269 270 // Handle types that have the same size. 271 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 272 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 273 274 // Handle types with different sizes. 275 if (PartEVT.isInteger() && ValueVT.isInteger()) { 276 if (ValueVT.bitsLT(PartEVT)) { 277 // For a truncate, see if we have any information to 278 // indicate whether the truncated bits will always be 279 // zero or sign-extension. 280 if (AssertOp) 281 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 282 DAG.getValueType(ValueVT)); 283 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 284 } 285 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 286 } 287 288 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 289 // FP_ROUND's are always exact here. 290 if (ValueVT.bitsLT(Val.getValueType())) { 291 292 SDValue NoChange = 293 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 294 295 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr( 296 llvm::Attribute::StrictFP)) { 297 return DAG.getNode(ISD::STRICT_FP_ROUND, DL, 298 DAG.getVTList(ValueVT, MVT::Other), InChain, Val, 299 NoChange); 300 } 301 302 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange); 303 } 304 305 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 306 } 307 308 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 309 // then truncating. 310 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 311 ValueVT.bitsLT(PartEVT)) { 312 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 313 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 314 } 315 316 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 317 } 318 319 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 320 const Twine &ErrMsg) { 321 const Instruction *I = dyn_cast_or_null<Instruction>(V); 322 if (!V) 323 return Ctx.emitError(ErrMsg); 324 325 const char *AsmError = ", possible invalid constraint for vector type"; 326 if (const CallInst *CI = dyn_cast<CallInst>(I)) 327 if (CI->isInlineAsm()) 328 return Ctx.emitError(I, ErrMsg + AsmError); 329 330 return Ctx.emitError(I, ErrMsg); 331 } 332 333 /// getCopyFromPartsVector - Create a value that contains the specified legal 334 /// parts combined into the value they represent. If the parts combine to a 335 /// type larger than ValueVT then AssertOp can be used to specify whether the 336 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 337 /// ValueVT (ISD::AssertSext). 338 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 339 const SDValue *Parts, unsigned NumParts, 340 MVT PartVT, EVT ValueVT, const Value *V, 341 SDValue InChain, 342 std::optional<CallingConv::ID> CallConv) { 343 assert(ValueVT.isVector() && "Not a vector value"); 344 assert(NumParts > 0 && "No parts to assemble!"); 345 const bool IsABIRegCopy = CallConv.has_value(); 346 347 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 348 SDValue Val = Parts[0]; 349 350 // Handle a multi-element vector. 351 if (NumParts > 1) { 352 EVT IntermediateVT; 353 MVT RegisterVT; 354 unsigned NumIntermediates; 355 unsigned NumRegs; 356 357 if (IsABIRegCopy) { 358 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 359 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 360 NumIntermediates, RegisterVT); 361 } else { 362 NumRegs = 363 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 364 NumIntermediates, RegisterVT); 365 } 366 367 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 368 NumParts = NumRegs; // Silence a compiler warning. 369 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 370 assert(RegisterVT.getSizeInBits() == 371 Parts[0].getSimpleValueType().getSizeInBits() && 372 "Part type sizes don't match!"); 373 374 // Assemble the parts into intermediate operands. 375 SmallVector<SDValue, 8> Ops(NumIntermediates); 376 if (NumIntermediates == NumParts) { 377 // If the register was not expanded, truncate or copy the value, 378 // as appropriate. 379 for (unsigned i = 0; i != NumParts; ++i) 380 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT, 381 V, InChain, CallConv); 382 } else if (NumParts > 0) { 383 // If the intermediate type was expanded, build the intermediate 384 // operands from the parts. 385 assert(NumParts % NumIntermediates == 0 && 386 "Must expand into a divisible number of parts!"); 387 unsigned Factor = NumParts / NumIntermediates; 388 for (unsigned i = 0; i != NumIntermediates; ++i) 389 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT, 390 IntermediateVT, V, InChain, CallConv); 391 } 392 393 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 394 // intermediate operands. 395 EVT BuiltVectorTy = 396 IntermediateVT.isVector() 397 ? EVT::getVectorVT( 398 *DAG.getContext(), IntermediateVT.getScalarType(), 399 IntermediateVT.getVectorElementCount() * NumParts) 400 : EVT::getVectorVT(*DAG.getContext(), 401 IntermediateVT.getScalarType(), 402 NumIntermediates); 403 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 404 : ISD::BUILD_VECTOR, 405 DL, BuiltVectorTy, Ops); 406 } 407 408 // There is now one part, held in Val. Correct it to match ValueVT. 409 EVT PartEVT = Val.getValueType(); 410 411 if (PartEVT == ValueVT) 412 return Val; 413 414 if (PartEVT.isVector()) { 415 // Vector/Vector bitcast. 416 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 417 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 418 419 // If the parts vector has more elements than the value vector, then we 420 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 421 // Extract the elements we want. 422 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 423 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 424 ValueVT.getVectorElementCount().getKnownMinValue()) && 425 (PartEVT.getVectorElementCount().isScalable() == 426 ValueVT.getVectorElementCount().isScalable()) && 427 "Cannot narrow, it would be a lossy transformation"); 428 PartEVT = 429 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 430 ValueVT.getVectorElementCount()); 431 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 432 DAG.getVectorIdxConstant(0, DL)); 433 if (PartEVT == ValueVT) 434 return Val; 435 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 437 438 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 439 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 440 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 441 } 442 443 // Promoted vector extract 444 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 445 } 446 447 // Trivial bitcast if the types are the same size and the destination 448 // vector type is legal. 449 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 450 TLI.isTypeLegal(ValueVT)) 451 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 452 453 if (ValueVT.getVectorNumElements() != 1) { 454 // Certain ABIs require that vectors are passed as integers. For vectors 455 // are the same size, this is an obvious bitcast. 456 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 457 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 458 } else if (ValueVT.bitsLT(PartEVT)) { 459 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 460 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 461 // Drop the extra bits. 462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 463 return DAG.getBitcast(ValueVT, Val); 464 } 465 466 diagnosePossiblyInvalidConstraint( 467 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 468 return DAG.getUNDEF(ValueVT); 469 } 470 471 // Handle cases such as i8 -> <1 x i1> 472 EVT ValueSVT = ValueVT.getVectorElementType(); 473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 474 unsigned ValueSize = ValueSVT.getSizeInBits(); 475 if (ValueSize == PartEVT.getSizeInBits()) { 476 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 477 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 478 // It's possible a scalar floating point type gets softened to integer and 479 // then promoted to a larger integer. If PartEVT is the larger integer 480 // we need to truncate it and then bitcast to the FP type. 481 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 482 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 483 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 484 Val = DAG.getBitcast(ValueSVT, Val); 485 } else { 486 Val = ValueVT.isFloatingPoint() 487 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 488 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 489 } 490 } 491 492 return DAG.getBuildVector(ValueVT, DL, Val); 493 } 494 495 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 496 SDValue Val, SDValue *Parts, unsigned NumParts, 497 MVT PartVT, const Value *V, 498 std::optional<CallingConv::ID> CallConv); 499 500 /// getCopyToParts - Create a series of nodes that contain the specified value 501 /// split into legal parts. If the parts contain more bits than Val, then, for 502 /// integers, ExtendKind can be used to specify how to generate the extra bits. 503 static void 504 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 505 unsigned NumParts, MVT PartVT, const Value *V, 506 std::optional<CallingConv::ID> CallConv = std::nullopt, 507 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 508 // Let the target split the parts if it wants to 509 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 510 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 511 CallConv)) 512 return; 513 EVT ValueVT = Val.getValueType(); 514 515 // Handle the vector case separately. 516 if (ValueVT.isVector()) 517 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 518 CallConv); 519 520 unsigned OrigNumParts = NumParts; 521 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 522 "Copying to an illegal type!"); 523 524 if (NumParts == 0) 525 return; 526 527 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 528 EVT PartEVT = PartVT; 529 if (PartEVT == ValueVT) { 530 assert(NumParts == 1 && "No-op copy with multiple parts!"); 531 Parts[0] = Val; 532 return; 533 } 534 535 unsigned PartBits = PartVT.getSizeInBits(); 536 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 537 // If the parts cover more bits than the value has, promote the value. 538 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 539 assert(NumParts == 1 && "Do not know what to promote to!"); 540 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 541 } else { 542 if (ValueVT.isFloatingPoint()) { 543 // FP values need to be bitcast, then extended if they are being put 544 // into a larger container. 545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 546 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 547 } 548 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 549 ValueVT.isInteger() && 550 "Unknown mismatch!"); 551 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 552 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 553 if (PartVT == MVT::x86mmx) 554 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 555 } 556 } else if (PartBits == ValueVT.getSizeInBits()) { 557 // Different types of the same size. 558 assert(NumParts == 1 && PartEVT != ValueVT); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 561 // If the parts cover less bits than value has, truncate the value. 562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 563 ValueVT.isInteger() && 564 "Unknown mismatch!"); 565 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 566 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 567 if (PartVT == MVT::x86mmx) 568 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 569 } 570 571 // The value may have changed - recompute ValueVT. 572 ValueVT = Val.getValueType(); 573 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 574 "Failed to tile the value with PartVT!"); 575 576 if (NumParts == 1) { 577 if (PartEVT != ValueVT) { 578 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 579 "scalar-to-vector conversion failed"); 580 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 581 } 582 583 Parts[0] = Val; 584 return; 585 } 586 587 // Expand the value into multiple parts. 588 if (NumParts & (NumParts - 1)) { 589 // The number of parts is not a power of 2. Split off and copy the tail. 590 assert(PartVT.isInteger() && ValueVT.isInteger() && 591 "Do not know what to expand to!"); 592 unsigned RoundParts = llvm::bit_floor(NumParts); 593 unsigned RoundBits = RoundParts * PartBits; 594 unsigned OddParts = NumParts - RoundParts; 595 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 596 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 597 598 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 599 CallConv); 600 601 if (DAG.getDataLayout().isBigEndian()) 602 // The odd parts were reversed by getCopyToParts - unreverse them. 603 std::reverse(Parts + RoundParts, Parts + NumParts); 604 605 NumParts = RoundParts; 606 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 607 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 608 } 609 610 // The number of parts is a power of 2. Repeatedly bisect the value using 611 // EXTRACT_ELEMENT. 612 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 613 EVT::getIntegerVT(*DAG.getContext(), 614 ValueVT.getSizeInBits()), 615 Val); 616 617 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 618 for (unsigned i = 0; i < NumParts; i += StepSize) { 619 unsigned ThisBits = StepSize * PartBits / 2; 620 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 621 SDValue &Part0 = Parts[i]; 622 SDValue &Part1 = Parts[i+StepSize/2]; 623 624 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 625 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 626 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 627 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 628 629 if (ThisBits == PartBits && ThisVT != PartVT) { 630 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 631 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 632 } 633 } 634 } 635 636 if (DAG.getDataLayout().isBigEndian()) 637 std::reverse(Parts, Parts + OrigNumParts); 638 } 639 640 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 641 const SDLoc &DL, EVT PartVT) { 642 if (!PartVT.isVector()) 643 return SDValue(); 644 645 EVT ValueVT = Val.getValueType(); 646 EVT PartEVT = PartVT.getVectorElementType(); 647 EVT ValueEVT = ValueVT.getVectorElementType(); 648 ElementCount PartNumElts = PartVT.getVectorElementCount(); 649 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 650 651 // We only support widening vectors with equivalent element types and 652 // fixed/scalable properties. If a target needs to widen a fixed-length type 653 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 654 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 655 PartNumElts.isScalable() != ValueNumElts.isScalable()) 656 return SDValue(); 657 658 // Have a try for bf16 because some targets share its ABI with fp16. 659 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 660 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 661 "Cannot widen to illegal type"); 662 Val = DAG.getNode(ISD::BITCAST, DL, 663 ValueVT.changeVectorElementType(MVT::f16), Val); 664 } else if (PartEVT != ValueEVT) { 665 return SDValue(); 666 } 667 668 // Widening a scalable vector to another scalable vector is done by inserting 669 // the vector into a larger undef one. 670 if (PartNumElts.isScalable()) 671 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 672 Val, DAG.getVectorIdxConstant(0, DL)); 673 674 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 675 // undef elements. 676 SmallVector<SDValue, 16> Ops; 677 DAG.ExtractVectorElements(Val, Ops); 678 SDValue EltUndef = DAG.getUNDEF(PartEVT); 679 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 680 681 // FIXME: Use CONCAT for 2x -> 4x. 682 return DAG.getBuildVector(PartVT, DL, Ops); 683 } 684 685 /// getCopyToPartsVector - Create a series of nodes that contain the specified 686 /// value split into legal parts. 687 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 688 SDValue Val, SDValue *Parts, unsigned NumParts, 689 MVT PartVT, const Value *V, 690 std::optional<CallingConv::ID> CallConv) { 691 EVT ValueVT = Val.getValueType(); 692 assert(ValueVT.isVector() && "Not a vector"); 693 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 694 const bool IsABIRegCopy = CallConv.has_value(); 695 696 if (NumParts == 1) { 697 EVT PartEVT = PartVT; 698 if (PartEVT == ValueVT) { 699 // Nothing to do. 700 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 701 // Bitconvert vector->vector case. 702 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 703 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 704 Val = Widened; 705 } else if (PartVT.isVector() && 706 PartEVT.getVectorElementType().bitsGE( 707 ValueVT.getVectorElementType()) && 708 PartEVT.getVectorElementCount() == 709 ValueVT.getVectorElementCount()) { 710 711 // Promoted vector extract 712 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 713 } else if (PartEVT.isVector() && 714 PartEVT.getVectorElementType() != 715 ValueVT.getVectorElementType() && 716 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 717 TargetLowering::TypeWidenVector) { 718 // Combination of widening and promotion. 719 EVT WidenVT = 720 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 721 PartVT.getVectorElementCount()); 722 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 723 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 724 } else { 725 // Don't extract an integer from a float vector. This can happen if the 726 // FP type gets softened to integer and then promoted. The promotion 727 // prevents it from being picked up by the earlier bitcast case. 728 if (ValueVT.getVectorElementCount().isScalar() && 729 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 730 // If we reach this condition and PartVT is FP, this means that 731 // ValueVT is also FP and both have a different size, otherwise we 732 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here 733 // would be invalid since that would mean the smaller FP type has to 734 // be extended to the larger one. 735 if (PartVT.isFloatingPoint()) { 736 Val = DAG.getBitcast(ValueVT.getScalarType(), Val); 737 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 738 } else 739 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 740 DAG.getVectorIdxConstant(0, DL)); 741 } else { 742 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 743 assert(PartVT.getFixedSizeInBits() > ValueSize && 744 "lossy conversion of vector to scalar type"); 745 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 746 Val = DAG.getBitcast(IntermediateType, Val); 747 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 748 } 749 } 750 751 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 752 Parts[0] = Val; 753 return; 754 } 755 756 // Handle a multi-element vector. 757 EVT IntermediateVT; 758 MVT RegisterVT; 759 unsigned NumIntermediates; 760 unsigned NumRegs; 761 if (IsABIRegCopy) { 762 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 763 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 764 RegisterVT); 765 } else { 766 NumRegs = 767 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 768 NumIntermediates, RegisterVT); 769 } 770 771 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 772 NumParts = NumRegs; // Silence a compiler warning. 773 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 774 775 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 776 "Mixing scalable and fixed vectors when copying in parts"); 777 778 std::optional<ElementCount> DestEltCnt; 779 780 if (IntermediateVT.isVector()) 781 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 782 else 783 DestEltCnt = ElementCount::getFixed(NumIntermediates); 784 785 EVT BuiltVectorTy = EVT::getVectorVT( 786 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 787 788 if (ValueVT == BuiltVectorTy) { 789 // Nothing to do. 790 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 791 // Bitconvert vector->vector case. 792 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 793 } else { 794 if (BuiltVectorTy.getVectorElementType().bitsGT( 795 ValueVT.getVectorElementType())) { 796 // Integer promotion. 797 ValueVT = EVT::getVectorVT(*DAG.getContext(), 798 BuiltVectorTy.getVectorElementType(), 799 ValueVT.getVectorElementCount()); 800 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 801 } 802 803 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 804 Val = Widened; 805 } 806 } 807 808 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 809 810 // Split the vector into intermediate operands. 811 SmallVector<SDValue, 8> Ops(NumIntermediates); 812 for (unsigned i = 0; i != NumIntermediates; ++i) { 813 if (IntermediateVT.isVector()) { 814 // This does something sensible for scalable vectors - see the 815 // definition of EXTRACT_SUBVECTOR for further details. 816 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 817 Ops[i] = 818 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 819 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 820 } else { 821 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 822 DAG.getVectorIdxConstant(i, DL)); 823 } 824 } 825 826 // Split the intermediate operands into legal parts. 827 if (NumParts == NumIntermediates) { 828 // If the register was not expanded, promote or copy the value, 829 // as appropriate. 830 for (unsigned i = 0; i != NumParts; ++i) 831 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 832 } else if (NumParts > 0) { 833 // If the intermediate type was expanded, split each the value into 834 // legal parts. 835 assert(NumIntermediates != 0 && "division by zero"); 836 assert(NumParts % NumIntermediates == 0 && 837 "Must expand into a divisible number of parts!"); 838 unsigned Factor = NumParts / NumIntermediates; 839 for (unsigned i = 0; i != NumIntermediates; ++i) 840 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 841 CallConv); 842 } 843 } 844 845 RegsForValue::RegsForValue(const SmallVector<Register, 4> ®s, MVT regvt, 846 EVT valuevt, std::optional<CallingConv::ID> CC) 847 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 848 RegCount(1, regs.size()), CallConv(CC) {} 849 850 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 851 const DataLayout &DL, Register Reg, Type *Ty, 852 std::optional<CallingConv::ID> CC) { 853 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 854 855 CallConv = CC; 856 857 for (EVT ValueVT : ValueVTs) { 858 unsigned NumRegs = 859 isABIMangled() 860 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 861 : TLI.getNumRegisters(Context, ValueVT); 862 MVT RegisterVT = 863 isABIMangled() 864 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 865 : TLI.getRegisterType(Context, ValueVT); 866 for (unsigned i = 0; i != NumRegs; ++i) 867 Regs.push_back(Reg + i); 868 RegVTs.push_back(RegisterVT); 869 RegCount.push_back(NumRegs); 870 Reg = Reg.id() + NumRegs; 871 } 872 } 873 874 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 875 FunctionLoweringInfo &FuncInfo, 876 const SDLoc &dl, SDValue &Chain, 877 SDValue *Glue, const Value *V) const { 878 // A Value with type {} or [0 x %t] needs no registers. 879 if (ValueVTs.empty()) 880 return SDValue(); 881 882 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 883 884 // Assemble the legal parts into the final values. 885 SmallVector<SDValue, 4> Values(ValueVTs.size()); 886 SmallVector<SDValue, 8> Parts; 887 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 888 // Copy the legal parts from the registers. 889 EVT ValueVT = ValueVTs[Value]; 890 unsigned NumRegs = RegCount[Value]; 891 MVT RegisterVT = isABIMangled() 892 ? TLI.getRegisterTypeForCallingConv( 893 *DAG.getContext(), *CallConv, RegVTs[Value]) 894 : RegVTs[Value]; 895 896 Parts.resize(NumRegs); 897 for (unsigned i = 0; i != NumRegs; ++i) { 898 SDValue P; 899 if (!Glue) { 900 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 901 } else { 902 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 903 *Glue = P.getValue(2); 904 } 905 906 Chain = P.getValue(1); 907 Parts[i] = P; 908 909 // If the source register was virtual and if we know something about it, 910 // add an assert node. 911 if (!Register::isVirtualRegister(Regs[Part + i]) || 912 !RegisterVT.isInteger()) 913 continue; 914 915 const FunctionLoweringInfo::LiveOutInfo *LOI = 916 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 917 if (!LOI) 918 continue; 919 920 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 921 unsigned NumSignBits = LOI->NumSignBits; 922 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 923 924 if (NumZeroBits == RegSize) { 925 // The current value is a zero. 926 // Explicitly express that as it would be easier for 927 // optimizations to kick in. 928 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 929 continue; 930 } 931 932 // FIXME: We capture more information than the dag can represent. For 933 // now, just use the tightest assertzext/assertsext possible. 934 bool isSExt; 935 EVT FromVT(MVT::Other); 936 if (NumZeroBits) { 937 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 938 isSExt = false; 939 } else if (NumSignBits > 1) { 940 FromVT = 941 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 942 isSExt = true; 943 } else { 944 continue; 945 } 946 // Add an assertion node. 947 assert(FromVT != MVT::Other); 948 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 949 RegisterVT, P, DAG.getValueType(FromVT)); 950 } 951 952 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 953 RegisterVT, ValueVT, V, Chain, CallConv); 954 Part += NumRegs; 955 Parts.clear(); 956 } 957 958 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 959 } 960 961 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 962 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 963 const Value *V, 964 ISD::NodeType PreferredExtendType) const { 965 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 966 ISD::NodeType ExtendKind = PreferredExtendType; 967 968 // Get the list of the values's legal parts. 969 unsigned NumRegs = Regs.size(); 970 SmallVector<SDValue, 8> Parts(NumRegs); 971 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 972 unsigned NumParts = RegCount[Value]; 973 974 MVT RegisterVT = isABIMangled() 975 ? TLI.getRegisterTypeForCallingConv( 976 *DAG.getContext(), *CallConv, RegVTs[Value]) 977 : RegVTs[Value]; 978 979 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 980 ExtendKind = ISD::ZERO_EXTEND; 981 982 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 983 NumParts, RegisterVT, V, CallConv, ExtendKind); 984 Part += NumParts; 985 } 986 987 // Copy the parts into the registers. 988 SmallVector<SDValue, 8> Chains(NumRegs); 989 for (unsigned i = 0; i != NumRegs; ++i) { 990 SDValue Part; 991 if (!Glue) { 992 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 993 } else { 994 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 995 *Glue = Part.getValue(1); 996 } 997 998 Chains[i] = Part.getValue(0); 999 } 1000 1001 if (NumRegs == 1 || Glue) 1002 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 1003 // flagged to it. That is the CopyToReg nodes and the user are considered 1004 // a single scheduling unit. If we create a TokenFactor and return it as 1005 // chain, then the TokenFactor is both a predecessor (operand) of the 1006 // user as well as a successor (the TF operands are flagged to the user). 1007 // c1, f1 = CopyToReg 1008 // c2, f2 = CopyToReg 1009 // c3 = TokenFactor c1, c2 1010 // ... 1011 // = op c3, ..., f2 1012 Chain = Chains[NumRegs-1]; 1013 else 1014 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 1015 } 1016 1017 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 1018 unsigned MatchingIdx, const SDLoc &dl, 1019 SelectionDAG &DAG, 1020 std::vector<SDValue> &Ops) const { 1021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1022 1023 InlineAsm::Flag Flag(Code, Regs.size()); 1024 if (HasMatching) 1025 Flag.setMatchingOp(MatchingIdx); 1026 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1027 // Put the register class of the virtual registers in the flag word. That 1028 // way, later passes can recompute register class constraints for inline 1029 // assembly as well as normal instructions. 1030 // Don't do this for tied operands that can use the regclass information 1031 // from the def. 1032 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1033 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1034 Flag.setRegClass(RC->getID()); 1035 } 1036 1037 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1038 Ops.push_back(Res); 1039 1040 if (Code == InlineAsm::Kind::Clobber) { 1041 // Clobbers should always have a 1:1 mapping with registers, and may 1042 // reference registers that have illegal (e.g. vector) types. Hence, we 1043 // shouldn't try to apply any sort of splitting logic to them. 1044 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1045 "No 1:1 mapping from clobbers to regs?"); 1046 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1047 (void)SP; 1048 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1049 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1050 assert( 1051 (Regs[I] != SP || 1052 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1053 "If we clobbered the stack pointer, MFI should know about it."); 1054 } 1055 return; 1056 } 1057 1058 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1059 MVT RegisterVT = RegVTs[Value]; 1060 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1061 RegisterVT); 1062 for (unsigned i = 0; i != NumRegs; ++i) { 1063 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1064 unsigned TheReg = Regs[Reg++]; 1065 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1066 } 1067 } 1068 } 1069 1070 SmallVector<std::pair<Register, TypeSize>, 4> 1071 RegsForValue::getRegsAndSizes() const { 1072 SmallVector<std::pair<Register, TypeSize>, 4> OutVec; 1073 unsigned I = 0; 1074 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1075 unsigned RegCount = std::get<0>(CountAndVT); 1076 MVT RegisterVT = std::get<1>(CountAndVT); 1077 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1078 for (unsigned E = I + RegCount; I != E; ++I) 1079 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1080 } 1081 return OutVec; 1082 } 1083 1084 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1085 AssumptionCache *ac, 1086 const TargetLibraryInfo *li) { 1087 AA = aa; 1088 AC = ac; 1089 GFI = gfi; 1090 LibInfo = li; 1091 Context = DAG.getContext(); 1092 LPadToCallSiteMap.clear(); 1093 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1094 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1095 *DAG.getMachineFunction().getFunction().getParent()); 1096 } 1097 1098 void SelectionDAGBuilder::clear() { 1099 NodeMap.clear(); 1100 UnusedArgNodeMap.clear(); 1101 PendingLoads.clear(); 1102 PendingExports.clear(); 1103 PendingConstrainedFP.clear(); 1104 PendingConstrainedFPStrict.clear(); 1105 CurInst = nullptr; 1106 HasTailCall = false; 1107 SDNodeOrder = LowestSDNodeOrder; 1108 StatepointLowering.clear(); 1109 } 1110 1111 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1112 DanglingDebugInfoMap.clear(); 1113 } 1114 1115 // Update DAG root to include dependencies on Pending chains. 1116 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1117 SDValue Root = DAG.getRoot(); 1118 1119 if (Pending.empty()) 1120 return Root; 1121 1122 // Add current root to PendingChains, unless we already indirectly 1123 // depend on it. 1124 if (Root.getOpcode() != ISD::EntryToken) { 1125 unsigned i = 0, e = Pending.size(); 1126 for (; i != e; ++i) { 1127 assert(Pending[i].getNode()->getNumOperands() > 1); 1128 if (Pending[i].getNode()->getOperand(0) == Root) 1129 break; // Don't add the root if we already indirectly depend on it. 1130 } 1131 1132 if (i == e) 1133 Pending.push_back(Root); 1134 } 1135 1136 if (Pending.size() == 1) 1137 Root = Pending[0]; 1138 else 1139 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1140 1141 DAG.setRoot(Root); 1142 Pending.clear(); 1143 return Root; 1144 } 1145 1146 SDValue SelectionDAGBuilder::getMemoryRoot() { 1147 return updateRoot(PendingLoads); 1148 } 1149 1150 SDValue SelectionDAGBuilder::getRoot() { 1151 // Chain up all pending constrained intrinsics together with all 1152 // pending loads, by simply appending them to PendingLoads and 1153 // then calling getMemoryRoot(). 1154 PendingLoads.reserve(PendingLoads.size() + 1155 PendingConstrainedFP.size() + 1156 PendingConstrainedFPStrict.size()); 1157 PendingLoads.append(PendingConstrainedFP.begin(), 1158 PendingConstrainedFP.end()); 1159 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1160 PendingConstrainedFPStrict.end()); 1161 PendingConstrainedFP.clear(); 1162 PendingConstrainedFPStrict.clear(); 1163 return getMemoryRoot(); 1164 } 1165 1166 SDValue SelectionDAGBuilder::getControlRoot() { 1167 // We need to emit pending fpexcept.strict constrained intrinsics, 1168 // so append them to the PendingExports list. 1169 PendingExports.append(PendingConstrainedFPStrict.begin(), 1170 PendingConstrainedFPStrict.end()); 1171 PendingConstrainedFPStrict.clear(); 1172 return updateRoot(PendingExports); 1173 } 1174 1175 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1176 DILocalVariable *Variable, 1177 DIExpression *Expression, 1178 DebugLoc DL) { 1179 assert(Variable && "Missing variable"); 1180 1181 // Check if address has undef value. 1182 if (!Address || isa<UndefValue>(Address) || 1183 (Address->use_empty() && !isa<Argument>(Address))) { 1184 LLVM_DEBUG( 1185 dbgs() 1186 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1187 return; 1188 } 1189 1190 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1191 1192 SDValue &N = NodeMap[Address]; 1193 if (!N.getNode() && isa<Argument>(Address)) 1194 // Check unused arguments map. 1195 N = UnusedArgNodeMap[Address]; 1196 SDDbgValue *SDV; 1197 if (N.getNode()) { 1198 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1199 Address = BCI->getOperand(0); 1200 // Parameters are handled specially. 1201 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1202 if (IsParameter && FINode) { 1203 // Byval parameter. We have a frame index at this point. 1204 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1205 /*IsIndirect*/ true, DL, SDNodeOrder); 1206 } else if (isa<Argument>(Address)) { 1207 // Address is an argument, so try to emit its dbg value using 1208 // virtual register info from the FuncInfo.ValueMap. 1209 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1210 FuncArgumentDbgValueKind::Declare, N); 1211 return; 1212 } else { 1213 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1214 true, DL, SDNodeOrder); 1215 } 1216 DAG.AddDbgValue(SDV, IsParameter); 1217 } else { 1218 // If Address is an argument then try to emit its dbg value using 1219 // virtual register info from the FuncInfo.ValueMap. 1220 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1221 FuncArgumentDbgValueKind::Declare, N)) { 1222 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1223 << " (could not emit func-arg dbg_value)\n"); 1224 } 1225 } 1226 return; 1227 } 1228 1229 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1230 // Add SDDbgValue nodes for any var locs here. Do so before updating 1231 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1232 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1233 // Add SDDbgValue nodes for any var locs here. Do so before updating 1234 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1235 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1236 It != End; ++It) { 1237 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1238 dropDanglingDebugInfo(Var, It->Expr); 1239 if (It->Values.isKillLocation(It->Expr)) { 1240 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1241 continue; 1242 } 1243 SmallVector<Value *> Values(It->Values.location_ops()); 1244 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1245 It->Values.hasArgList())) { 1246 SmallVector<Value *, 4> Vals(It->Values.location_ops()); 1247 addDanglingDebugInfo(Vals, 1248 FnVarLocs->getDILocalVariable(It->VariableID), 1249 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1250 } 1251 } 1252 } 1253 1254 // We must skip DbgVariableRecords if they've already been processed above as 1255 // we have just emitted the debug values resulting from assignment tracking 1256 // analysis, making any existing DbgVariableRecords redundant (and probably 1257 // less correct). We still need to process DbgLabelRecords. This does sink 1258 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't 1259 // be important as it does so deterministcally and ordering between 1260 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR 1261 // printing). 1262 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs(); 1263 // Is there is any debug-info attached to this instruction, in the form of 1264 // DbgRecord non-instruction debug-info records. 1265 for (DbgRecord &DR : I.getDbgRecordRange()) { 1266 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 1267 assert(DLR->getLabel() && "Missing label"); 1268 SDDbgLabel *SDV = 1269 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder); 1270 DAG.AddDbgLabel(SDV); 1271 continue; 1272 } 1273 1274 if (SkipDbgVariableRecords) 1275 continue; 1276 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 1277 DILocalVariable *Variable = DVR.getVariable(); 1278 DIExpression *Expression = DVR.getExpression(); 1279 dropDanglingDebugInfo(Variable, Expression); 1280 1281 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) { 1282 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR)) 1283 continue; 1284 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR 1285 << "\n"); 1286 handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression, 1287 DVR.getDebugLoc()); 1288 continue; 1289 } 1290 1291 // A DbgVariableRecord with no locations is a kill location. 1292 SmallVector<Value *, 4> Values(DVR.location_ops()); 1293 if (Values.empty()) { 1294 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1295 SDNodeOrder); 1296 continue; 1297 } 1298 1299 // A DbgVariableRecord with an undef or absent location is also a kill 1300 // location. 1301 if (llvm::any_of(Values, 1302 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1303 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1304 SDNodeOrder); 1305 continue; 1306 } 1307 1308 bool IsVariadic = DVR.hasArgList(); 1309 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(), 1310 SDNodeOrder, IsVariadic)) { 1311 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1312 DVR.getDebugLoc(), SDNodeOrder); 1313 } 1314 } 1315 } 1316 1317 void SelectionDAGBuilder::visit(const Instruction &I) { 1318 visitDbgInfo(I); 1319 1320 // Set up outgoing PHI node register values before emitting the terminator. 1321 if (I.isTerminator()) { 1322 HandlePHINodesInSuccessorBlocks(I.getParent()); 1323 } 1324 1325 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1326 if (!isa<DbgInfoIntrinsic>(I)) 1327 ++SDNodeOrder; 1328 1329 CurInst = &I; 1330 1331 // Set inserted listener only if required. 1332 bool NodeInserted = false; 1333 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1334 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1335 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra); 1336 if (PCSectionsMD || MMRA) { 1337 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1338 DAG, [&](SDNode *) { NodeInserted = true; }); 1339 } 1340 1341 visit(I.getOpcode(), I); 1342 1343 if (!I.isTerminator() && !HasTailCall && 1344 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1345 CopyToExportRegsIfNeeded(&I); 1346 1347 // Handle metadata. 1348 if (PCSectionsMD || MMRA) { 1349 auto It = NodeMap.find(&I); 1350 if (It != NodeMap.end()) { 1351 if (PCSectionsMD) 1352 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1353 if (MMRA) 1354 DAG.addMMRAMetadata(It->second.getNode(), MMRA); 1355 } else if (NodeInserted) { 1356 // This should not happen; if it does, don't let it go unnoticed so we can 1357 // fix it. Relevant visit*() function is probably missing a setValue(). 1358 errs() << "warning: loosing !pcsections and/or !mmra metadata [" 1359 << I.getModule()->getName() << "]\n"; 1360 LLVM_DEBUG(I.dump()); 1361 assert(false); 1362 } 1363 } 1364 1365 CurInst = nullptr; 1366 } 1367 1368 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1369 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1370 } 1371 1372 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1373 // Note: this doesn't use InstVisitor, because it has to work with 1374 // ConstantExpr's in addition to instructions. 1375 switch (Opcode) { 1376 default: llvm_unreachable("Unknown instruction type encountered!"); 1377 // Build the switch statement using the Instruction.def file. 1378 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1379 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1380 #include "llvm/IR/Instruction.def" 1381 } 1382 } 1383 1384 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1385 DILocalVariable *Variable, 1386 DebugLoc DL, unsigned Order, 1387 SmallVectorImpl<Value *> &Values, 1388 DIExpression *Expression) { 1389 // For variadic dbg_values we will now insert an undef. 1390 // FIXME: We can potentially recover these! 1391 SmallVector<SDDbgOperand, 2> Locs; 1392 for (const Value *V : Values) { 1393 auto *Undef = UndefValue::get(V->getType()); 1394 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1395 } 1396 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1397 /*IsIndirect=*/false, DL, Order, 1398 /*IsVariadic=*/true); 1399 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1400 return true; 1401 } 1402 1403 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1404 DILocalVariable *Var, 1405 DIExpression *Expr, 1406 bool IsVariadic, DebugLoc DL, 1407 unsigned Order) { 1408 if (IsVariadic) { 1409 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1410 return; 1411 } 1412 // TODO: Dangling debug info will eventually either be resolved or produce 1413 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1414 // between the original dbg.value location and its resolved DBG_VALUE, 1415 // which we should ideally fill with an extra Undef DBG_VALUE. 1416 assert(Values.size() == 1); 1417 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1418 } 1419 1420 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1421 const DIExpression *Expr) { 1422 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1423 DIVariable *DanglingVariable = DDI.getVariable(); 1424 DIExpression *DanglingExpr = DDI.getExpression(); 1425 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1426 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1427 << printDDI(nullptr, DDI) << "\n"); 1428 return true; 1429 } 1430 return false; 1431 }; 1432 1433 for (auto &DDIMI : DanglingDebugInfoMap) { 1434 DanglingDebugInfoVector &DDIV = DDIMI.second; 1435 1436 // If debug info is to be dropped, run it through final checks to see 1437 // whether it can be salvaged. 1438 for (auto &DDI : DDIV) 1439 if (isMatchingDbgValue(DDI)) 1440 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1441 1442 erase_if(DDIV, isMatchingDbgValue); 1443 } 1444 } 1445 1446 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1447 // generate the debug data structures now that we've seen its definition. 1448 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1449 SDValue Val) { 1450 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1451 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1452 return; 1453 1454 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1455 for (auto &DDI : DDIV) { 1456 DebugLoc DL = DDI.getDebugLoc(); 1457 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1458 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1459 DILocalVariable *Variable = DDI.getVariable(); 1460 DIExpression *Expr = DDI.getExpression(); 1461 assert(Variable->isValidLocationForIntrinsic(DL) && 1462 "Expected inlined-at fields to agree"); 1463 SDDbgValue *SDV; 1464 if (Val.getNode()) { 1465 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1466 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1467 // we couldn't resolve it directly when examining the DbgValue intrinsic 1468 // in the first place we should not be more successful here). Unless we 1469 // have some test case that prove this to be correct we should avoid 1470 // calling EmitFuncArgumentDbgValue here. 1471 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1472 FuncArgumentDbgValueKind::Value, Val)) { 1473 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1474 << printDDI(V, DDI) << "\n"); 1475 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1476 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1477 // inserted after the definition of Val when emitting the instructions 1478 // after ISel. An alternative could be to teach 1479 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1480 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1481 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1482 << ValSDNodeOrder << "\n"); 1483 SDV = getDbgValue(Val, Variable, Expr, DL, 1484 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1485 DAG.AddDbgValue(SDV, false); 1486 } else 1487 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1488 << printDDI(V, DDI) 1489 << " in EmitFuncArgumentDbgValue\n"); 1490 } else { 1491 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1492 << "\n"); 1493 auto Undef = UndefValue::get(V->getType()); 1494 auto SDV = 1495 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1496 DAG.AddDbgValue(SDV, false); 1497 } 1498 } 1499 DDIV.clear(); 1500 } 1501 1502 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1503 DanglingDebugInfo &DDI) { 1504 // TODO: For the variadic implementation, instead of only checking the fail 1505 // state of `handleDebugValue`, we need know specifically which values were 1506 // invalid, so that we attempt to salvage only those values when processing 1507 // a DIArgList. 1508 const Value *OrigV = V; 1509 DILocalVariable *Var = DDI.getVariable(); 1510 DIExpression *Expr = DDI.getExpression(); 1511 DebugLoc DL = DDI.getDebugLoc(); 1512 unsigned SDOrder = DDI.getSDNodeOrder(); 1513 1514 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1515 // that DW_OP_stack_value is desired. 1516 bool StackValue = true; 1517 1518 // Can this Value can be encoded without any further work? 1519 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1520 return; 1521 1522 // Attempt to salvage back through as many instructions as possible. Bail if 1523 // a non-instruction is seen, such as a constant expression or global 1524 // variable. FIXME: Further work could recover those too. 1525 while (isa<Instruction>(V)) { 1526 const Instruction &VAsInst = *cast<const Instruction>(V); 1527 // Temporary "0", awaiting real implementation. 1528 SmallVector<uint64_t, 16> Ops; 1529 SmallVector<Value *, 4> AdditionalValues; 1530 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1531 Expr->getNumLocationOperands(), Ops, 1532 AdditionalValues); 1533 // If we cannot salvage any further, and haven't yet found a suitable debug 1534 // expression, bail out. 1535 if (!V) 1536 break; 1537 1538 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1539 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1540 // here for variadic dbg_values, remove that condition. 1541 if (!AdditionalValues.empty()) 1542 break; 1543 1544 // New value and expr now represent this debuginfo. 1545 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1546 1547 // Some kind of simplification occurred: check whether the operand of the 1548 // salvaged debug expression can be encoded in this DAG. 1549 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1550 LLVM_DEBUG( 1551 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1552 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1553 return; 1554 } 1555 } 1556 1557 // This was the final opportunity to salvage this debug information, and it 1558 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1559 // any earlier variable location. 1560 assert(OrigV && "V shouldn't be null"); 1561 auto *Undef = UndefValue::get(OrigV->getType()); 1562 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1563 DAG.AddDbgValue(SDV, false); 1564 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1565 << printDDI(OrigV, DDI) << "\n"); 1566 } 1567 1568 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1569 DIExpression *Expr, 1570 DebugLoc DbgLoc, 1571 unsigned Order) { 1572 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1573 DIExpression *NewExpr = 1574 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1575 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1576 /*IsVariadic*/ false); 1577 } 1578 1579 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1580 DILocalVariable *Var, 1581 DIExpression *Expr, DebugLoc DbgLoc, 1582 unsigned Order, bool IsVariadic) { 1583 if (Values.empty()) 1584 return true; 1585 1586 // Filter EntryValue locations out early. 1587 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1588 return true; 1589 1590 SmallVector<SDDbgOperand> LocationOps; 1591 SmallVector<SDNode *> Dependencies; 1592 for (const Value *V : Values) { 1593 // Constant value. 1594 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1595 isa<ConstantPointerNull>(V)) { 1596 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1597 continue; 1598 } 1599 1600 // Look through IntToPtr constants. 1601 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1602 if (CE->getOpcode() == Instruction::IntToPtr) { 1603 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1604 continue; 1605 } 1606 1607 // If the Value is a frame index, we can create a FrameIndex debug value 1608 // without relying on the DAG at all. 1609 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1610 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1611 if (SI != FuncInfo.StaticAllocaMap.end()) { 1612 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1613 continue; 1614 } 1615 } 1616 1617 // Do not use getValue() in here; we don't want to generate code at 1618 // this point if it hasn't been done yet. 1619 SDValue N = NodeMap[V]; 1620 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1621 N = UnusedArgNodeMap[V]; 1622 1623 if (N.getNode()) { 1624 // Only emit func arg dbg value for non-variadic dbg.values for now. 1625 if (!IsVariadic && 1626 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1627 FuncArgumentDbgValueKind::Value, N)) 1628 return true; 1629 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1630 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1631 // describe stack slot locations. 1632 // 1633 // Consider "int x = 0; int *px = &x;". There are two kinds of 1634 // interesting debug values here after optimization: 1635 // 1636 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1637 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1638 // 1639 // Both describe the direct values of their associated variables. 1640 Dependencies.push_back(N.getNode()); 1641 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1642 continue; 1643 } 1644 LocationOps.emplace_back( 1645 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1646 continue; 1647 } 1648 1649 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1650 // Special rules apply for the first dbg.values of parameter variables in a 1651 // function. Identify them by the fact they reference Argument Values, that 1652 // they're parameters, and they are parameters of the current function. We 1653 // need to let them dangle until they get an SDNode. 1654 bool IsParamOfFunc = 1655 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1656 if (IsParamOfFunc) 1657 return false; 1658 1659 // The value is not used in this block yet (or it would have an SDNode). 1660 // We still want the value to appear for the user if possible -- if it has 1661 // an associated VReg, we can refer to that instead. 1662 auto VMI = FuncInfo.ValueMap.find(V); 1663 if (VMI != FuncInfo.ValueMap.end()) { 1664 unsigned Reg = VMI->second; 1665 // If this is a PHI node, it may be split up into several MI PHI nodes 1666 // (in FunctionLoweringInfo::set). 1667 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1668 V->getType(), std::nullopt); 1669 if (RFV.occupiesMultipleRegs()) { 1670 // FIXME: We could potentially support variadic dbg_values here. 1671 if (IsVariadic) 1672 return false; 1673 unsigned Offset = 0; 1674 unsigned BitsToDescribe = 0; 1675 if (auto VarSize = Var->getSizeInBits()) 1676 BitsToDescribe = *VarSize; 1677 if (auto Fragment = Expr->getFragmentInfo()) 1678 BitsToDescribe = Fragment->SizeInBits; 1679 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1680 // Bail out if all bits are described already. 1681 if (Offset >= BitsToDescribe) 1682 break; 1683 // TODO: handle scalable vectors. 1684 unsigned RegisterSize = RegAndSize.second; 1685 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1686 ? BitsToDescribe - Offset 1687 : RegisterSize; 1688 auto FragmentExpr = DIExpression::createFragmentExpression( 1689 Expr, Offset, FragmentSize); 1690 if (!FragmentExpr) 1691 continue; 1692 SDDbgValue *SDV = DAG.getVRegDbgValue( 1693 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order); 1694 DAG.AddDbgValue(SDV, false); 1695 Offset += RegisterSize; 1696 } 1697 return true; 1698 } 1699 // We can use simple vreg locations for variadic dbg_values as well. 1700 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1701 continue; 1702 } 1703 // We failed to create a SDDbgOperand for V. 1704 return false; 1705 } 1706 1707 // We have created a SDDbgOperand for each Value in Values. 1708 assert(!LocationOps.empty()); 1709 SDDbgValue *SDV = 1710 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1711 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic); 1712 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1713 return true; 1714 } 1715 1716 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1717 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1718 for (auto &Pair : DanglingDebugInfoMap) 1719 for (auto &DDI : Pair.second) 1720 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1721 clearDanglingDebugInfo(); 1722 } 1723 1724 /// getCopyFromRegs - If there was virtual register allocated for the value V 1725 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1726 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1727 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1728 SDValue Result; 1729 1730 if (It != FuncInfo.ValueMap.end()) { 1731 Register InReg = It->second; 1732 1733 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1734 DAG.getDataLayout(), InReg, Ty, 1735 std::nullopt); // This is not an ABI copy. 1736 SDValue Chain = DAG.getEntryNode(); 1737 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1738 V); 1739 resolveDanglingDebugInfo(V, Result); 1740 } 1741 1742 return Result; 1743 } 1744 1745 /// getValue - Return an SDValue for the given Value. 1746 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1747 // If we already have an SDValue for this value, use it. It's important 1748 // to do this first, so that we don't create a CopyFromReg if we already 1749 // have a regular SDValue. 1750 SDValue &N = NodeMap[V]; 1751 if (N.getNode()) return N; 1752 1753 // If there's a virtual register allocated and initialized for this 1754 // value, use it. 1755 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1756 return copyFromReg; 1757 1758 // Otherwise create a new SDValue and remember it. 1759 SDValue Val = getValueImpl(V); 1760 NodeMap[V] = Val; 1761 resolveDanglingDebugInfo(V, Val); 1762 return Val; 1763 } 1764 1765 /// getNonRegisterValue - Return an SDValue for the given Value, but 1766 /// don't look in FuncInfo.ValueMap for a virtual register. 1767 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1768 // If we already have an SDValue for this value, use it. 1769 SDValue &N = NodeMap[V]; 1770 if (N.getNode()) { 1771 if (isIntOrFPConstant(N)) { 1772 // Remove the debug location from the node as the node is about to be used 1773 // in a location which may differ from the original debug location. This 1774 // is relevant to Constant and ConstantFP nodes because they can appear 1775 // as constant expressions inside PHI nodes. 1776 N->setDebugLoc(DebugLoc()); 1777 } 1778 return N; 1779 } 1780 1781 // Otherwise create a new SDValue and remember it. 1782 SDValue Val = getValueImpl(V); 1783 NodeMap[V] = Val; 1784 resolveDanglingDebugInfo(V, Val); 1785 return Val; 1786 } 1787 1788 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1789 /// Create an SDValue for the given value. 1790 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1791 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1792 1793 if (const Constant *C = dyn_cast<Constant>(V)) { 1794 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1795 1796 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1797 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1798 1799 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1800 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1801 1802 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) { 1803 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT, 1804 getValue(CPA->getPointer()), getValue(CPA->getKey()), 1805 getValue(CPA->getAddrDiscriminator()), 1806 getValue(CPA->getDiscriminator())); 1807 } 1808 1809 if (isa<ConstantPointerNull>(C)) { 1810 unsigned AS = V->getType()->getPointerAddressSpace(); 1811 return DAG.getConstant(0, getCurSDLoc(), 1812 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1813 } 1814 1815 if (match(C, m_VScale())) 1816 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1817 1818 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1819 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1820 1821 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1822 return DAG.getUNDEF(VT); 1823 1824 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1825 visit(CE->getOpcode(), *CE); 1826 SDValue N1 = NodeMap[V]; 1827 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1828 return N1; 1829 } 1830 1831 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1832 SmallVector<SDValue, 4> Constants; 1833 for (const Use &U : C->operands()) { 1834 SDNode *Val = getValue(U).getNode(); 1835 // If the operand is an empty aggregate, there are no values. 1836 if (!Val) continue; 1837 // Add each leaf value from the operand to the Constants list 1838 // to form a flattened list of all the values. 1839 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1840 Constants.push_back(SDValue(Val, i)); 1841 } 1842 1843 return DAG.getMergeValues(Constants, getCurSDLoc()); 1844 } 1845 1846 if (const ConstantDataSequential *CDS = 1847 dyn_cast<ConstantDataSequential>(C)) { 1848 SmallVector<SDValue, 4> Ops; 1849 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1850 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1851 // Add each leaf value from the operand to the Constants list 1852 // to form a flattened list of all the values. 1853 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1854 Ops.push_back(SDValue(Val, i)); 1855 } 1856 1857 if (isa<ArrayType>(CDS->getType())) 1858 return DAG.getMergeValues(Ops, getCurSDLoc()); 1859 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1860 } 1861 1862 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1863 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1864 "Unknown struct or array constant!"); 1865 1866 SmallVector<EVT, 4> ValueVTs; 1867 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1868 unsigned NumElts = ValueVTs.size(); 1869 if (NumElts == 0) 1870 return SDValue(); // empty struct 1871 SmallVector<SDValue, 4> Constants(NumElts); 1872 for (unsigned i = 0; i != NumElts; ++i) { 1873 EVT EltVT = ValueVTs[i]; 1874 if (isa<UndefValue>(C)) 1875 Constants[i] = DAG.getUNDEF(EltVT); 1876 else if (EltVT.isFloatingPoint()) 1877 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1878 else 1879 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1880 } 1881 1882 return DAG.getMergeValues(Constants, getCurSDLoc()); 1883 } 1884 1885 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1886 return DAG.getBlockAddress(BA, VT); 1887 1888 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1889 return getValue(Equiv->getGlobalValue()); 1890 1891 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1892 return getValue(NC->getGlobalValue()); 1893 1894 if (VT == MVT::aarch64svcount) { 1895 assert(C->isNullValue() && "Can only zero this target type!"); 1896 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1897 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1898 } 1899 1900 VectorType *VecTy = cast<VectorType>(V->getType()); 1901 1902 // Now that we know the number and type of the elements, get that number of 1903 // elements into the Ops array based on what kind of constant it is. 1904 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1905 SmallVector<SDValue, 16> Ops; 1906 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1907 for (unsigned i = 0; i != NumElements; ++i) 1908 Ops.push_back(getValue(CV->getOperand(i))); 1909 1910 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1911 } 1912 1913 if (isa<ConstantAggregateZero>(C)) { 1914 EVT EltVT = 1915 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1916 1917 SDValue Op; 1918 if (EltVT.isFloatingPoint()) 1919 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1920 else 1921 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1922 1923 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1924 } 1925 1926 llvm_unreachable("Unknown vector constant"); 1927 } 1928 1929 // If this is a static alloca, generate it as the frameindex instead of 1930 // computation. 1931 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1932 DenseMap<const AllocaInst*, int>::iterator SI = 1933 FuncInfo.StaticAllocaMap.find(AI); 1934 if (SI != FuncInfo.StaticAllocaMap.end()) 1935 return DAG.getFrameIndex( 1936 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1937 } 1938 1939 // If this is an instruction which fast-isel has deferred, select it now. 1940 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1941 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1942 1943 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1944 Inst->getType(), std::nullopt); 1945 SDValue Chain = DAG.getEntryNode(); 1946 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1947 } 1948 1949 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1950 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1951 1952 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1953 return DAG.getBasicBlock(FuncInfo.getMBB(BB)); 1954 1955 llvm_unreachable("Can't get register for value!"); 1956 } 1957 1958 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1959 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1960 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1961 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1962 bool IsSEH = isAsynchronousEHPersonality(Pers); 1963 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1964 if (!IsSEH) 1965 CatchPadMBB->setIsEHScopeEntry(); 1966 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1967 if (IsMSVCCXX || IsCoreCLR) 1968 CatchPadMBB->setIsEHFuncletEntry(); 1969 } 1970 1971 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1972 // Update machine-CFG edge. 1973 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor()); 1974 FuncInfo.MBB->addSuccessor(TargetMBB); 1975 TargetMBB->setIsEHCatchretTarget(true); 1976 DAG.getMachineFunction().setHasEHCatchret(true); 1977 1978 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1979 bool IsSEH = isAsynchronousEHPersonality(Pers); 1980 if (IsSEH) { 1981 // If this is not a fall-through branch or optimizations are switched off, 1982 // emit the branch. 1983 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1984 TM.getOptLevel() == CodeGenOptLevel::None) 1985 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1986 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1987 return; 1988 } 1989 1990 // Figure out the funclet membership for the catchret's successor. 1991 // This will be used by the FuncletLayout pass to determine how to order the 1992 // BB's. 1993 // A 'catchret' returns to the outer scope's color. 1994 Value *ParentPad = I.getCatchSwitchParentPad(); 1995 const BasicBlock *SuccessorColor; 1996 if (isa<ConstantTokenNone>(ParentPad)) 1997 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1998 else 1999 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 2000 assert(SuccessorColor && "No parent funclet for catchret!"); 2001 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor); 2002 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 2003 2004 // Create the terminator node. 2005 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 2006 getControlRoot(), DAG.getBasicBlock(TargetMBB), 2007 DAG.getBasicBlock(SuccessorColorMBB)); 2008 DAG.setRoot(Ret); 2009 } 2010 2011 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 2012 // Don't emit any special code for the cleanuppad instruction. It just marks 2013 // the start of an EH scope/funclet. 2014 FuncInfo.MBB->setIsEHScopeEntry(); 2015 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2016 if (Pers != EHPersonality::Wasm_CXX) { 2017 FuncInfo.MBB->setIsEHFuncletEntry(); 2018 FuncInfo.MBB->setIsCleanupFuncletEntry(); 2019 } 2020 } 2021 2022 // In wasm EH, even though a catchpad may not catch an exception if a tag does 2023 // not match, it is OK to add only the first unwind destination catchpad to the 2024 // successors, because there will be at least one invoke instruction within the 2025 // catch scope that points to the next unwind destination, if one exists, so 2026 // CFGSort cannot mess up with BB sorting order. 2027 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 2028 // call within them, and catchpads only consisting of 'catch (...)' have a 2029 // '__cxa_end_catch' call within them, both of which generate invokes in case 2030 // the next unwind destination exists, i.e., the next unwind destination is not 2031 // the caller.) 2032 // 2033 // Having at most one EH pad successor is also simpler and helps later 2034 // transformations. 2035 // 2036 // For example, 2037 // current: 2038 // invoke void @foo to ... unwind label %catch.dispatch 2039 // catch.dispatch: 2040 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2041 // catch.start: 2042 // ... 2043 // ... in this BB or some other child BB dominated by this BB there will be an 2044 // invoke that points to 'next' BB as an unwind destination 2045 // 2046 // next: ; We don't need to add this to 'current' BB's successor 2047 // ... 2048 static void findWasmUnwindDestinations( 2049 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2050 BranchProbability Prob, 2051 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2052 &UnwindDests) { 2053 while (EHPadBB) { 2054 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2055 if (isa<CleanupPadInst>(Pad)) { 2056 // Stop on cleanup pads. 2057 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2058 UnwindDests.back().first->setIsEHScopeEntry(); 2059 break; 2060 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2061 // Add the catchpad handlers to the possible destinations. We don't 2062 // continue to the unwind destination of the catchswitch for wasm. 2063 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2064 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob); 2065 UnwindDests.back().first->setIsEHScopeEntry(); 2066 } 2067 break; 2068 } else { 2069 continue; 2070 } 2071 } 2072 } 2073 2074 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2075 /// many places it could ultimately go. In the IR, we have a single unwind 2076 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2077 /// This function skips over imaginary basic blocks that hold catchswitch 2078 /// instructions, and finds all the "real" machine 2079 /// basic block destinations. As those destinations may not be successors of 2080 /// EHPadBB, here we also calculate the edge probability to those destinations. 2081 /// The passed-in Prob is the edge probability to EHPadBB. 2082 static void findUnwindDestinations( 2083 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2084 BranchProbability Prob, 2085 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2086 &UnwindDests) { 2087 EHPersonality Personality = 2088 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2089 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2090 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2091 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2092 bool IsSEH = isAsynchronousEHPersonality(Personality); 2093 2094 if (IsWasmCXX) { 2095 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2096 assert(UnwindDests.size() <= 1 && 2097 "There should be at most one unwind destination for wasm"); 2098 return; 2099 } 2100 2101 while (EHPadBB) { 2102 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2103 BasicBlock *NewEHPadBB = nullptr; 2104 if (isa<LandingPadInst>(Pad)) { 2105 // Stop on landingpads. They are not funclets. 2106 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2107 break; 2108 } else if (isa<CleanupPadInst>(Pad)) { 2109 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2110 // personalities. 2111 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2112 UnwindDests.back().first->setIsEHScopeEntry(); 2113 UnwindDests.back().first->setIsEHFuncletEntry(); 2114 break; 2115 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2116 // Add the catchpad handlers to the possible destinations. 2117 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2118 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob); 2119 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2120 if (IsMSVCCXX || IsCoreCLR) 2121 UnwindDests.back().first->setIsEHFuncletEntry(); 2122 if (!IsSEH) 2123 UnwindDests.back().first->setIsEHScopeEntry(); 2124 } 2125 NewEHPadBB = CatchSwitch->getUnwindDest(); 2126 } else { 2127 continue; 2128 } 2129 2130 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2131 if (BPI && NewEHPadBB) 2132 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2133 EHPadBB = NewEHPadBB; 2134 } 2135 } 2136 2137 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2138 // Update successor info. 2139 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2140 auto UnwindDest = I.getUnwindDest(); 2141 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2142 BranchProbability UnwindDestProb = 2143 (BPI && UnwindDest) 2144 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2145 : BranchProbability::getZero(); 2146 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2147 for (auto &UnwindDest : UnwindDests) { 2148 UnwindDest.first->setIsEHPad(); 2149 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2150 } 2151 FuncInfo.MBB->normalizeSuccProbs(); 2152 2153 // Create the terminator node. 2154 MachineBasicBlock *CleanupPadMBB = 2155 FuncInfo.getMBB(I.getCleanupPad()->getParent()); 2156 SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, 2157 getControlRoot(), DAG.getBasicBlock(CleanupPadMBB)); 2158 DAG.setRoot(Ret); 2159 } 2160 2161 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2162 report_fatal_error("visitCatchSwitch not yet implemented!"); 2163 } 2164 2165 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2166 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2167 auto &DL = DAG.getDataLayout(); 2168 SDValue Chain = getControlRoot(); 2169 SmallVector<ISD::OutputArg, 8> Outs; 2170 SmallVector<SDValue, 8> OutVals; 2171 2172 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2173 // lower 2174 // 2175 // %val = call <ty> @llvm.experimental.deoptimize() 2176 // ret <ty> %val 2177 // 2178 // differently. 2179 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2180 LowerDeoptimizingReturn(); 2181 return; 2182 } 2183 2184 if (!FuncInfo.CanLowerReturn) { 2185 Register DemoteReg = FuncInfo.DemoteRegister; 2186 const Function *F = I.getParent()->getParent(); 2187 2188 // Emit a store of the return value through the virtual register. 2189 // Leave Outs empty so that LowerReturn won't try to load return 2190 // registers the usual way. 2191 SmallVector<EVT, 1> PtrValueVTs; 2192 ComputeValueVTs(TLI, DL, 2193 PointerType::get(F->getContext(), 2194 DAG.getDataLayout().getAllocaAddrSpace()), 2195 PtrValueVTs); 2196 2197 SDValue RetPtr = 2198 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2199 SDValue RetOp = getValue(I.getOperand(0)); 2200 2201 SmallVector<EVT, 4> ValueVTs, MemVTs; 2202 SmallVector<uint64_t, 4> Offsets; 2203 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2204 &Offsets, 0); 2205 unsigned NumValues = ValueVTs.size(); 2206 2207 SmallVector<SDValue, 4> Chains(NumValues); 2208 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2209 for (unsigned i = 0; i != NumValues; ++i) { 2210 // An aggregate return value cannot wrap around the address space, so 2211 // offsets to its parts don't wrap either. 2212 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2213 TypeSize::getFixed(Offsets[i])); 2214 2215 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2216 if (MemVTs[i] != ValueVTs[i]) 2217 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2218 Chains[i] = DAG.getStore( 2219 Chain, getCurSDLoc(), Val, 2220 // FIXME: better loc info would be nice. 2221 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2222 commonAlignment(BaseAlign, Offsets[i])); 2223 } 2224 2225 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2226 MVT::Other, Chains); 2227 } else if (I.getNumOperands() != 0) { 2228 SmallVector<EVT, 4> ValueVTs; 2229 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2230 unsigned NumValues = ValueVTs.size(); 2231 if (NumValues) { 2232 SDValue RetOp = getValue(I.getOperand(0)); 2233 2234 const Function *F = I.getParent()->getParent(); 2235 2236 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2237 I.getOperand(0)->getType(), F->getCallingConv(), 2238 /*IsVarArg*/ false, DL); 2239 2240 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2241 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2242 ExtendKind = ISD::SIGN_EXTEND; 2243 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2244 ExtendKind = ISD::ZERO_EXTEND; 2245 2246 LLVMContext &Context = F->getContext(); 2247 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2248 2249 for (unsigned j = 0; j != NumValues; ++j) { 2250 EVT VT = ValueVTs[j]; 2251 2252 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2253 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2254 2255 CallingConv::ID CC = F->getCallingConv(); 2256 2257 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2258 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2259 SmallVector<SDValue, 4> Parts(NumParts); 2260 getCopyToParts(DAG, getCurSDLoc(), 2261 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2262 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2263 2264 // 'inreg' on function refers to return value 2265 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2266 if (RetInReg) 2267 Flags.setInReg(); 2268 2269 if (I.getOperand(0)->getType()->isPointerTy()) { 2270 Flags.setPointer(); 2271 Flags.setPointerAddrSpace( 2272 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2273 } 2274 2275 if (NeedsRegBlock) { 2276 Flags.setInConsecutiveRegs(); 2277 if (j == NumValues - 1) 2278 Flags.setInConsecutiveRegsLast(); 2279 } 2280 2281 // Propagate extension type if any 2282 if (ExtendKind == ISD::SIGN_EXTEND) 2283 Flags.setSExt(); 2284 else if (ExtendKind == ISD::ZERO_EXTEND) 2285 Flags.setZExt(); 2286 else if (F->getAttributes().hasRetAttr(Attribute::NoExt)) 2287 Flags.setNoExt(); 2288 2289 for (unsigned i = 0; i < NumParts; ++i) { 2290 Outs.push_back(ISD::OutputArg(Flags, 2291 Parts[i].getValueType().getSimpleVT(), 2292 VT, /*isfixed=*/true, 0, 0)); 2293 OutVals.push_back(Parts[i]); 2294 } 2295 } 2296 } 2297 } 2298 2299 // Push in swifterror virtual register as the last element of Outs. This makes 2300 // sure swifterror virtual register will be returned in the swifterror 2301 // physical register. 2302 const Function *F = I.getParent()->getParent(); 2303 if (TLI.supportSwiftError() && 2304 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2305 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2306 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2307 Flags.setSwiftError(); 2308 Outs.push_back(ISD::OutputArg( 2309 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2310 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2311 // Create SDNode for the swifterror virtual register. 2312 OutVals.push_back( 2313 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2314 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2315 EVT(TLI.getPointerTy(DL)))); 2316 } 2317 2318 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2319 CallingConv::ID CallConv = 2320 DAG.getMachineFunction().getFunction().getCallingConv(); 2321 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2322 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2323 2324 // Verify that the target's LowerReturn behaved as expected. 2325 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2326 "LowerReturn didn't return a valid chain!"); 2327 2328 // Update the DAG with the new chain value resulting from return lowering. 2329 DAG.setRoot(Chain); 2330 } 2331 2332 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2333 /// created for it, emit nodes to copy the value into the virtual 2334 /// registers. 2335 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2336 // Skip empty types 2337 if (V->getType()->isEmptyTy()) 2338 return; 2339 2340 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2341 if (VMI != FuncInfo.ValueMap.end()) { 2342 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2343 "Unused value assigned virtual registers!"); 2344 CopyValueToVirtualRegister(V, VMI->second); 2345 } 2346 } 2347 2348 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2349 /// the current basic block, add it to ValueMap now so that we'll get a 2350 /// CopyTo/FromReg. 2351 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2352 // No need to export constants. 2353 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2354 2355 // Already exported? 2356 if (FuncInfo.isExportedInst(V)) return; 2357 2358 Register Reg = FuncInfo.InitializeRegForValue(V); 2359 CopyValueToVirtualRegister(V, Reg); 2360 } 2361 2362 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2363 const BasicBlock *FromBB) { 2364 // The operands of the setcc have to be in this block. We don't know 2365 // how to export them from some other block. 2366 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2367 // Can export from current BB. 2368 if (VI->getParent() == FromBB) 2369 return true; 2370 2371 // Is already exported, noop. 2372 return FuncInfo.isExportedInst(V); 2373 } 2374 2375 // If this is an argument, we can export it if the BB is the entry block or 2376 // if it is already exported. 2377 if (isa<Argument>(V)) { 2378 if (FromBB->isEntryBlock()) 2379 return true; 2380 2381 // Otherwise, can only export this if it is already exported. 2382 return FuncInfo.isExportedInst(V); 2383 } 2384 2385 // Otherwise, constants can always be exported. 2386 return true; 2387 } 2388 2389 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2390 BranchProbability 2391 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2392 const MachineBasicBlock *Dst) const { 2393 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2394 const BasicBlock *SrcBB = Src->getBasicBlock(); 2395 const BasicBlock *DstBB = Dst->getBasicBlock(); 2396 if (!BPI) { 2397 // If BPI is not available, set the default probability as 1 / N, where N is 2398 // the number of successors. 2399 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2400 return BranchProbability(1, SuccSize); 2401 } 2402 return BPI->getEdgeProbability(SrcBB, DstBB); 2403 } 2404 2405 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2406 MachineBasicBlock *Dst, 2407 BranchProbability Prob) { 2408 if (!FuncInfo.BPI) 2409 Src->addSuccessorWithoutProb(Dst); 2410 else { 2411 if (Prob.isUnknown()) 2412 Prob = getEdgeProbability(Src, Dst); 2413 Src->addSuccessor(Dst, Prob); 2414 } 2415 } 2416 2417 static bool InBlock(const Value *V, const BasicBlock *BB) { 2418 if (const Instruction *I = dyn_cast<Instruction>(V)) 2419 return I->getParent() == BB; 2420 return true; 2421 } 2422 2423 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2424 /// This function emits a branch and is used at the leaves of an OR or an 2425 /// AND operator tree. 2426 void 2427 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2428 MachineBasicBlock *TBB, 2429 MachineBasicBlock *FBB, 2430 MachineBasicBlock *CurBB, 2431 MachineBasicBlock *SwitchBB, 2432 BranchProbability TProb, 2433 BranchProbability FProb, 2434 bool InvertCond) { 2435 const BasicBlock *BB = CurBB->getBasicBlock(); 2436 2437 // If the leaf of the tree is a comparison, merge the condition into 2438 // the caseblock. 2439 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2440 // The operands of the cmp have to be in this block. We don't know 2441 // how to export them from some other block. If this is the first block 2442 // of the sequence, no exporting is needed. 2443 if (CurBB == SwitchBB || 2444 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2445 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2446 ISD::CondCode Condition; 2447 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2448 ICmpInst::Predicate Pred = 2449 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2450 Condition = getICmpCondCode(Pred); 2451 } else { 2452 const FCmpInst *FC = cast<FCmpInst>(Cond); 2453 FCmpInst::Predicate Pred = 2454 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2455 Condition = getFCmpCondCode(Pred); 2456 if (TM.Options.NoNaNsFPMath) 2457 Condition = getFCmpCodeWithoutNaN(Condition); 2458 } 2459 2460 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2461 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2462 SL->SwitchCases.push_back(CB); 2463 return; 2464 } 2465 } 2466 2467 // Create a CaseBlock record representing this branch. 2468 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2469 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2470 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2471 SL->SwitchCases.push_back(CB); 2472 } 2473 2474 // Collect dependencies on V recursively. This is used for the cost analysis in 2475 // `shouldKeepJumpConditionsTogether`. 2476 static bool collectInstructionDeps( 2477 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V, 2478 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr, 2479 unsigned Depth = 0) { 2480 // Return false if we have an incomplete count. 2481 if (Depth >= SelectionDAG::MaxRecursionDepth) 2482 return false; 2483 2484 auto *I = dyn_cast<Instruction>(V); 2485 if (I == nullptr) 2486 return true; 2487 2488 if (Necessary != nullptr) { 2489 // This instruction is necessary for the other side of the condition so 2490 // don't count it. 2491 if (Necessary->contains(I)) 2492 return true; 2493 } 2494 2495 // Already added this dep. 2496 if (!Deps->try_emplace(I, false).second) 2497 return true; 2498 2499 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx) 2500 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary, 2501 Depth + 1)) 2502 return false; 2503 return true; 2504 } 2505 2506 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether( 2507 const FunctionLoweringInfo &FuncInfo, const BranchInst &I, 2508 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, 2509 TargetLoweringBase::CondMergingParams Params) const { 2510 if (I.getNumSuccessors() != 2) 2511 return false; 2512 2513 if (!I.isConditional()) 2514 return false; 2515 2516 if (Params.BaseCost < 0) 2517 return false; 2518 2519 // Baseline cost. 2520 InstructionCost CostThresh = Params.BaseCost; 2521 2522 BranchProbabilityInfo *BPI = nullptr; 2523 if (Params.LikelyBias || Params.UnlikelyBias) 2524 BPI = FuncInfo.BPI; 2525 if (BPI != nullptr) { 2526 // See if we are either likely to get an early out or compute both lhs/rhs 2527 // of the condition. 2528 BasicBlock *IfFalse = I.getSuccessor(0); 2529 BasicBlock *IfTrue = I.getSuccessor(1); 2530 2531 std::optional<bool> Likely; 2532 if (BPI->isEdgeHot(I.getParent(), IfTrue)) 2533 Likely = true; 2534 else if (BPI->isEdgeHot(I.getParent(), IfFalse)) 2535 Likely = false; 2536 2537 if (Likely) { 2538 if (Opc == (*Likely ? Instruction::And : Instruction::Or)) 2539 // Its likely we will have to compute both lhs and rhs of condition 2540 CostThresh += Params.LikelyBias; 2541 else { 2542 if (Params.UnlikelyBias < 0) 2543 return false; 2544 // Its likely we will get an early out. 2545 CostThresh -= Params.UnlikelyBias; 2546 } 2547 } 2548 } 2549 2550 if (CostThresh <= 0) 2551 return false; 2552 2553 // Collect "all" instructions that lhs condition is dependent on. 2554 // Use map for stable iteration (to avoid non-determanism of iteration of 2555 // SmallPtrSet). The `bool` value is just a dummy. 2556 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps; 2557 collectInstructionDeps(&LhsDeps, Lhs); 2558 // Collect "all" instructions that rhs condition is dependent on AND are 2559 // dependencies of lhs. This gives us an estimate on which instructions we 2560 // stand to save by splitting the condition. 2561 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps)) 2562 return false; 2563 // Add the compare instruction itself unless its a dependency on the LHS. 2564 if (const auto *RhsI = dyn_cast<Instruction>(Rhs)) 2565 if (!LhsDeps.contains(RhsI)) 2566 RhsDeps.try_emplace(RhsI, false); 2567 2568 const auto &TLI = DAG.getTargetLoweringInfo(); 2569 const auto &TTI = 2570 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 2571 2572 InstructionCost CostOfIncluding = 0; 2573 // See if this instruction will need to computed independently of whether RHS 2574 // is. 2575 Value *BrCond = I.getCondition(); 2576 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) { 2577 for (const auto *U : Ins->users()) { 2578 // If user is independent of RHS calculation we don't need to count it. 2579 if (auto *UIns = dyn_cast<Instruction>(U)) 2580 if (UIns != BrCond && !RhsDeps.contains(UIns)) 2581 return false; 2582 } 2583 return true; 2584 }; 2585 2586 // Prune instructions from RHS Deps that are dependencies of unrelated 2587 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly 2588 // arbitrary and just meant to cap the how much time we spend in the pruning 2589 // loop. Its highly unlikely to come into affect. 2590 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth; 2591 // Stop after a certain point. No incorrectness from including too many 2592 // instructions. 2593 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) { 2594 const Instruction *ToDrop = nullptr; 2595 for (const auto &InsPair : RhsDeps) { 2596 if (!ShouldCountInsn(InsPair.first)) { 2597 ToDrop = InsPair.first; 2598 break; 2599 } 2600 } 2601 if (ToDrop == nullptr) 2602 break; 2603 RhsDeps.erase(ToDrop); 2604 } 2605 2606 for (const auto &InsPair : RhsDeps) { 2607 // Finally accumulate latency that we can only attribute to computing the 2608 // RHS condition. Use latency because we are essentially trying to calculate 2609 // the cost of the dependency chain. 2610 // Possible TODO: We could try to estimate ILP and make this more precise. 2611 CostOfIncluding += 2612 TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency); 2613 2614 if (CostOfIncluding > CostThresh) 2615 return false; 2616 } 2617 return true; 2618 } 2619 2620 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2621 MachineBasicBlock *TBB, 2622 MachineBasicBlock *FBB, 2623 MachineBasicBlock *CurBB, 2624 MachineBasicBlock *SwitchBB, 2625 Instruction::BinaryOps Opc, 2626 BranchProbability TProb, 2627 BranchProbability FProb, 2628 bool InvertCond) { 2629 // Skip over not part of the tree and remember to invert op and operands at 2630 // next level. 2631 Value *NotCond; 2632 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2633 InBlock(NotCond, CurBB->getBasicBlock())) { 2634 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2635 !InvertCond); 2636 return; 2637 } 2638 2639 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2640 const Value *BOpOp0, *BOpOp1; 2641 // Compute the effective opcode for Cond, taking into account whether it needs 2642 // to be inverted, e.g. 2643 // and (not (or A, B)), C 2644 // gets lowered as 2645 // and (and (not A, not B), C) 2646 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2647 if (BOp) { 2648 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2649 ? Instruction::And 2650 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2651 ? Instruction::Or 2652 : (Instruction::BinaryOps)0); 2653 if (InvertCond) { 2654 if (BOpc == Instruction::And) 2655 BOpc = Instruction::Or; 2656 else if (BOpc == Instruction::Or) 2657 BOpc = Instruction::And; 2658 } 2659 } 2660 2661 // If this node is not part of the or/and tree, emit it as a branch. 2662 // Note that all nodes in the tree should have same opcode. 2663 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2664 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2665 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2666 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2667 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2668 TProb, FProb, InvertCond); 2669 return; 2670 } 2671 2672 // Create TmpBB after CurBB. 2673 MachineFunction::iterator BBI(CurBB); 2674 MachineFunction &MF = DAG.getMachineFunction(); 2675 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2676 CurBB->getParent()->insert(++BBI, TmpBB); 2677 2678 if (Opc == Instruction::Or) { 2679 // Codegen X | Y as: 2680 // BB1: 2681 // jmp_if_X TBB 2682 // jmp TmpBB 2683 // TmpBB: 2684 // jmp_if_Y TBB 2685 // jmp FBB 2686 // 2687 2688 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2689 // The requirement is that 2690 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2691 // = TrueProb for original BB. 2692 // Assuming the original probabilities are A and B, one choice is to set 2693 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2694 // A/(1+B) and 2B/(1+B). This choice assumes that 2695 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2696 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2697 // TmpBB, but the math is more complicated. 2698 2699 auto NewTrueProb = TProb / 2; 2700 auto NewFalseProb = TProb / 2 + FProb; 2701 // Emit the LHS condition. 2702 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2703 NewFalseProb, InvertCond); 2704 2705 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2706 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2707 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2708 // Emit the RHS condition into TmpBB. 2709 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2710 Probs[1], InvertCond); 2711 } else { 2712 assert(Opc == Instruction::And && "Unknown merge op!"); 2713 // Codegen X & Y as: 2714 // BB1: 2715 // jmp_if_X TmpBB 2716 // jmp FBB 2717 // TmpBB: 2718 // jmp_if_Y TBB 2719 // jmp FBB 2720 // 2721 // This requires creation of TmpBB after CurBB. 2722 2723 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2724 // The requirement is that 2725 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2726 // = FalseProb for original BB. 2727 // Assuming the original probabilities are A and B, one choice is to set 2728 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2729 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2730 // TrueProb for BB1 * FalseProb for TmpBB. 2731 2732 auto NewTrueProb = TProb + FProb / 2; 2733 auto NewFalseProb = FProb / 2; 2734 // Emit the LHS condition. 2735 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2736 NewFalseProb, InvertCond); 2737 2738 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2739 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2740 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2741 // Emit the RHS condition into TmpBB. 2742 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2743 Probs[1], InvertCond); 2744 } 2745 } 2746 2747 /// If the set of cases should be emitted as a series of branches, return true. 2748 /// If we should emit this as a bunch of and/or'd together conditions, return 2749 /// false. 2750 bool 2751 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2752 if (Cases.size() != 2) return true; 2753 2754 // If this is two comparisons of the same values or'd or and'd together, they 2755 // will get folded into a single comparison, so don't emit two blocks. 2756 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2757 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2758 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2759 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2760 return false; 2761 } 2762 2763 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2764 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2765 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2766 Cases[0].CC == Cases[1].CC && 2767 isa<Constant>(Cases[0].CmpRHS) && 2768 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2769 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2770 return false; 2771 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2772 return false; 2773 } 2774 2775 return true; 2776 } 2777 2778 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2779 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2780 2781 // Update machine-CFG edges. 2782 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0)); 2783 2784 if (I.isUnconditional()) { 2785 // Update machine-CFG edges. 2786 BrMBB->addSuccessor(Succ0MBB); 2787 2788 // If this is not a fall-through branch or optimizations are switched off, 2789 // emit the branch. 2790 if (Succ0MBB != NextBlock(BrMBB) || 2791 TM.getOptLevel() == CodeGenOptLevel::None) { 2792 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2793 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2794 setValue(&I, Br); 2795 DAG.setRoot(Br); 2796 } 2797 2798 return; 2799 } 2800 2801 // If this condition is one of the special cases we handle, do special stuff 2802 // now. 2803 const Value *CondVal = I.getCondition(); 2804 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1)); 2805 2806 // If this is a series of conditions that are or'd or and'd together, emit 2807 // this as a sequence of branches instead of setcc's with and/or operations. 2808 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2809 // unpredictable branches, and vector extracts because those jumps are likely 2810 // expensive for any target), this should improve performance. 2811 // For example, instead of something like: 2812 // cmp A, B 2813 // C = seteq 2814 // cmp D, E 2815 // F = setle 2816 // or C, F 2817 // jnz foo 2818 // Emit: 2819 // cmp A, B 2820 // je foo 2821 // cmp D, E 2822 // jle foo 2823 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable); 2824 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2825 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2826 BOp->hasOneUse() && !IsUnpredictable) { 2827 Value *Vec; 2828 const Value *BOp0, *BOp1; 2829 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2830 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2831 Opcode = Instruction::And; 2832 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2833 Opcode = Instruction::Or; 2834 2835 if (Opcode && 2836 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2837 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) && 2838 !shouldKeepJumpConditionsTogether( 2839 FuncInfo, I, Opcode, BOp0, BOp1, 2840 DAG.getTargetLoweringInfo().getJumpConditionMergingParams( 2841 Opcode, BOp0, BOp1))) { 2842 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2843 getEdgeProbability(BrMBB, Succ0MBB), 2844 getEdgeProbability(BrMBB, Succ1MBB), 2845 /*InvertCond=*/false); 2846 // If the compares in later blocks need to use values not currently 2847 // exported from this block, export them now. This block should always 2848 // be the first entry. 2849 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2850 2851 // Allow some cases to be rejected. 2852 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2853 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2854 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2855 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2856 } 2857 2858 // Emit the branch for this block. 2859 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2860 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2861 return; 2862 } 2863 2864 // Okay, we decided not to do this, remove any inserted MBB's and clear 2865 // SwitchCases. 2866 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2867 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2868 2869 SL->SwitchCases.clear(); 2870 } 2871 } 2872 2873 // Create a CaseBlock record representing this branch. 2874 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2875 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(), 2876 BranchProbability::getUnknown(), BranchProbability::getUnknown(), 2877 IsUnpredictable); 2878 2879 // Use visitSwitchCase to actually insert the fast branch sequence for this 2880 // cond branch. 2881 visitSwitchCase(CB, BrMBB); 2882 } 2883 2884 /// visitSwitchCase - Emits the necessary code to represent a single node in 2885 /// the binary search tree resulting from lowering a switch instruction. 2886 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2887 MachineBasicBlock *SwitchBB) { 2888 SDValue Cond; 2889 SDValue CondLHS = getValue(CB.CmpLHS); 2890 SDLoc dl = CB.DL; 2891 2892 if (CB.CC == ISD::SETTRUE) { 2893 // Branch or fall through to TrueBB. 2894 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2895 SwitchBB->normalizeSuccProbs(); 2896 if (CB.TrueBB != NextBlock(SwitchBB)) { 2897 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2898 DAG.getBasicBlock(CB.TrueBB))); 2899 } 2900 return; 2901 } 2902 2903 auto &TLI = DAG.getTargetLoweringInfo(); 2904 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2905 2906 // Build the setcc now. 2907 if (!CB.CmpMHS) { 2908 // Fold "(X == true)" to X and "(X == false)" to !X to 2909 // handle common cases produced by branch lowering. 2910 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2911 CB.CC == ISD::SETEQ) 2912 Cond = CondLHS; 2913 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2914 CB.CC == ISD::SETEQ) { 2915 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2916 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2917 } else { 2918 SDValue CondRHS = getValue(CB.CmpRHS); 2919 2920 // If a pointer's DAG type is larger than its memory type then the DAG 2921 // values are zero-extended. This breaks signed comparisons so truncate 2922 // back to the underlying type before doing the compare. 2923 if (CondLHS.getValueType() != MemVT) { 2924 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2925 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2926 } 2927 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2928 } 2929 } else { 2930 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2931 2932 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2933 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2934 2935 SDValue CmpOp = getValue(CB.CmpMHS); 2936 EVT VT = CmpOp.getValueType(); 2937 2938 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2939 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2940 ISD::SETLE); 2941 } else { 2942 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2943 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2944 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2945 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2946 } 2947 } 2948 2949 // Update successor info 2950 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2951 // TrueBB and FalseBB are always different unless the incoming IR is 2952 // degenerate. This only happens when running llc on weird IR. 2953 if (CB.TrueBB != CB.FalseBB) 2954 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2955 SwitchBB->normalizeSuccProbs(); 2956 2957 // If the lhs block is the next block, invert the condition so that we can 2958 // fall through to the lhs instead of the rhs block. 2959 if (CB.TrueBB == NextBlock(SwitchBB)) { 2960 std::swap(CB.TrueBB, CB.FalseBB); 2961 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2962 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2963 } 2964 2965 SDNodeFlags Flags; 2966 Flags.setUnpredictable(CB.IsUnpredictable); 2967 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(), 2968 Cond, DAG.getBasicBlock(CB.TrueBB), Flags); 2969 2970 setValue(CurInst, BrCond); 2971 2972 // Insert the false branch. Do this even if it's a fall through branch, 2973 // this makes it easier to do DAG optimizations which require inverting 2974 // the branch condition. 2975 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2976 DAG.getBasicBlock(CB.FalseBB)); 2977 2978 DAG.setRoot(BrCond); 2979 } 2980 2981 /// visitJumpTable - Emit JumpTable node in the current MBB 2982 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2983 // Emit the code for the jump table 2984 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2985 assert(JT.Reg && "Should lower JT Header first!"); 2986 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout()); 2987 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2988 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2989 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2990 Index.getValue(1), Table, Index); 2991 DAG.setRoot(BrJumpTable); 2992 } 2993 2994 /// visitJumpTableHeader - This function emits necessary code to produce index 2995 /// in the JumpTable from switch case. 2996 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2997 JumpTableHeader &JTH, 2998 MachineBasicBlock *SwitchBB) { 2999 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 3000 const SDLoc &dl = *JT.SL; 3001 3002 // Subtract the lowest switch case value from the value being switched on. 3003 SDValue SwitchOp = getValue(JTH.SValue); 3004 EVT VT = SwitchOp.getValueType(); 3005 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 3006 DAG.getConstant(JTH.First, dl, VT)); 3007 3008 // The SDNode we just created, which holds the value being switched on minus 3009 // the smallest case value, needs to be copied to a virtual register so it 3010 // can be used as an index into the jump table in a subsequent basic block. 3011 // This value may be smaller or larger than the target's pointer type, and 3012 // therefore require extension or truncating. 3013 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3014 SwitchOp = 3015 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout())); 3016 3017 Register JumpTableReg = 3018 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout())); 3019 SDValue CopyTo = 3020 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp); 3021 JT.Reg = JumpTableReg; 3022 3023 if (!JTH.FallthroughUnreachable) { 3024 // Emit the range check for the jump table, and branch to the default block 3025 // for the switch statement if the value being switched on exceeds the 3026 // largest case in the switch. 3027 SDValue CMP = DAG.getSetCC( 3028 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3029 Sub.getValueType()), 3030 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 3031 3032 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3033 MVT::Other, CopyTo, CMP, 3034 DAG.getBasicBlock(JT.Default)); 3035 3036 // Avoid emitting unnecessary branches to the next block. 3037 if (JT.MBB != NextBlock(SwitchBB)) 3038 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 3039 DAG.getBasicBlock(JT.MBB)); 3040 3041 DAG.setRoot(BrCond); 3042 } else { 3043 // Avoid emitting unnecessary branches to the next block. 3044 if (JT.MBB != NextBlock(SwitchBB)) 3045 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 3046 DAG.getBasicBlock(JT.MBB))); 3047 else 3048 DAG.setRoot(CopyTo); 3049 } 3050 } 3051 3052 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 3053 /// variable if there exists one. 3054 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 3055 SDValue &Chain) { 3056 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3057 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3058 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3059 MachineFunction &MF = DAG.getMachineFunction(); 3060 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 3061 MachineSDNode *Node = 3062 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 3063 if (Global) { 3064 MachinePointerInfo MPInfo(Global); 3065 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 3066 MachineMemOperand::MODereferenceable; 3067 MachineMemOperand *MemRef = MF.getMachineMemOperand( 3068 MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8), 3069 DAG.getEVTAlign(PtrTy)); 3070 DAG.setNodeMemRefs(Node, {MemRef}); 3071 } 3072 if (PtrTy != PtrMemTy) 3073 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 3074 return SDValue(Node, 0); 3075 } 3076 3077 /// Codegen a new tail for a stack protector check ParentMBB which has had its 3078 /// tail spliced into a stack protector check success bb. 3079 /// 3080 /// For a high level explanation of how this fits into the stack protector 3081 /// generation see the comment on the declaration of class 3082 /// StackProtectorDescriptor. 3083 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 3084 MachineBasicBlock *ParentBB) { 3085 3086 // First create the loads to the guard/stack slot for the comparison. 3087 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3088 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3089 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3090 3091 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 3092 int FI = MFI.getStackProtectorIndex(); 3093 3094 SDValue Guard; 3095 SDLoc dl = getCurSDLoc(); 3096 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 3097 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 3098 Align Align = 3099 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 3100 3101 // Generate code to load the content of the guard slot. 3102 SDValue GuardVal = DAG.getLoad( 3103 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 3104 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 3105 MachineMemOperand::MOVolatile); 3106 3107 if (TLI.useStackGuardXorFP()) 3108 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 3109 3110 // Retrieve guard check function, nullptr if instrumentation is inlined. 3111 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 3112 // The target provides a guard check function to validate the guard value. 3113 // Generate a call to that function with the content of the guard slot as 3114 // argument. 3115 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 3116 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 3117 3118 TargetLowering::ArgListTy Args; 3119 TargetLowering::ArgListEntry Entry; 3120 Entry.Node = GuardVal; 3121 Entry.Ty = FnTy->getParamType(0); 3122 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 3123 Entry.IsInReg = true; 3124 Args.push_back(Entry); 3125 3126 TargetLowering::CallLoweringInfo CLI(DAG); 3127 CLI.setDebugLoc(getCurSDLoc()) 3128 .setChain(DAG.getEntryNode()) 3129 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 3130 getValue(GuardCheckFn), std::move(Args)); 3131 3132 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 3133 DAG.setRoot(Result.second); 3134 return; 3135 } 3136 3137 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 3138 // Otherwise, emit a volatile load to retrieve the stack guard value. 3139 SDValue Chain = DAG.getEntryNode(); 3140 if (TLI.useLoadStackGuardNode(M)) { 3141 Guard = getLoadStackGuard(DAG, dl, Chain); 3142 } else { 3143 const Value *IRGuard = TLI.getSDagStackGuard(M); 3144 SDValue GuardPtr = getValue(IRGuard); 3145 3146 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 3147 MachinePointerInfo(IRGuard, 0), Align, 3148 MachineMemOperand::MOVolatile); 3149 } 3150 3151 // Perform the comparison via a getsetcc. 3152 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 3153 *DAG.getContext(), 3154 Guard.getValueType()), 3155 Guard, GuardVal, ISD::SETNE); 3156 3157 // If the guard/stackslot do not equal, branch to failure MBB. 3158 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3159 MVT::Other, GuardVal.getOperand(0), 3160 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 3161 // Otherwise branch to success MBB. 3162 SDValue Br = DAG.getNode(ISD::BR, dl, 3163 MVT::Other, BrCond, 3164 DAG.getBasicBlock(SPD.getSuccessMBB())); 3165 3166 DAG.setRoot(Br); 3167 } 3168 3169 /// Codegen the failure basic block for a stack protector check. 3170 /// 3171 /// A failure stack protector machine basic block consists simply of a call to 3172 /// __stack_chk_fail(). 3173 /// 3174 /// For a high level explanation of how this fits into the stack protector 3175 /// generation see the comment on the declaration of class 3176 /// StackProtectorDescriptor. 3177 void 3178 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 3179 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3180 TargetLowering::MakeLibCallOptions CallOptions; 3181 CallOptions.setDiscardResult(true); 3182 SDValue Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, 3183 MVT::isVoid, {}, CallOptions, getCurSDLoc()) 3184 .second; 3185 3186 // Emit a trap instruction if we are required to do so. 3187 const TargetOptions &TargetOpts = DAG.getTarget().Options; 3188 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn) 3189 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3190 3191 DAG.setRoot(Chain); 3192 } 3193 3194 /// visitBitTestHeader - This function emits necessary code to produce value 3195 /// suitable for "bit tests" 3196 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3197 MachineBasicBlock *SwitchBB) { 3198 SDLoc dl = getCurSDLoc(); 3199 3200 // Subtract the minimum value. 3201 SDValue SwitchOp = getValue(B.SValue); 3202 EVT VT = SwitchOp.getValueType(); 3203 SDValue RangeSub = 3204 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3205 3206 // Determine the type of the test operands. 3207 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3208 bool UsePtrType = false; 3209 if (!TLI.isTypeLegal(VT)) { 3210 UsePtrType = true; 3211 } else { 3212 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3213 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3214 // Switch table case range are encoded into series of masks. 3215 // Just use pointer type, it's guaranteed to fit. 3216 UsePtrType = true; 3217 break; 3218 } 3219 } 3220 SDValue Sub = RangeSub; 3221 if (UsePtrType) { 3222 VT = TLI.getPointerTy(DAG.getDataLayout()); 3223 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3224 } 3225 3226 B.RegVT = VT.getSimpleVT(); 3227 B.Reg = FuncInfo.CreateReg(B.RegVT); 3228 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3229 3230 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3231 3232 if (!B.FallthroughUnreachable) 3233 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3234 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3235 SwitchBB->normalizeSuccProbs(); 3236 3237 SDValue Root = CopyTo; 3238 if (!B.FallthroughUnreachable) { 3239 // Conditional branch to the default block. 3240 SDValue RangeCmp = DAG.getSetCC(dl, 3241 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3242 RangeSub.getValueType()), 3243 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3244 ISD::SETUGT); 3245 3246 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3247 DAG.getBasicBlock(B.Default)); 3248 } 3249 3250 // Avoid emitting unnecessary branches to the next block. 3251 if (MBB != NextBlock(SwitchBB)) 3252 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3253 3254 DAG.setRoot(Root); 3255 } 3256 3257 /// visitBitTestCase - this function produces one "bit test" 3258 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3259 MachineBasicBlock *NextMBB, 3260 BranchProbability BranchProbToNext, 3261 Register Reg, BitTestCase &B, 3262 MachineBasicBlock *SwitchBB) { 3263 SDLoc dl = getCurSDLoc(); 3264 MVT VT = BB.RegVT; 3265 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3266 SDValue Cmp; 3267 unsigned PopCount = llvm::popcount(B.Mask); 3268 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3269 if (PopCount == 1) { 3270 // Testing for a single bit; just compare the shift count with what it 3271 // would need to be to shift a 1 bit in that position. 3272 Cmp = DAG.getSetCC( 3273 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3274 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3275 ISD::SETEQ); 3276 } else if (PopCount == BB.Range) { 3277 // There is only one zero bit in the range, test for it directly. 3278 Cmp = DAG.getSetCC( 3279 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3280 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3281 } else { 3282 // Make desired shift 3283 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3284 DAG.getConstant(1, dl, VT), ShiftOp); 3285 3286 // Emit bit tests and jumps 3287 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3288 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3289 Cmp = DAG.getSetCC( 3290 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3291 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3292 } 3293 3294 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3295 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3296 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3297 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3298 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3299 // one as they are relative probabilities (and thus work more like weights), 3300 // and hence we need to normalize them to let the sum of them become one. 3301 SwitchBB->normalizeSuccProbs(); 3302 3303 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3304 MVT::Other, getControlRoot(), 3305 Cmp, DAG.getBasicBlock(B.TargetBB)); 3306 3307 // Avoid emitting unnecessary branches to the next block. 3308 if (NextMBB != NextBlock(SwitchBB)) 3309 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3310 DAG.getBasicBlock(NextMBB)); 3311 3312 DAG.setRoot(BrAnd); 3313 } 3314 3315 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3316 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3317 3318 // Retrieve successors. Look through artificial IR level blocks like 3319 // catchswitch for successors. 3320 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0)); 3321 const BasicBlock *EHPadBB = I.getSuccessor(1); 3322 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB); 3323 3324 // Deopt and ptrauth bundles are lowered in helper functions, and we don't 3325 // have to do anything here to lower funclet bundles. 3326 assert(!I.hasOperandBundlesOtherThan( 3327 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3328 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3329 LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth, 3330 LLVMContext::OB_clang_arc_attachedcall}) && 3331 "Cannot lower invokes with arbitrary operand bundles yet!"); 3332 3333 const Value *Callee(I.getCalledOperand()); 3334 const Function *Fn = dyn_cast<Function>(Callee); 3335 if (isa<InlineAsm>(Callee)) 3336 visitInlineAsm(I, EHPadBB); 3337 else if (Fn && Fn->isIntrinsic()) { 3338 switch (Fn->getIntrinsicID()) { 3339 default: 3340 llvm_unreachable("Cannot invoke this intrinsic"); 3341 case Intrinsic::donothing: 3342 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3343 case Intrinsic::seh_try_begin: 3344 case Intrinsic::seh_scope_begin: 3345 case Intrinsic::seh_try_end: 3346 case Intrinsic::seh_scope_end: 3347 if (EHPadMBB) 3348 // a block referenced by EH table 3349 // so dtor-funclet not removed by opts 3350 EHPadMBB->setMachineBlockAddressTaken(); 3351 break; 3352 case Intrinsic::experimental_patchpoint_void: 3353 case Intrinsic::experimental_patchpoint: 3354 visitPatchpoint(I, EHPadBB); 3355 break; 3356 case Intrinsic::experimental_gc_statepoint: 3357 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3358 break; 3359 case Intrinsic::wasm_rethrow: { 3360 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3361 // special because it can be invoked, so we manually lower it to a DAG 3362 // node here. 3363 SmallVector<SDValue, 8> Ops; 3364 Ops.push_back(getControlRoot()); // inchain for the terminator node 3365 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3366 Ops.push_back( 3367 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3368 TLI.getPointerTy(DAG.getDataLayout()))); 3369 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3370 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3371 break; 3372 } 3373 } 3374 } else if (I.hasDeoptState()) { 3375 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3376 // Eventually we will support lowering the @llvm.experimental.deoptimize 3377 // intrinsic, and right now there are no plans to support other intrinsics 3378 // with deopt state. 3379 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3380 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 3381 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB); 3382 } else { 3383 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3384 } 3385 3386 // If the value of the invoke is used outside of its defining block, make it 3387 // available as a virtual register. 3388 // We already took care of the exported value for the statepoint instruction 3389 // during call to the LowerStatepoint. 3390 if (!isa<GCStatepointInst>(I)) { 3391 CopyToExportRegsIfNeeded(&I); 3392 } 3393 3394 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3395 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3396 BranchProbability EHPadBBProb = 3397 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3398 : BranchProbability::getZero(); 3399 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3400 3401 // Update successor info. 3402 addSuccessorWithProb(InvokeMBB, Return); 3403 for (auto &UnwindDest : UnwindDests) { 3404 UnwindDest.first->setIsEHPad(); 3405 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3406 } 3407 InvokeMBB->normalizeSuccProbs(); 3408 3409 // Drop into normal successor. 3410 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3411 DAG.getBasicBlock(Return))); 3412 } 3413 3414 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3415 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3416 3417 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3418 // have to do anything here to lower funclet bundles. 3419 assert(!I.hasOperandBundlesOtherThan( 3420 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3421 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3422 3423 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3424 visitInlineAsm(I); 3425 CopyToExportRegsIfNeeded(&I); 3426 3427 // Retrieve successors. 3428 SmallPtrSet<BasicBlock *, 8> Dests; 3429 Dests.insert(I.getDefaultDest()); 3430 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest()); 3431 3432 // Update successor info. 3433 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3434 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3435 BasicBlock *Dest = I.getIndirectDest(i); 3436 MachineBasicBlock *Target = FuncInfo.getMBB(Dest); 3437 Target->setIsInlineAsmBrIndirectTarget(); 3438 Target->setMachineBlockAddressTaken(); 3439 Target->setLabelMustBeEmitted(); 3440 // Don't add duplicate machine successors. 3441 if (Dests.insert(Dest).second) 3442 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3443 } 3444 CallBrMBB->normalizeSuccProbs(); 3445 3446 // Drop into default successor. 3447 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3448 MVT::Other, getControlRoot(), 3449 DAG.getBasicBlock(Return))); 3450 } 3451 3452 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3453 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3454 } 3455 3456 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3457 assert(FuncInfo.MBB->isEHPad() && 3458 "Call to landingpad not in landing pad!"); 3459 3460 // If there aren't registers to copy the values into (e.g., during SjLj 3461 // exceptions), then don't bother to create these DAG nodes. 3462 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3463 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3464 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3465 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3466 return; 3467 3468 // If landingpad's return type is token type, we don't create DAG nodes 3469 // for its exception pointer and selector value. The extraction of exception 3470 // pointer or selector value from token type landingpads is not currently 3471 // supported. 3472 if (LP.getType()->isTokenTy()) 3473 return; 3474 3475 SmallVector<EVT, 2> ValueVTs; 3476 SDLoc dl = getCurSDLoc(); 3477 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3478 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3479 3480 // Get the two live-in registers as SDValues. The physregs have already been 3481 // copied into virtual registers. 3482 SDValue Ops[2]; 3483 if (FuncInfo.ExceptionPointerVirtReg) { 3484 Ops[0] = DAG.getZExtOrTrunc( 3485 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3486 FuncInfo.ExceptionPointerVirtReg, 3487 TLI.getPointerTy(DAG.getDataLayout())), 3488 dl, ValueVTs[0]); 3489 } else { 3490 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3491 } 3492 Ops[1] = DAG.getZExtOrTrunc( 3493 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3494 FuncInfo.ExceptionSelectorVirtReg, 3495 TLI.getPointerTy(DAG.getDataLayout())), 3496 dl, ValueVTs[1]); 3497 3498 // Merge into one. 3499 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3500 DAG.getVTList(ValueVTs), Ops); 3501 setValue(&LP, Res); 3502 } 3503 3504 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3505 MachineBasicBlock *Last) { 3506 // Update JTCases. 3507 for (JumpTableBlock &JTB : SL->JTCases) 3508 if (JTB.first.HeaderBB == First) 3509 JTB.first.HeaderBB = Last; 3510 3511 // Update BitTestCases. 3512 for (BitTestBlock &BTB : SL->BitTestCases) 3513 if (BTB.Parent == First) 3514 BTB.Parent = Last; 3515 } 3516 3517 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3518 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3519 3520 // Update machine-CFG edges with unique successors. 3521 SmallSet<BasicBlock*, 32> Done; 3522 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3523 BasicBlock *BB = I.getSuccessor(i); 3524 bool Inserted = Done.insert(BB).second; 3525 if (!Inserted) 3526 continue; 3527 3528 MachineBasicBlock *Succ = FuncInfo.getMBB(BB); 3529 addSuccessorWithProb(IndirectBrMBB, Succ); 3530 } 3531 IndirectBrMBB->normalizeSuccProbs(); 3532 3533 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3534 MVT::Other, getControlRoot(), 3535 getValue(I.getAddress()))); 3536 } 3537 3538 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3539 if (!DAG.getTarget().Options.TrapUnreachable) 3540 return; 3541 3542 // We may be able to ignore unreachable behind a noreturn call. 3543 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode()); 3544 Call && Call->doesNotReturn()) { 3545 if (DAG.getTarget().Options.NoTrapAfterNoreturn) 3546 return; 3547 // Do not emit an additional trap instruction. 3548 if (Call->isNonContinuableTrap()) 3549 return; 3550 } 3551 3552 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3553 } 3554 3555 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3556 SDNodeFlags Flags; 3557 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3558 Flags.copyFMF(*FPOp); 3559 3560 SDValue Op = getValue(I.getOperand(0)); 3561 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3562 Op, Flags); 3563 setValue(&I, UnNodeValue); 3564 } 3565 3566 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3567 SDNodeFlags Flags; 3568 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3569 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3570 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3571 } 3572 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3573 Flags.setExact(ExactOp->isExact()); 3574 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3575 Flags.setDisjoint(DisjointOp->isDisjoint()); 3576 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3577 Flags.copyFMF(*FPOp); 3578 3579 SDValue Op1 = getValue(I.getOperand(0)); 3580 SDValue Op2 = getValue(I.getOperand(1)); 3581 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3582 Op1, Op2, Flags); 3583 setValue(&I, BinNodeValue); 3584 } 3585 3586 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3587 SDValue Op1 = getValue(I.getOperand(0)); 3588 SDValue Op2 = getValue(I.getOperand(1)); 3589 3590 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3591 Op1.getValueType(), DAG.getDataLayout()); 3592 3593 // Coerce the shift amount to the right type if we can. This exposes the 3594 // truncate or zext to optimization early. 3595 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3596 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3597 "Unexpected shift type"); 3598 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3599 } 3600 3601 bool nuw = false; 3602 bool nsw = false; 3603 bool exact = false; 3604 3605 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3606 3607 if (const OverflowingBinaryOperator *OFBinOp = 3608 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3609 nuw = OFBinOp->hasNoUnsignedWrap(); 3610 nsw = OFBinOp->hasNoSignedWrap(); 3611 } 3612 if (const PossiblyExactOperator *ExactOp = 3613 dyn_cast<const PossiblyExactOperator>(&I)) 3614 exact = ExactOp->isExact(); 3615 } 3616 SDNodeFlags Flags; 3617 Flags.setExact(exact); 3618 Flags.setNoSignedWrap(nsw); 3619 Flags.setNoUnsignedWrap(nuw); 3620 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3621 Flags); 3622 setValue(&I, Res); 3623 } 3624 3625 void SelectionDAGBuilder::visitSDiv(const User &I) { 3626 SDValue Op1 = getValue(I.getOperand(0)); 3627 SDValue Op2 = getValue(I.getOperand(1)); 3628 3629 SDNodeFlags Flags; 3630 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3631 cast<PossiblyExactOperator>(&I)->isExact()); 3632 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3633 Op2, Flags)); 3634 } 3635 3636 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) { 3637 ICmpInst::Predicate predicate = I.getPredicate(); 3638 SDValue Op1 = getValue(I.getOperand(0)); 3639 SDValue Op2 = getValue(I.getOperand(1)); 3640 ISD::CondCode Opcode = getICmpCondCode(predicate); 3641 3642 auto &TLI = DAG.getTargetLoweringInfo(); 3643 EVT MemVT = 3644 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3645 3646 // If a pointer's DAG type is larger than its memory type then the DAG values 3647 // are zero-extended. This breaks signed comparisons so truncate back to the 3648 // underlying type before doing the compare. 3649 if (Op1.getValueType() != MemVT) { 3650 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3651 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3652 } 3653 3654 SDNodeFlags Flags; 3655 Flags.setSameSign(I.hasSameSign()); 3656 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3657 3658 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3659 I.getType()); 3660 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3661 } 3662 3663 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) { 3664 FCmpInst::Predicate predicate = I.getPredicate(); 3665 SDValue Op1 = getValue(I.getOperand(0)); 3666 SDValue Op2 = getValue(I.getOperand(1)); 3667 3668 ISD::CondCode Condition = getFCmpCondCode(predicate); 3669 auto *FPMO = cast<FPMathOperator>(&I); 3670 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3671 Condition = getFCmpCodeWithoutNaN(Condition); 3672 3673 SDNodeFlags Flags; 3674 Flags.copyFMF(*FPMO); 3675 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3676 3677 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3678 I.getType()); 3679 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3680 } 3681 3682 // Check if the condition of the select has one use or two users that are both 3683 // selects with the same condition. 3684 static bool hasOnlySelectUsers(const Value *Cond) { 3685 return llvm::all_of(Cond->users(), [](const Value *V) { 3686 return isa<SelectInst>(V); 3687 }); 3688 } 3689 3690 void SelectionDAGBuilder::visitSelect(const User &I) { 3691 SmallVector<EVT, 4> ValueVTs; 3692 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3693 ValueVTs); 3694 unsigned NumValues = ValueVTs.size(); 3695 if (NumValues == 0) return; 3696 3697 SmallVector<SDValue, 4> Values(NumValues); 3698 SDValue Cond = getValue(I.getOperand(0)); 3699 SDValue LHSVal = getValue(I.getOperand(1)); 3700 SDValue RHSVal = getValue(I.getOperand(2)); 3701 SmallVector<SDValue, 1> BaseOps(1, Cond); 3702 ISD::NodeType OpCode = 3703 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3704 3705 bool IsUnaryAbs = false; 3706 bool Negate = false; 3707 3708 SDNodeFlags Flags; 3709 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3710 Flags.copyFMF(*FPOp); 3711 3712 Flags.setUnpredictable( 3713 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3714 3715 // Min/max matching is only viable if all output VTs are the same. 3716 if (all_equal(ValueVTs)) { 3717 EVT VT = ValueVTs[0]; 3718 LLVMContext &Ctx = *DAG.getContext(); 3719 auto &TLI = DAG.getTargetLoweringInfo(); 3720 3721 // We care about the legality of the operation after it has been type 3722 // legalized. 3723 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3724 VT = TLI.getTypeToTransformTo(Ctx, VT); 3725 3726 // If the vselect is legal, assume we want to leave this as a vector setcc + 3727 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3728 // min/max is legal on the scalar type. 3729 bool UseScalarMinMax = VT.isVector() && 3730 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3731 3732 // ValueTracking's select pattern matching does not account for -0.0, 3733 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3734 // -0.0 is less than +0.0. 3735 const Value *LHS, *RHS; 3736 auto SPR = matchSelectPattern(&I, LHS, RHS); 3737 ISD::NodeType Opc = ISD::DELETED_NODE; 3738 switch (SPR.Flavor) { 3739 case SPF_UMAX: Opc = ISD::UMAX; break; 3740 case SPF_UMIN: Opc = ISD::UMIN; break; 3741 case SPF_SMAX: Opc = ISD::SMAX; break; 3742 case SPF_SMIN: Opc = ISD::SMIN; break; 3743 case SPF_FMINNUM: 3744 switch (SPR.NaNBehavior) { 3745 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3746 case SPNB_RETURNS_NAN: break; 3747 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3748 case SPNB_RETURNS_ANY: 3749 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3750 (UseScalarMinMax && 3751 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3752 Opc = ISD::FMINNUM; 3753 break; 3754 } 3755 break; 3756 case SPF_FMAXNUM: 3757 switch (SPR.NaNBehavior) { 3758 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3759 case SPNB_RETURNS_NAN: break; 3760 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3761 case SPNB_RETURNS_ANY: 3762 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3763 (UseScalarMinMax && 3764 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3765 Opc = ISD::FMAXNUM; 3766 break; 3767 } 3768 break; 3769 case SPF_NABS: 3770 Negate = true; 3771 [[fallthrough]]; 3772 case SPF_ABS: 3773 IsUnaryAbs = true; 3774 Opc = ISD::ABS; 3775 break; 3776 default: break; 3777 } 3778 3779 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3780 (TLI.isOperationLegalOrCustom(Opc, VT) || 3781 (UseScalarMinMax && 3782 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3783 // If the underlying comparison instruction is used by any other 3784 // instruction, the consumed instructions won't be destroyed, so it is 3785 // not profitable to convert to a min/max. 3786 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3787 OpCode = Opc; 3788 LHSVal = getValue(LHS); 3789 RHSVal = getValue(RHS); 3790 BaseOps.clear(); 3791 } 3792 3793 if (IsUnaryAbs) { 3794 OpCode = Opc; 3795 LHSVal = getValue(LHS); 3796 BaseOps.clear(); 3797 } 3798 } 3799 3800 if (IsUnaryAbs) { 3801 for (unsigned i = 0; i != NumValues; ++i) { 3802 SDLoc dl = getCurSDLoc(); 3803 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3804 Values[i] = 3805 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3806 if (Negate) 3807 Values[i] = DAG.getNegative(Values[i], dl, VT); 3808 } 3809 } else { 3810 for (unsigned i = 0; i != NumValues; ++i) { 3811 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3812 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3813 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3814 Values[i] = DAG.getNode( 3815 OpCode, getCurSDLoc(), 3816 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3817 } 3818 } 3819 3820 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3821 DAG.getVTList(ValueVTs), Values)); 3822 } 3823 3824 void SelectionDAGBuilder::visitTrunc(const User &I) { 3825 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3826 SDValue N = getValue(I.getOperand(0)); 3827 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3828 I.getType()); 3829 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3830 } 3831 3832 void SelectionDAGBuilder::visitZExt(const User &I) { 3833 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3834 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3835 SDValue N = getValue(I.getOperand(0)); 3836 auto &TLI = DAG.getTargetLoweringInfo(); 3837 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3838 3839 SDNodeFlags Flags; 3840 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3841 Flags.setNonNeg(PNI->hasNonNeg()); 3842 3843 // Eagerly use nonneg information to canonicalize towards sign_extend if 3844 // that is the target's preference. 3845 // TODO: Let the target do this later. 3846 if (Flags.hasNonNeg() && 3847 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3848 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3849 return; 3850 } 3851 3852 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3853 } 3854 3855 void SelectionDAGBuilder::visitSExt(const User &I) { 3856 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3857 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3858 SDValue N = getValue(I.getOperand(0)); 3859 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3860 I.getType()); 3861 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3862 } 3863 3864 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3865 // FPTrunc is never a no-op cast, no need to check 3866 SDValue N = getValue(I.getOperand(0)); 3867 SDLoc dl = getCurSDLoc(); 3868 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3869 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3870 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3871 DAG.getTargetConstant( 3872 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3873 } 3874 3875 void SelectionDAGBuilder::visitFPExt(const User &I) { 3876 // FPExt is never a no-op cast, no need to check 3877 SDValue N = getValue(I.getOperand(0)); 3878 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3879 I.getType()); 3880 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3881 } 3882 3883 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3884 // FPToUI is never a no-op cast, no need to check 3885 SDValue N = getValue(I.getOperand(0)); 3886 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3887 I.getType()); 3888 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3889 } 3890 3891 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3892 // FPToSI is never a no-op cast, no need to check 3893 SDValue N = getValue(I.getOperand(0)); 3894 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3895 I.getType()); 3896 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3897 } 3898 3899 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3900 // UIToFP is never a no-op cast, no need to check 3901 SDValue N = getValue(I.getOperand(0)); 3902 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3903 I.getType()); 3904 SDNodeFlags Flags; 3905 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3906 Flags.setNonNeg(PNI->hasNonNeg()); 3907 3908 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags)); 3909 } 3910 3911 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3912 // SIToFP is never a no-op cast, no need to check 3913 SDValue N = getValue(I.getOperand(0)); 3914 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3915 I.getType()); 3916 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3917 } 3918 3919 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3920 // What to do depends on the size of the integer and the size of the pointer. 3921 // We can either truncate, zero extend, or no-op, accordingly. 3922 SDValue N = getValue(I.getOperand(0)); 3923 auto &TLI = DAG.getTargetLoweringInfo(); 3924 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3925 I.getType()); 3926 EVT PtrMemVT = 3927 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3928 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3929 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3930 setValue(&I, N); 3931 } 3932 3933 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3934 // What to do depends on the size of the integer and the size of the pointer. 3935 // We can either truncate, zero extend, or no-op, accordingly. 3936 SDValue N = getValue(I.getOperand(0)); 3937 auto &TLI = DAG.getTargetLoweringInfo(); 3938 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3939 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3940 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3941 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3942 setValue(&I, N); 3943 } 3944 3945 void SelectionDAGBuilder::visitBitCast(const User &I) { 3946 SDValue N = getValue(I.getOperand(0)); 3947 SDLoc dl = getCurSDLoc(); 3948 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3949 I.getType()); 3950 3951 // BitCast assures us that source and destination are the same size so this is 3952 // either a BITCAST or a no-op. 3953 if (DestVT != N.getValueType()) 3954 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3955 DestVT, N)); // convert types. 3956 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3957 // might fold any kind of constant expression to an integer constant and that 3958 // is not what we are looking for. Only recognize a bitcast of a genuine 3959 // constant integer as an opaque constant. 3960 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3961 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3962 /*isOpaque*/true)); 3963 else 3964 setValue(&I, N); // noop cast. 3965 } 3966 3967 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3968 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3969 const Value *SV = I.getOperand(0); 3970 SDValue N = getValue(SV); 3971 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3972 3973 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3974 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3975 3976 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3977 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3978 3979 setValue(&I, N); 3980 } 3981 3982 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3983 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3984 SDValue InVec = getValue(I.getOperand(0)); 3985 SDValue InVal = getValue(I.getOperand(1)); 3986 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3987 TLI.getVectorIdxTy(DAG.getDataLayout())); 3988 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3989 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3990 InVec, InVal, InIdx)); 3991 } 3992 3993 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3994 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3995 SDValue InVec = getValue(I.getOperand(0)); 3996 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3997 TLI.getVectorIdxTy(DAG.getDataLayout())); 3998 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3999 TLI.getValueType(DAG.getDataLayout(), I.getType()), 4000 InVec, InIdx)); 4001 } 4002 4003 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 4004 SDValue Src1 = getValue(I.getOperand(0)); 4005 SDValue Src2 = getValue(I.getOperand(1)); 4006 ArrayRef<int> Mask; 4007 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 4008 Mask = SVI->getShuffleMask(); 4009 else 4010 Mask = cast<ConstantExpr>(I).getShuffleMask(); 4011 SDLoc DL = getCurSDLoc(); 4012 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4013 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4014 EVT SrcVT = Src1.getValueType(); 4015 4016 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 4017 VT.isScalableVector()) { 4018 // Canonical splat form of first element of first input vector. 4019 SDValue FirstElt = 4020 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 4021 DAG.getVectorIdxConstant(0, DL)); 4022 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 4023 return; 4024 } 4025 4026 // For now, we only handle splats for scalable vectors. 4027 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 4028 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 4029 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 4030 4031 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 4032 unsigned MaskNumElts = Mask.size(); 4033 4034 if (SrcNumElts == MaskNumElts) { 4035 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 4036 return; 4037 } 4038 4039 // Normalize the shuffle vector since mask and vector length don't match. 4040 if (SrcNumElts < MaskNumElts) { 4041 // Mask is longer than the source vectors. We can use concatenate vector to 4042 // make the mask and vectors lengths match. 4043 4044 if (MaskNumElts % SrcNumElts == 0) { 4045 // Mask length is a multiple of the source vector length. 4046 // Check if the shuffle is some kind of concatenation of the input 4047 // vectors. 4048 unsigned NumConcat = MaskNumElts / SrcNumElts; 4049 bool IsConcat = true; 4050 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 4051 for (unsigned i = 0; i != MaskNumElts; ++i) { 4052 int Idx = Mask[i]; 4053 if (Idx < 0) 4054 continue; 4055 // Ensure the indices in each SrcVT sized piece are sequential and that 4056 // the same source is used for the whole piece. 4057 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 4058 (ConcatSrcs[i / SrcNumElts] >= 0 && 4059 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 4060 IsConcat = false; 4061 break; 4062 } 4063 // Remember which source this index came from. 4064 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 4065 } 4066 4067 // The shuffle is concatenating multiple vectors together. Just emit 4068 // a CONCAT_VECTORS operation. 4069 if (IsConcat) { 4070 SmallVector<SDValue, 8> ConcatOps; 4071 for (auto Src : ConcatSrcs) { 4072 if (Src < 0) 4073 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 4074 else if (Src == 0) 4075 ConcatOps.push_back(Src1); 4076 else 4077 ConcatOps.push_back(Src2); 4078 } 4079 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 4080 return; 4081 } 4082 } 4083 4084 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 4085 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 4086 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 4087 PaddedMaskNumElts); 4088 4089 // Pad both vectors with undefs to make them the same length as the mask. 4090 SDValue UndefVal = DAG.getUNDEF(SrcVT); 4091 4092 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 4093 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 4094 MOps1[0] = Src1; 4095 MOps2[0] = Src2; 4096 4097 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 4098 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 4099 4100 // Readjust mask for new input vector length. 4101 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 4102 for (unsigned i = 0; i != MaskNumElts; ++i) { 4103 int Idx = Mask[i]; 4104 if (Idx >= (int)SrcNumElts) 4105 Idx -= SrcNumElts - PaddedMaskNumElts; 4106 MappedOps[i] = Idx; 4107 } 4108 4109 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 4110 4111 // If the concatenated vector was padded, extract a subvector with the 4112 // correct number of elements. 4113 if (MaskNumElts != PaddedMaskNumElts) 4114 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 4115 DAG.getVectorIdxConstant(0, DL)); 4116 4117 setValue(&I, Result); 4118 return; 4119 } 4120 4121 assert(SrcNumElts > MaskNumElts); 4122 4123 // Analyze the access pattern of the vector to see if we can extract 4124 // two subvectors and do the shuffle. 4125 int StartIdx[2] = {-1, -1}; // StartIdx to extract from 4126 bool CanExtract = true; 4127 for (int Idx : Mask) { 4128 unsigned Input = 0; 4129 if (Idx < 0) 4130 continue; 4131 4132 if (Idx >= (int)SrcNumElts) { 4133 Input = 1; 4134 Idx -= SrcNumElts; 4135 } 4136 4137 // If all the indices come from the same MaskNumElts sized portion of 4138 // the sources we can use extract. Also make sure the extract wouldn't 4139 // extract past the end of the source. 4140 int NewStartIdx = alignDown(Idx, MaskNumElts); 4141 if (NewStartIdx + MaskNumElts > SrcNumElts || 4142 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 4143 CanExtract = false; 4144 // Make sure we always update StartIdx as we use it to track if all 4145 // elements are undef. 4146 StartIdx[Input] = NewStartIdx; 4147 } 4148 4149 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 4150 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 4151 return; 4152 } 4153 if (CanExtract) { 4154 // Extract appropriate subvector and generate a vector shuffle 4155 for (unsigned Input = 0; Input < 2; ++Input) { 4156 SDValue &Src = Input == 0 ? Src1 : Src2; 4157 if (StartIdx[Input] < 0) 4158 Src = DAG.getUNDEF(VT); 4159 else { 4160 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 4161 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 4162 } 4163 } 4164 4165 // Calculate new mask. 4166 SmallVector<int, 8> MappedOps(Mask); 4167 for (int &Idx : MappedOps) { 4168 if (Idx >= (int)SrcNumElts) 4169 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 4170 else if (Idx >= 0) 4171 Idx -= StartIdx[0]; 4172 } 4173 4174 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 4175 return; 4176 } 4177 4178 // We can't use either concat vectors or extract subvectors so fall back to 4179 // replacing the shuffle with extract and build vector. 4180 // to insert and build vector. 4181 EVT EltVT = VT.getVectorElementType(); 4182 SmallVector<SDValue,8> Ops; 4183 for (int Idx : Mask) { 4184 SDValue Res; 4185 4186 if (Idx < 0) { 4187 Res = DAG.getUNDEF(EltVT); 4188 } else { 4189 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 4190 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 4191 4192 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4193 DAG.getVectorIdxConstant(Idx, DL)); 4194 } 4195 4196 Ops.push_back(Res); 4197 } 4198 4199 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4200 } 4201 4202 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4203 ArrayRef<unsigned> Indices = I.getIndices(); 4204 const Value *Op0 = I.getOperand(0); 4205 const Value *Op1 = I.getOperand(1); 4206 Type *AggTy = I.getType(); 4207 Type *ValTy = Op1->getType(); 4208 bool IntoUndef = isa<UndefValue>(Op0); 4209 bool FromUndef = isa<UndefValue>(Op1); 4210 4211 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4212 4213 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4214 SmallVector<EVT, 4> AggValueVTs; 4215 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4216 SmallVector<EVT, 4> ValValueVTs; 4217 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4218 4219 unsigned NumAggValues = AggValueVTs.size(); 4220 unsigned NumValValues = ValValueVTs.size(); 4221 SmallVector<SDValue, 4> Values(NumAggValues); 4222 4223 // Ignore an insertvalue that produces an empty object 4224 if (!NumAggValues) { 4225 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4226 return; 4227 } 4228 4229 SDValue Agg = getValue(Op0); 4230 unsigned i = 0; 4231 // Copy the beginning value(s) from the original aggregate. 4232 for (; i != LinearIndex; ++i) 4233 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4234 SDValue(Agg.getNode(), Agg.getResNo() + i); 4235 // Copy values from the inserted value(s). 4236 if (NumValValues) { 4237 SDValue Val = getValue(Op1); 4238 for (; i != LinearIndex + NumValValues; ++i) 4239 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4240 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4241 } 4242 // Copy remaining value(s) from the original aggregate. 4243 for (; i != NumAggValues; ++i) 4244 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4245 SDValue(Agg.getNode(), Agg.getResNo() + i); 4246 4247 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4248 DAG.getVTList(AggValueVTs), Values)); 4249 } 4250 4251 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4252 ArrayRef<unsigned> Indices = I.getIndices(); 4253 const Value *Op0 = I.getOperand(0); 4254 Type *AggTy = Op0->getType(); 4255 Type *ValTy = I.getType(); 4256 bool OutOfUndef = isa<UndefValue>(Op0); 4257 4258 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4259 4260 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4261 SmallVector<EVT, 4> ValValueVTs; 4262 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4263 4264 unsigned NumValValues = ValValueVTs.size(); 4265 4266 // Ignore a extractvalue that produces an empty object 4267 if (!NumValValues) { 4268 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4269 return; 4270 } 4271 4272 SmallVector<SDValue, 4> Values(NumValValues); 4273 4274 SDValue Agg = getValue(Op0); 4275 // Copy out the selected value(s). 4276 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4277 Values[i - LinearIndex] = 4278 OutOfUndef ? 4279 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4280 SDValue(Agg.getNode(), Agg.getResNo() + i); 4281 4282 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4283 DAG.getVTList(ValValueVTs), Values)); 4284 } 4285 4286 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4287 Value *Op0 = I.getOperand(0); 4288 // Note that the pointer operand may be a vector of pointers. Take the scalar 4289 // element which holds a pointer. 4290 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4291 SDValue N = getValue(Op0); 4292 SDLoc dl = getCurSDLoc(); 4293 auto &TLI = DAG.getTargetLoweringInfo(); 4294 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags(); 4295 4296 // Normalize Vector GEP - all scalar operands should be converted to the 4297 // splat vector. 4298 bool IsVectorGEP = I.getType()->isVectorTy(); 4299 ElementCount VectorElementCount = 4300 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4301 : ElementCount::getFixed(0); 4302 4303 if (IsVectorGEP && !N.getValueType().isVector()) { 4304 LLVMContext &Context = *DAG.getContext(); 4305 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4306 N = DAG.getSplat(VT, dl, N); 4307 } 4308 4309 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4310 GTI != E; ++GTI) { 4311 const Value *Idx = GTI.getOperand(); 4312 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4313 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4314 if (Field) { 4315 // N = N + Offset 4316 uint64_t Offset = 4317 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4318 4319 // In an inbounds GEP with an offset that is nonnegative even when 4320 // interpreted as signed, assume there is no unsigned overflow. 4321 SDNodeFlags Flags; 4322 if (NW.hasNoUnsignedWrap() || 4323 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap())) 4324 Flags |= SDNodeFlags::NoUnsignedWrap; 4325 4326 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4327 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4328 } 4329 } else { 4330 // IdxSize is the width of the arithmetic according to IR semantics. 4331 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4332 // (and fix up the result later). 4333 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4334 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4335 TypeSize ElementSize = 4336 GTI.getSequentialElementStride(DAG.getDataLayout()); 4337 // We intentionally mask away the high bits here; ElementSize may not 4338 // fit in IdxTy. 4339 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(), 4340 /*isSigned=*/false, /*implicitTrunc=*/true); 4341 bool ElementScalable = ElementSize.isScalable(); 4342 4343 // If this is a scalar constant or a splat vector of constants, 4344 // handle it quickly. 4345 const auto *C = dyn_cast<Constant>(Idx); 4346 if (C && isa<VectorType>(C->getType())) 4347 C = C->getSplatValue(); 4348 4349 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4350 if (CI && CI->isZero()) 4351 continue; 4352 if (CI && !ElementScalable) { 4353 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4354 LLVMContext &Context = *DAG.getContext(); 4355 SDValue OffsVal; 4356 if (IsVectorGEP) 4357 OffsVal = DAG.getConstant( 4358 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4359 else 4360 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4361 4362 // In an inbounds GEP with an offset that is nonnegative even when 4363 // interpreted as signed, assume there is no unsigned overflow. 4364 SDNodeFlags Flags; 4365 if (NW.hasNoUnsignedWrap() || 4366 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap())) 4367 Flags.setNoUnsignedWrap(true); 4368 4369 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4370 4371 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4372 continue; 4373 } 4374 4375 // N = N + Idx * ElementMul; 4376 SDValue IdxN = getValue(Idx); 4377 4378 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4379 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4380 VectorElementCount); 4381 IdxN = DAG.getSplat(VT, dl, IdxN); 4382 } 4383 4384 // If the index is smaller or larger than intptr_t, truncate or extend 4385 // it. 4386 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4387 4388 SDNodeFlags ScaleFlags; 4389 // The multiplication of an index by the type size does not wrap the 4390 // pointer index type in a signed sense (mul nsw). 4391 ScaleFlags.setNoSignedWrap(NW.hasNoUnsignedSignedWrap()); 4392 4393 // The multiplication of an index by the type size does not wrap the 4394 // pointer index type in an unsigned sense (mul nuw). 4395 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap()); 4396 4397 if (ElementScalable) { 4398 EVT VScaleTy = N.getValueType().getScalarType(); 4399 SDValue VScale = DAG.getNode( 4400 ISD::VSCALE, dl, VScaleTy, 4401 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4402 if (IsVectorGEP) 4403 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4404 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale, 4405 ScaleFlags); 4406 } else { 4407 // If this is a multiply by a power of two, turn it into a shl 4408 // immediately. This is a very common case. 4409 if (ElementMul != 1) { 4410 if (ElementMul.isPowerOf2()) { 4411 unsigned Amt = ElementMul.logBase2(); 4412 IdxN = DAG.getNode(ISD::SHL, dl, N.getValueType(), IdxN, 4413 DAG.getConstant(Amt, dl, IdxN.getValueType()), 4414 ScaleFlags); 4415 } else { 4416 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4417 IdxN.getValueType()); 4418 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale, 4419 ScaleFlags); 4420 } 4421 } 4422 } 4423 4424 // The successive addition of the current address, truncated to the 4425 // pointer index type and interpreted as an unsigned number, and each 4426 // offset, also interpreted as an unsigned number, does not wrap the 4427 // pointer index type (add nuw). 4428 SDNodeFlags AddFlags; 4429 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap()); 4430 4431 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, IdxN, AddFlags); 4432 } 4433 } 4434 4435 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4436 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4437 if (IsVectorGEP) { 4438 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4439 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4440 } 4441 4442 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4443 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4444 4445 setValue(&I, N); 4446 } 4447 4448 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4449 // If this is a fixed sized alloca in the entry block of the function, 4450 // allocate it statically on the stack. 4451 if (FuncInfo.StaticAllocaMap.count(&I)) 4452 return; // getValue will auto-populate this. 4453 4454 SDLoc dl = getCurSDLoc(); 4455 Type *Ty = I.getAllocatedType(); 4456 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4457 auto &DL = DAG.getDataLayout(); 4458 TypeSize TySize = DL.getTypeAllocSize(Ty); 4459 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4460 4461 SDValue AllocSize = getValue(I.getArraySize()); 4462 4463 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4464 if (AllocSize.getValueType() != IntPtr) 4465 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4466 4467 if (TySize.isScalable()) 4468 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4469 DAG.getVScale(dl, IntPtr, 4470 APInt(IntPtr.getScalarSizeInBits(), 4471 TySize.getKnownMinValue()))); 4472 else { 4473 SDValue TySizeValue = 4474 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4475 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4476 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4477 } 4478 4479 // Handle alignment. If the requested alignment is less than or equal to 4480 // the stack alignment, ignore it. If the size is greater than or equal to 4481 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4482 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4483 if (*Alignment <= StackAlign) 4484 Alignment = std::nullopt; 4485 4486 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4487 // Round the size of the allocation up to the stack alignment size 4488 // by add SA-1 to the size. This doesn't overflow because we're computing 4489 // an address inside an alloca. 4490 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4491 DAG.getConstant(StackAlignMask, dl, IntPtr), 4492 SDNodeFlags::NoUnsignedWrap); 4493 4494 // Mask out the low bits for alignment purposes. 4495 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4496 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr)); 4497 4498 SDValue Ops[] = { 4499 getRoot(), AllocSize, 4500 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4501 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4502 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4503 setValue(&I, DSA); 4504 DAG.setRoot(DSA.getValue(1)); 4505 4506 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4507 } 4508 4509 static const MDNode *getRangeMetadata(const Instruction &I) { 4510 // If !noundef is not present, then !range violation results in a poison 4511 // value rather than immediate undefined behavior. In theory, transferring 4512 // these annotations to SDAG is fine, but in practice there are key SDAG 4513 // transforms that are known not to be poison-safe, such as folding logical 4514 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4515 // also present. 4516 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4517 return nullptr; 4518 return I.getMetadata(LLVMContext::MD_range); 4519 } 4520 4521 static std::optional<ConstantRange> getRange(const Instruction &I) { 4522 if (const auto *CB = dyn_cast<CallBase>(&I)) { 4523 // see comment in getRangeMetadata about this check 4524 if (CB->hasRetAttr(Attribute::NoUndef)) 4525 return CB->getRange(); 4526 } 4527 if (const MDNode *Range = getRangeMetadata(I)) 4528 return getConstantRangeFromMetadata(*Range); 4529 return std::nullopt; 4530 } 4531 4532 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4533 if (I.isAtomic()) 4534 return visitAtomicLoad(I); 4535 4536 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4537 const Value *SV = I.getOperand(0); 4538 if (TLI.supportSwiftError()) { 4539 // Swifterror values can come from either a function parameter with 4540 // swifterror attribute or an alloca with swifterror attribute. 4541 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4542 if (Arg->hasSwiftErrorAttr()) 4543 return visitLoadFromSwiftError(I); 4544 } 4545 4546 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4547 if (Alloca->isSwiftError()) 4548 return visitLoadFromSwiftError(I); 4549 } 4550 } 4551 4552 SDValue Ptr = getValue(SV); 4553 4554 Type *Ty = I.getType(); 4555 SmallVector<EVT, 4> ValueVTs, MemVTs; 4556 SmallVector<TypeSize, 4> Offsets; 4557 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4558 unsigned NumValues = ValueVTs.size(); 4559 if (NumValues == 0) 4560 return; 4561 4562 Align Alignment = I.getAlign(); 4563 AAMDNodes AAInfo = I.getAAMetadata(); 4564 const MDNode *Ranges = getRangeMetadata(I); 4565 bool isVolatile = I.isVolatile(); 4566 MachineMemOperand::Flags MMOFlags = 4567 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4568 4569 SDValue Root; 4570 bool ConstantMemory = false; 4571 if (isVolatile) 4572 // Serialize volatile loads with other side effects. 4573 Root = getRoot(); 4574 else if (NumValues > MaxParallelChains) 4575 Root = getMemoryRoot(); 4576 else if (AA && 4577 AA->pointsToConstantMemory(MemoryLocation( 4578 SV, 4579 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4580 AAInfo))) { 4581 // Do not serialize (non-volatile) loads of constant memory with anything. 4582 Root = DAG.getEntryNode(); 4583 ConstantMemory = true; 4584 MMOFlags |= MachineMemOperand::MOInvariant; 4585 } else { 4586 // Do not serialize non-volatile loads against each other. 4587 Root = DAG.getRoot(); 4588 } 4589 4590 SDLoc dl = getCurSDLoc(); 4591 4592 if (isVolatile) 4593 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4594 4595 SmallVector<SDValue, 4> Values(NumValues); 4596 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4597 4598 unsigned ChainI = 0; 4599 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4600 // Serializing loads here may result in excessive register pressure, and 4601 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4602 // could recover a bit by hoisting nodes upward in the chain by recognizing 4603 // they are side-effect free or do not alias. The optimizer should really 4604 // avoid this case by converting large object/array copies to llvm.memcpy 4605 // (MaxParallelChains should always remain as failsafe). 4606 if (ChainI == MaxParallelChains) { 4607 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4608 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4609 ArrayRef(Chains.data(), ChainI)); 4610 Root = Chain; 4611 ChainI = 0; 4612 } 4613 4614 // TODO: MachinePointerInfo only supports a fixed length offset. 4615 MachinePointerInfo PtrInfo = 4616 !Offsets[i].isScalable() || Offsets[i].isZero() 4617 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4618 : MachinePointerInfo(); 4619 4620 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4621 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4622 MMOFlags, AAInfo, Ranges); 4623 Chains[ChainI] = L.getValue(1); 4624 4625 if (MemVTs[i] != ValueVTs[i]) 4626 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4627 4628 Values[i] = L; 4629 } 4630 4631 if (!ConstantMemory) { 4632 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4633 ArrayRef(Chains.data(), ChainI)); 4634 if (isVolatile) 4635 DAG.setRoot(Chain); 4636 else 4637 PendingLoads.push_back(Chain); 4638 } 4639 4640 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4641 DAG.getVTList(ValueVTs), Values)); 4642 } 4643 4644 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4645 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4646 "call visitStoreToSwiftError when backend supports swifterror"); 4647 4648 SmallVector<EVT, 4> ValueVTs; 4649 SmallVector<uint64_t, 4> Offsets; 4650 const Value *SrcV = I.getOperand(0); 4651 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4652 SrcV->getType(), ValueVTs, &Offsets, 0); 4653 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4654 "expect a single EVT for swifterror"); 4655 4656 SDValue Src = getValue(SrcV); 4657 // Create a virtual register, then update the virtual register. 4658 Register VReg = 4659 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4660 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4661 // Chain can be getRoot or getControlRoot. 4662 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4663 SDValue(Src.getNode(), Src.getResNo())); 4664 DAG.setRoot(CopyNode); 4665 } 4666 4667 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4668 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4669 "call visitLoadFromSwiftError when backend supports swifterror"); 4670 4671 assert(!I.isVolatile() && 4672 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4673 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4674 "Support volatile, non temporal, invariant for load_from_swift_error"); 4675 4676 const Value *SV = I.getOperand(0); 4677 Type *Ty = I.getType(); 4678 assert( 4679 (!AA || 4680 !AA->pointsToConstantMemory(MemoryLocation( 4681 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4682 I.getAAMetadata()))) && 4683 "load_from_swift_error should not be constant memory"); 4684 4685 SmallVector<EVT, 4> ValueVTs; 4686 SmallVector<uint64_t, 4> Offsets; 4687 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4688 ValueVTs, &Offsets, 0); 4689 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4690 "expect a single EVT for swifterror"); 4691 4692 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4693 SDValue L = DAG.getCopyFromReg( 4694 getRoot(), getCurSDLoc(), 4695 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4696 4697 setValue(&I, L); 4698 } 4699 4700 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4701 if (I.isAtomic()) 4702 return visitAtomicStore(I); 4703 4704 const Value *SrcV = I.getOperand(0); 4705 const Value *PtrV = I.getOperand(1); 4706 4707 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4708 if (TLI.supportSwiftError()) { 4709 // Swifterror values can come from either a function parameter with 4710 // swifterror attribute or an alloca with swifterror attribute. 4711 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4712 if (Arg->hasSwiftErrorAttr()) 4713 return visitStoreToSwiftError(I); 4714 } 4715 4716 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4717 if (Alloca->isSwiftError()) 4718 return visitStoreToSwiftError(I); 4719 } 4720 } 4721 4722 SmallVector<EVT, 4> ValueVTs, MemVTs; 4723 SmallVector<TypeSize, 4> Offsets; 4724 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4725 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4726 unsigned NumValues = ValueVTs.size(); 4727 if (NumValues == 0) 4728 return; 4729 4730 // Get the lowered operands. Note that we do this after 4731 // checking if NumResults is zero, because with zero results 4732 // the operands won't have values in the map. 4733 SDValue Src = getValue(SrcV); 4734 SDValue Ptr = getValue(PtrV); 4735 4736 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4737 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4738 SDLoc dl = getCurSDLoc(); 4739 Align Alignment = I.getAlign(); 4740 AAMDNodes AAInfo = I.getAAMetadata(); 4741 4742 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4743 4744 unsigned ChainI = 0; 4745 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4746 // See visitLoad comments. 4747 if (ChainI == MaxParallelChains) { 4748 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4749 ArrayRef(Chains.data(), ChainI)); 4750 Root = Chain; 4751 ChainI = 0; 4752 } 4753 4754 // TODO: MachinePointerInfo only supports a fixed length offset. 4755 MachinePointerInfo PtrInfo = 4756 !Offsets[i].isScalable() || Offsets[i].isZero() 4757 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4758 : MachinePointerInfo(); 4759 4760 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4761 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4762 if (MemVTs[i] != ValueVTs[i]) 4763 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4764 SDValue St = 4765 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4766 Chains[ChainI] = St; 4767 } 4768 4769 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4770 ArrayRef(Chains.data(), ChainI)); 4771 setValue(&I, StoreNode); 4772 DAG.setRoot(StoreNode); 4773 } 4774 4775 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4776 bool IsCompressing) { 4777 SDLoc sdl = getCurSDLoc(); 4778 4779 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4780 Align &Alignment) { 4781 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4782 Src0 = I.getArgOperand(0); 4783 Ptr = I.getArgOperand(1); 4784 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue(); 4785 Mask = I.getArgOperand(3); 4786 }; 4787 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4788 Align &Alignment) { 4789 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4790 Src0 = I.getArgOperand(0); 4791 Ptr = I.getArgOperand(1); 4792 Mask = I.getArgOperand(2); 4793 Alignment = I.getParamAlign(1).valueOrOne(); 4794 }; 4795 4796 Value *PtrOperand, *MaskOperand, *Src0Operand; 4797 Align Alignment; 4798 if (IsCompressing) 4799 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4800 else 4801 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4802 4803 SDValue Ptr = getValue(PtrOperand); 4804 SDValue Src0 = getValue(Src0Operand); 4805 SDValue Mask = getValue(MaskOperand); 4806 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4807 4808 EVT VT = Src0.getValueType(); 4809 4810 auto MMOFlags = MachineMemOperand::MOStore; 4811 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4812 MMOFlags |= MachineMemOperand::MONonTemporal; 4813 4814 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4815 MachinePointerInfo(PtrOperand), MMOFlags, 4816 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4817 4818 const auto &TLI = DAG.getTargetLoweringInfo(); 4819 const auto &TTI = 4820 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 4821 SDValue StoreNode = 4822 !IsCompressing && 4823 TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType()) 4824 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0, 4825 Mask) 4826 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, 4827 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false, 4828 IsCompressing); 4829 DAG.setRoot(StoreNode); 4830 setValue(&I, StoreNode); 4831 } 4832 4833 // Get a uniform base for the Gather/Scatter intrinsic. 4834 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4835 // We try to represent it as a base pointer + vector of indices. 4836 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4837 // The first operand of the GEP may be a single pointer or a vector of pointers 4838 // Example: 4839 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4840 // or 4841 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4842 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4843 // 4844 // When the first GEP operand is a single pointer - it is the uniform base we 4845 // are looking for. If first operand of the GEP is a splat vector - we 4846 // extract the splat value and use it as a uniform base. 4847 // In all other cases the function returns 'false'. 4848 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4849 ISD::MemIndexType &IndexType, SDValue &Scale, 4850 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4851 uint64_t ElemSize) { 4852 SelectionDAG& DAG = SDB->DAG; 4853 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4854 const DataLayout &DL = DAG.getDataLayout(); 4855 4856 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4857 4858 // Handle splat constant pointer. 4859 if (auto *C = dyn_cast<Constant>(Ptr)) { 4860 C = C->getSplatValue(); 4861 if (!C) 4862 return false; 4863 4864 Base = SDB->getValue(C); 4865 4866 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4867 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4868 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4869 IndexType = ISD::SIGNED_SCALED; 4870 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4871 return true; 4872 } 4873 4874 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4875 if (!GEP || GEP->getParent() != CurBB) 4876 return false; 4877 4878 if (GEP->getNumOperands() != 2) 4879 return false; 4880 4881 const Value *BasePtr = GEP->getPointerOperand(); 4882 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4883 4884 // Make sure the base is scalar and the index is a vector. 4885 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4886 return false; 4887 4888 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4889 if (ScaleVal.isScalable()) 4890 return false; 4891 4892 // Target may not support the required addressing mode. 4893 if (ScaleVal != 1 && 4894 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4895 return false; 4896 4897 Base = SDB->getValue(BasePtr); 4898 Index = SDB->getValue(IndexVal); 4899 IndexType = ISD::SIGNED_SCALED; 4900 4901 Scale = 4902 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4903 return true; 4904 } 4905 4906 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4907 SDLoc sdl = getCurSDLoc(); 4908 4909 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4910 const Value *Ptr = I.getArgOperand(1); 4911 SDValue Src0 = getValue(I.getArgOperand(0)); 4912 SDValue Mask = getValue(I.getArgOperand(3)); 4913 EVT VT = Src0.getValueType(); 4914 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4915 ->getMaybeAlignValue() 4916 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4917 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4918 4919 SDValue Base; 4920 SDValue Index; 4921 ISD::MemIndexType IndexType; 4922 SDValue Scale; 4923 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4924 I.getParent(), VT.getScalarStoreSize()); 4925 4926 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4927 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4928 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4929 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4930 if (!UniformBase) { 4931 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4932 Index = getValue(Ptr); 4933 IndexType = ISD::SIGNED_SCALED; 4934 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4935 } 4936 4937 EVT IdxVT = Index.getValueType(); 4938 EVT EltTy = IdxVT.getVectorElementType(); 4939 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4940 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4941 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4942 } 4943 4944 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4945 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4946 Ops, MMO, IndexType, false); 4947 DAG.setRoot(Scatter); 4948 setValue(&I, Scatter); 4949 } 4950 4951 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4952 SDLoc sdl = getCurSDLoc(); 4953 4954 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4955 Align &Alignment) { 4956 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4957 Ptr = I.getArgOperand(0); 4958 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue(); 4959 Mask = I.getArgOperand(2); 4960 Src0 = I.getArgOperand(3); 4961 }; 4962 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4963 Align &Alignment) { 4964 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4965 Ptr = I.getArgOperand(0); 4966 Alignment = I.getParamAlign(0).valueOrOne(); 4967 Mask = I.getArgOperand(1); 4968 Src0 = I.getArgOperand(2); 4969 }; 4970 4971 Value *PtrOperand, *MaskOperand, *Src0Operand; 4972 Align Alignment; 4973 if (IsExpanding) 4974 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4975 else 4976 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4977 4978 SDValue Ptr = getValue(PtrOperand); 4979 SDValue Src0 = getValue(Src0Operand); 4980 SDValue Mask = getValue(MaskOperand); 4981 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4982 4983 EVT VT = Src0.getValueType(); 4984 AAMDNodes AAInfo = I.getAAMetadata(); 4985 const MDNode *Ranges = getRangeMetadata(I); 4986 4987 // Do not serialize masked loads of constant memory with anything. 4988 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4989 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4990 4991 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4992 4993 auto MMOFlags = MachineMemOperand::MOLoad; 4994 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4995 MMOFlags |= MachineMemOperand::MONonTemporal; 4996 4997 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4998 MachinePointerInfo(PtrOperand), MMOFlags, 4999 LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges); 5000 5001 const auto &TLI = DAG.getTargetLoweringInfo(); 5002 const auto &TTI = 5003 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 5004 // The Load/Res may point to different values and both of them are output 5005 // variables. 5006 SDValue Load; 5007 SDValue Res; 5008 if (!IsExpanding && 5009 TTI.hasConditionalLoadStoreForType(Src0Operand->getType())) 5010 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask); 5011 else 5012 Res = Load = 5013 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 5014 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 5015 if (AddToChain) 5016 PendingLoads.push_back(Load.getValue(1)); 5017 setValue(&I, Res); 5018 } 5019 5020 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 5021 SDLoc sdl = getCurSDLoc(); 5022 5023 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 5024 const Value *Ptr = I.getArgOperand(0); 5025 SDValue Src0 = getValue(I.getArgOperand(3)); 5026 SDValue Mask = getValue(I.getArgOperand(2)); 5027 5028 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5029 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5030 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 5031 ->getMaybeAlignValue() 5032 .value_or(DAG.getEVTAlign(VT.getScalarType())); 5033 5034 const MDNode *Ranges = getRangeMetadata(I); 5035 5036 SDValue Root = DAG.getRoot(); 5037 SDValue Base; 5038 SDValue Index; 5039 ISD::MemIndexType IndexType; 5040 SDValue Scale; 5041 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 5042 I.getParent(), VT.getScalarStoreSize()); 5043 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 5044 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5045 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 5046 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(), 5047 Ranges); 5048 5049 if (!UniformBase) { 5050 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 5051 Index = getValue(Ptr); 5052 IndexType = ISD::SIGNED_SCALED; 5053 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 5054 } 5055 5056 EVT IdxVT = Index.getValueType(); 5057 EVT EltTy = IdxVT.getVectorElementType(); 5058 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 5059 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 5060 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 5061 } 5062 5063 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 5064 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 5065 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 5066 5067 PendingLoads.push_back(Gather.getValue(1)); 5068 setValue(&I, Gather); 5069 } 5070 5071 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 5072 SDLoc dl = getCurSDLoc(); 5073 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 5074 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 5075 SyncScope::ID SSID = I.getSyncScopeID(); 5076 5077 SDValue InChain = getRoot(); 5078 5079 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 5080 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 5081 5082 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5083 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5084 5085 MachineFunction &MF = DAG.getMachineFunction(); 5086 MachineMemOperand *MMO = MF.getMachineMemOperand( 5087 MachinePointerInfo(I.getPointerOperand()), Flags, 5088 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5089 AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering); 5090 5091 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 5092 dl, MemVT, VTs, InChain, 5093 getValue(I.getPointerOperand()), 5094 getValue(I.getCompareOperand()), 5095 getValue(I.getNewValOperand()), MMO); 5096 5097 SDValue OutChain = L.getValue(2); 5098 5099 setValue(&I, L); 5100 DAG.setRoot(OutChain); 5101 } 5102 5103 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 5104 SDLoc dl = getCurSDLoc(); 5105 ISD::NodeType NT; 5106 switch (I.getOperation()) { 5107 default: llvm_unreachable("Unknown atomicrmw operation"); 5108 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 5109 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 5110 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 5111 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 5112 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 5113 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 5114 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 5115 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 5116 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 5117 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 5118 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 5119 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 5120 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 5121 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 5122 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 5123 case AtomicRMWInst::UIncWrap: 5124 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 5125 break; 5126 case AtomicRMWInst::UDecWrap: 5127 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 5128 break; 5129 case AtomicRMWInst::USubCond: 5130 NT = ISD::ATOMIC_LOAD_USUB_COND; 5131 break; 5132 case AtomicRMWInst::USubSat: 5133 NT = ISD::ATOMIC_LOAD_USUB_SAT; 5134 break; 5135 } 5136 AtomicOrdering Ordering = I.getOrdering(); 5137 SyncScope::ID SSID = I.getSyncScopeID(); 5138 5139 SDValue InChain = getRoot(); 5140 5141 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 5142 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5143 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5144 5145 MachineFunction &MF = DAG.getMachineFunction(); 5146 MachineMemOperand *MMO = MF.getMachineMemOperand( 5147 MachinePointerInfo(I.getPointerOperand()), Flags, 5148 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5149 AAMDNodes(), nullptr, SSID, Ordering); 5150 5151 SDValue L = 5152 DAG.getAtomic(NT, dl, MemVT, InChain, 5153 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 5154 MMO); 5155 5156 SDValue OutChain = L.getValue(1); 5157 5158 setValue(&I, L); 5159 DAG.setRoot(OutChain); 5160 } 5161 5162 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 5163 SDLoc dl = getCurSDLoc(); 5164 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5165 SDValue Ops[3]; 5166 Ops[0] = getRoot(); 5167 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 5168 TLI.getFenceOperandTy(DAG.getDataLayout())); 5169 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 5170 TLI.getFenceOperandTy(DAG.getDataLayout())); 5171 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 5172 setValue(&I, N); 5173 DAG.setRoot(N); 5174 } 5175 5176 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 5177 SDLoc dl = getCurSDLoc(); 5178 AtomicOrdering Order = I.getOrdering(); 5179 SyncScope::ID SSID = I.getSyncScopeID(); 5180 5181 SDValue InChain = getRoot(); 5182 5183 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5184 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5185 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 5186 5187 if (!TLI.supportsUnalignedAtomics() && 5188 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5189 report_fatal_error("Cannot generate unaligned atomic load"); 5190 5191 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 5192 5193 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5194 MachinePointerInfo(I.getPointerOperand()), Flags, 5195 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5196 nullptr, SSID, Order); 5197 5198 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 5199 5200 SDValue Ptr = getValue(I.getPointerOperand()); 5201 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 5202 Ptr, MMO); 5203 5204 SDValue OutChain = L.getValue(1); 5205 if (MemVT != VT) 5206 L = DAG.getPtrExtOrTrunc(L, dl, VT); 5207 5208 setValue(&I, L); 5209 DAG.setRoot(OutChain); 5210 } 5211 5212 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 5213 SDLoc dl = getCurSDLoc(); 5214 5215 AtomicOrdering Ordering = I.getOrdering(); 5216 SyncScope::ID SSID = I.getSyncScopeID(); 5217 5218 SDValue InChain = getRoot(); 5219 5220 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5221 EVT MemVT = 5222 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 5223 5224 if (!TLI.supportsUnalignedAtomics() && 5225 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5226 report_fatal_error("Cannot generate unaligned atomic store"); 5227 5228 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 5229 5230 MachineFunction &MF = DAG.getMachineFunction(); 5231 MachineMemOperand *MMO = MF.getMachineMemOperand( 5232 MachinePointerInfo(I.getPointerOperand()), Flags, 5233 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5234 nullptr, SSID, Ordering); 5235 5236 SDValue Val = getValue(I.getValueOperand()); 5237 if (Val.getValueType() != MemVT) 5238 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 5239 SDValue Ptr = getValue(I.getPointerOperand()); 5240 5241 SDValue OutChain = 5242 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 5243 5244 setValue(&I, OutChain); 5245 DAG.setRoot(OutChain); 5246 } 5247 5248 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 5249 /// node. 5250 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5251 unsigned Intrinsic) { 5252 // Ignore the callsite's attributes. A specific call site may be marked with 5253 // readnone, but the lowering code will expect the chain based on the 5254 // definition. 5255 const Function *F = I.getCalledFunction(); 5256 bool HasChain = !F->doesNotAccessMemory(); 5257 bool OnlyLoad = 5258 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow(); 5259 5260 // Build the operand list. 5261 SmallVector<SDValue, 8> Ops; 5262 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5263 if (OnlyLoad) { 5264 // We don't need to serialize loads against other loads. 5265 Ops.push_back(DAG.getRoot()); 5266 } else { 5267 Ops.push_back(getRoot()); 5268 } 5269 } 5270 5271 // Info is set by getTgtMemIntrinsic 5272 TargetLowering::IntrinsicInfo Info; 5273 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5274 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5275 DAG.getMachineFunction(), 5276 Intrinsic); 5277 5278 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5279 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5280 Info.opc == ISD::INTRINSIC_W_CHAIN) 5281 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5282 TLI.getPointerTy(DAG.getDataLayout()))); 5283 5284 // Add all operands of the call to the operand list. 5285 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5286 const Value *Arg = I.getArgOperand(i); 5287 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5288 Ops.push_back(getValue(Arg)); 5289 continue; 5290 } 5291 5292 // Use TargetConstant instead of a regular constant for immarg. 5293 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5294 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5295 assert(CI->getBitWidth() <= 64 && 5296 "large intrinsic immediates not handled"); 5297 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5298 } else { 5299 Ops.push_back( 5300 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5301 } 5302 } 5303 5304 SmallVector<EVT, 4> ValueVTs; 5305 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5306 5307 if (HasChain) 5308 ValueVTs.push_back(MVT::Other); 5309 5310 SDVTList VTs = DAG.getVTList(ValueVTs); 5311 5312 // Propagate fast-math-flags from IR to node(s). 5313 SDNodeFlags Flags; 5314 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5315 Flags.copyFMF(*FPMO); 5316 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5317 5318 // Create the node. 5319 SDValue Result; 5320 5321 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) { 5322 auto *Token = Bundle->Inputs[0].get(); 5323 SDValue ConvControlToken = getValue(Token); 5324 assert(Ops.back().getValueType() != MVT::Glue && 5325 "Did not expected another glue node here."); 5326 ConvControlToken = 5327 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken); 5328 Ops.push_back(ConvControlToken); 5329 } 5330 5331 // In some cases, custom collection of operands from CallInst I may be needed. 5332 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5333 if (IsTgtIntrinsic) { 5334 // This is target intrinsic that touches memory 5335 // 5336 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5337 // didn't yield anything useful. 5338 MachinePointerInfo MPI; 5339 if (Info.ptrVal) 5340 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5341 else if (Info.fallbackAddressSpace) 5342 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5343 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5344 Info.memVT, MPI, Info.align, Info.flags, 5345 Info.size, I.getAAMetadata()); 5346 } else if (!HasChain) { 5347 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5348 } else if (!I.getType()->isVoidTy()) { 5349 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5350 } else { 5351 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5352 } 5353 5354 if (HasChain) { 5355 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5356 if (OnlyLoad) 5357 PendingLoads.push_back(Chain); 5358 else 5359 DAG.setRoot(Chain); 5360 } 5361 5362 if (!I.getType()->isVoidTy()) { 5363 if (!isa<VectorType>(I.getType())) 5364 Result = lowerRangeToAssertZExt(DAG, I, Result); 5365 5366 MaybeAlign Alignment = I.getRetAlign(); 5367 5368 // Insert `assertalign` node if there's an alignment. 5369 if (InsertAssertAlign && Alignment) { 5370 Result = 5371 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5372 } 5373 } 5374 5375 setValue(&I, Result); 5376 } 5377 5378 /// GetSignificand - Get the significand and build it into a floating-point 5379 /// number with exponent of 1: 5380 /// 5381 /// Op = (Op & 0x007fffff) | 0x3f800000; 5382 /// 5383 /// where Op is the hexadecimal representation of floating point value. 5384 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5385 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5386 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5387 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5388 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5389 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5390 } 5391 5392 /// GetExponent - Get the exponent: 5393 /// 5394 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5395 /// 5396 /// where Op is the hexadecimal representation of floating point value. 5397 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5398 const TargetLowering &TLI, const SDLoc &dl) { 5399 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5400 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5401 SDValue t1 = DAG.getNode( 5402 ISD::SRL, dl, MVT::i32, t0, 5403 DAG.getConstant(23, dl, 5404 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5405 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5406 DAG.getConstant(127, dl, MVT::i32)); 5407 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5408 } 5409 5410 /// getF32Constant - Get 32-bit floating point constant. 5411 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5412 const SDLoc &dl) { 5413 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5414 MVT::f32); 5415 } 5416 5417 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5418 SelectionDAG &DAG) { 5419 // TODO: What fast-math-flags should be set on the floating-point nodes? 5420 5421 // IntegerPartOfX = ((int32_t)(t0); 5422 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5423 5424 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5425 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5426 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5427 5428 // IntegerPartOfX <<= 23; 5429 IntegerPartOfX = 5430 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5431 DAG.getConstant(23, dl, 5432 DAG.getTargetLoweringInfo().getShiftAmountTy( 5433 MVT::i32, DAG.getDataLayout()))); 5434 5435 SDValue TwoToFractionalPartOfX; 5436 if (LimitFloatPrecision <= 6) { 5437 // For floating-point precision of 6: 5438 // 5439 // TwoToFractionalPartOfX = 5440 // 0.997535578f + 5441 // (0.735607626f + 0.252464424f * x) * x; 5442 // 5443 // error 0.0144103317, which is 6 bits 5444 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5445 getF32Constant(DAG, 0x3e814304, dl)); 5446 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5447 getF32Constant(DAG, 0x3f3c50c8, dl)); 5448 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5449 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5450 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5451 } else if (LimitFloatPrecision <= 12) { 5452 // For floating-point precision of 12: 5453 // 5454 // TwoToFractionalPartOfX = 5455 // 0.999892986f + 5456 // (0.696457318f + 5457 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5458 // 5459 // error 0.000107046256, which is 13 to 14 bits 5460 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5461 getF32Constant(DAG, 0x3da235e3, dl)); 5462 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5463 getF32Constant(DAG, 0x3e65b8f3, dl)); 5464 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5465 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5466 getF32Constant(DAG, 0x3f324b07, dl)); 5467 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5468 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5469 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5470 } else { // LimitFloatPrecision <= 18 5471 // For floating-point precision of 18: 5472 // 5473 // TwoToFractionalPartOfX = 5474 // 0.999999982f + 5475 // (0.693148872f + 5476 // (0.240227044f + 5477 // (0.554906021e-1f + 5478 // (0.961591928e-2f + 5479 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5480 // error 2.47208000*10^(-7), which is better than 18 bits 5481 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5482 getF32Constant(DAG, 0x3924b03e, dl)); 5483 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5484 getF32Constant(DAG, 0x3ab24b87, dl)); 5485 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5486 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5487 getF32Constant(DAG, 0x3c1d8c17, dl)); 5488 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5489 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5490 getF32Constant(DAG, 0x3d634a1d, dl)); 5491 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5492 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5493 getF32Constant(DAG, 0x3e75fe14, dl)); 5494 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5495 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5496 getF32Constant(DAG, 0x3f317234, dl)); 5497 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5498 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5499 getF32Constant(DAG, 0x3f800000, dl)); 5500 } 5501 5502 // Add the exponent into the result in integer domain. 5503 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5504 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5505 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5506 } 5507 5508 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5509 /// limited-precision mode. 5510 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5511 const TargetLowering &TLI, SDNodeFlags Flags) { 5512 if (Op.getValueType() == MVT::f32 && 5513 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5514 5515 // Put the exponent in the right bit position for later addition to the 5516 // final result: 5517 // 5518 // t0 = Op * log2(e) 5519 5520 // TODO: What fast-math-flags should be set here? 5521 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5522 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5523 return getLimitedPrecisionExp2(t0, dl, DAG); 5524 } 5525 5526 // No special expansion. 5527 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5528 } 5529 5530 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5531 /// limited-precision mode. 5532 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5533 const TargetLowering &TLI, SDNodeFlags Flags) { 5534 // TODO: What fast-math-flags should be set on the floating-point nodes? 5535 5536 if (Op.getValueType() == MVT::f32 && 5537 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5538 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5539 5540 // Scale the exponent by log(2). 5541 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5542 SDValue LogOfExponent = 5543 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5544 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5545 5546 // Get the significand and build it into a floating-point number with 5547 // exponent of 1. 5548 SDValue X = GetSignificand(DAG, Op1, dl); 5549 5550 SDValue LogOfMantissa; 5551 if (LimitFloatPrecision <= 6) { 5552 // For floating-point precision of 6: 5553 // 5554 // LogofMantissa = 5555 // -1.1609546f + 5556 // (1.4034025f - 0.23903021f * x) * x; 5557 // 5558 // error 0.0034276066, which is better than 8 bits 5559 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5560 getF32Constant(DAG, 0xbe74c456, dl)); 5561 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5562 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5563 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5564 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5565 getF32Constant(DAG, 0x3f949a29, dl)); 5566 } else if (LimitFloatPrecision <= 12) { 5567 // For floating-point precision of 12: 5568 // 5569 // LogOfMantissa = 5570 // -1.7417939f + 5571 // (2.8212026f + 5572 // (-1.4699568f + 5573 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5574 // 5575 // error 0.000061011436, which is 14 bits 5576 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5577 getF32Constant(DAG, 0xbd67b6d6, dl)); 5578 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5579 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5580 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5581 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5582 getF32Constant(DAG, 0x3fbc278b, dl)); 5583 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5584 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5585 getF32Constant(DAG, 0x40348e95, dl)); 5586 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5587 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5588 getF32Constant(DAG, 0x3fdef31a, dl)); 5589 } else { // LimitFloatPrecision <= 18 5590 // For floating-point precision of 18: 5591 // 5592 // LogOfMantissa = 5593 // -2.1072184f + 5594 // (4.2372794f + 5595 // (-3.7029485f + 5596 // (2.2781945f + 5597 // (-0.87823314f + 5598 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5599 // 5600 // error 0.0000023660568, which is better than 18 bits 5601 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5602 getF32Constant(DAG, 0xbc91e5ac, dl)); 5603 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5604 getF32Constant(DAG, 0x3e4350aa, dl)); 5605 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5606 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5607 getF32Constant(DAG, 0x3f60d3e3, dl)); 5608 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5609 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5610 getF32Constant(DAG, 0x4011cdf0, dl)); 5611 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5612 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5613 getF32Constant(DAG, 0x406cfd1c, dl)); 5614 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5615 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5616 getF32Constant(DAG, 0x408797cb, dl)); 5617 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5618 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5619 getF32Constant(DAG, 0x4006dcab, dl)); 5620 } 5621 5622 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5623 } 5624 5625 // No special expansion. 5626 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5627 } 5628 5629 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5630 /// limited-precision mode. 5631 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5632 const TargetLowering &TLI, SDNodeFlags Flags) { 5633 // TODO: What fast-math-flags should be set on the floating-point nodes? 5634 5635 if (Op.getValueType() == MVT::f32 && 5636 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5637 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5638 5639 // Get the exponent. 5640 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5641 5642 // Get the significand and build it into a floating-point number with 5643 // exponent of 1. 5644 SDValue X = GetSignificand(DAG, Op1, dl); 5645 5646 // Different possible minimax approximations of significand in 5647 // floating-point for various degrees of accuracy over [1,2]. 5648 SDValue Log2ofMantissa; 5649 if (LimitFloatPrecision <= 6) { 5650 // For floating-point precision of 6: 5651 // 5652 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5653 // 5654 // error 0.0049451742, which is more than 7 bits 5655 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5656 getF32Constant(DAG, 0xbeb08fe0, dl)); 5657 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5658 getF32Constant(DAG, 0x40019463, dl)); 5659 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5660 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5661 getF32Constant(DAG, 0x3fd6633d, dl)); 5662 } else if (LimitFloatPrecision <= 12) { 5663 // For floating-point precision of 12: 5664 // 5665 // Log2ofMantissa = 5666 // -2.51285454f + 5667 // (4.07009056f + 5668 // (-2.12067489f + 5669 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5670 // 5671 // error 0.0000876136000, which is better than 13 bits 5672 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5673 getF32Constant(DAG, 0xbda7262e, dl)); 5674 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5675 getF32Constant(DAG, 0x3f25280b, dl)); 5676 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5677 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5678 getF32Constant(DAG, 0x4007b923, dl)); 5679 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5680 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5681 getF32Constant(DAG, 0x40823e2f, dl)); 5682 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5683 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5684 getF32Constant(DAG, 0x4020d29c, dl)); 5685 } else { // LimitFloatPrecision <= 18 5686 // For floating-point precision of 18: 5687 // 5688 // Log2ofMantissa = 5689 // -3.0400495f + 5690 // (6.1129976f + 5691 // (-5.3420409f + 5692 // (3.2865683f + 5693 // (-1.2669343f + 5694 // (0.27515199f - 5695 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5696 // 5697 // error 0.0000018516, which is better than 18 bits 5698 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5699 getF32Constant(DAG, 0xbcd2769e, dl)); 5700 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5701 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5702 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5703 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5704 getF32Constant(DAG, 0x3fa22ae7, dl)); 5705 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5706 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5707 getF32Constant(DAG, 0x40525723, dl)); 5708 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5709 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5710 getF32Constant(DAG, 0x40aaf200, dl)); 5711 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5712 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5713 getF32Constant(DAG, 0x40c39dad, dl)); 5714 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5715 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5716 getF32Constant(DAG, 0x4042902c, dl)); 5717 } 5718 5719 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5720 } 5721 5722 // No special expansion. 5723 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5724 } 5725 5726 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5727 /// limited-precision mode. 5728 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5729 const TargetLowering &TLI, SDNodeFlags Flags) { 5730 // TODO: What fast-math-flags should be set on the floating-point nodes? 5731 5732 if (Op.getValueType() == MVT::f32 && 5733 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5734 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5735 5736 // Scale the exponent by log10(2) [0.30102999f]. 5737 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5738 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5739 getF32Constant(DAG, 0x3e9a209a, dl)); 5740 5741 // Get the significand and build it into a floating-point number with 5742 // exponent of 1. 5743 SDValue X = GetSignificand(DAG, Op1, dl); 5744 5745 SDValue Log10ofMantissa; 5746 if (LimitFloatPrecision <= 6) { 5747 // For floating-point precision of 6: 5748 // 5749 // Log10ofMantissa = 5750 // -0.50419619f + 5751 // (0.60948995f - 0.10380950f * x) * x; 5752 // 5753 // error 0.0014886165, which is 6 bits 5754 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5755 getF32Constant(DAG, 0xbdd49a13, dl)); 5756 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5757 getF32Constant(DAG, 0x3f1c0789, dl)); 5758 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5759 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5760 getF32Constant(DAG, 0x3f011300, dl)); 5761 } else if (LimitFloatPrecision <= 12) { 5762 // For floating-point precision of 12: 5763 // 5764 // Log10ofMantissa = 5765 // -0.64831180f + 5766 // (0.91751397f + 5767 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5768 // 5769 // error 0.00019228036, which is better than 12 bits 5770 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5771 getF32Constant(DAG, 0x3d431f31, dl)); 5772 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5773 getF32Constant(DAG, 0x3ea21fb2, dl)); 5774 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5775 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5776 getF32Constant(DAG, 0x3f6ae232, dl)); 5777 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5778 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5779 getF32Constant(DAG, 0x3f25f7c3, dl)); 5780 } else { // LimitFloatPrecision <= 18 5781 // For floating-point precision of 18: 5782 // 5783 // Log10ofMantissa = 5784 // -0.84299375f + 5785 // (1.5327582f + 5786 // (-1.0688956f + 5787 // (0.49102474f + 5788 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5789 // 5790 // error 0.0000037995730, which is better than 18 bits 5791 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5792 getF32Constant(DAG, 0x3c5d51ce, dl)); 5793 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5794 getF32Constant(DAG, 0x3e00685a, dl)); 5795 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5796 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5797 getF32Constant(DAG, 0x3efb6798, dl)); 5798 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5799 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5800 getF32Constant(DAG, 0x3f88d192, dl)); 5801 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5802 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5803 getF32Constant(DAG, 0x3fc4316c, dl)); 5804 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5805 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5806 getF32Constant(DAG, 0x3f57ce70, dl)); 5807 } 5808 5809 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5810 } 5811 5812 // No special expansion. 5813 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5814 } 5815 5816 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5817 /// limited-precision mode. 5818 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5819 const TargetLowering &TLI, SDNodeFlags Flags) { 5820 if (Op.getValueType() == MVT::f32 && 5821 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5822 return getLimitedPrecisionExp2(Op, dl, DAG); 5823 5824 // No special expansion. 5825 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5826 } 5827 5828 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5829 /// limited-precision mode with x == 10.0f. 5830 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5831 SelectionDAG &DAG, const TargetLowering &TLI, 5832 SDNodeFlags Flags) { 5833 bool IsExp10 = false; 5834 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5835 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5836 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5837 APFloat Ten(10.0f); 5838 IsExp10 = LHSC->isExactlyValue(Ten); 5839 } 5840 } 5841 5842 // TODO: What fast-math-flags should be set on the FMUL node? 5843 if (IsExp10) { 5844 // Put the exponent in the right bit position for later addition to the 5845 // final result: 5846 // 5847 // #define LOG2OF10 3.3219281f 5848 // t0 = Op * LOG2OF10; 5849 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5850 getF32Constant(DAG, 0x40549a78, dl)); 5851 return getLimitedPrecisionExp2(t0, dl, DAG); 5852 } 5853 5854 // No special expansion. 5855 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5856 } 5857 5858 /// ExpandPowI - Expand a llvm.powi intrinsic. 5859 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5860 SelectionDAG &DAG) { 5861 // If RHS is a constant, we can expand this out to a multiplication tree if 5862 // it's beneficial on the target, otherwise we end up lowering to a call to 5863 // __powidf2 (for example). 5864 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5865 unsigned Val = RHSC->getSExtValue(); 5866 5867 // powi(x, 0) -> 1.0 5868 if (Val == 0) 5869 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5870 5871 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5872 Val, DAG.shouldOptForSize())) { 5873 // Get the exponent as a positive value. 5874 if ((int)Val < 0) 5875 Val = -Val; 5876 // We use the simple binary decomposition method to generate the multiply 5877 // sequence. There are more optimal ways to do this (for example, 5878 // powi(x,15) generates one more multiply than it should), but this has 5879 // the benefit of being both really simple and much better than a libcall. 5880 SDValue Res; // Logically starts equal to 1.0 5881 SDValue CurSquare = LHS; 5882 // TODO: Intrinsics should have fast-math-flags that propagate to these 5883 // nodes. 5884 while (Val) { 5885 if (Val & 1) { 5886 if (Res.getNode()) 5887 Res = 5888 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5889 else 5890 Res = CurSquare; // 1.0*CurSquare. 5891 } 5892 5893 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5894 CurSquare, CurSquare); 5895 Val >>= 1; 5896 } 5897 5898 // If the original was negative, invert the result, producing 1/(x*x*x). 5899 if (RHSC->getSExtValue() < 0) 5900 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5901 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5902 return Res; 5903 } 5904 } 5905 5906 // Otherwise, expand to a libcall. 5907 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5908 } 5909 5910 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5911 SDValue LHS, SDValue RHS, SDValue Scale, 5912 SelectionDAG &DAG, const TargetLowering &TLI) { 5913 EVT VT = LHS.getValueType(); 5914 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5915 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5916 LLVMContext &Ctx = *DAG.getContext(); 5917 5918 // If the type is legal but the operation isn't, this node might survive all 5919 // the way to operation legalization. If we end up there and we do not have 5920 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5921 // node. 5922 5923 // Coax the legalizer into expanding the node during type legalization instead 5924 // by bumping the size by one bit. This will force it to Promote, enabling the 5925 // early expansion and avoiding the need to expand later. 5926 5927 // We don't have to do this if Scale is 0; that can always be expanded, unless 5928 // it's a saturating signed operation. Those can experience true integer 5929 // division overflow, a case which we must avoid. 5930 5931 // FIXME: We wouldn't have to do this (or any of the early 5932 // expansion/promotion) if it was possible to expand a libcall of an 5933 // illegal type during operation legalization. But it's not, so things 5934 // get a bit hacky. 5935 unsigned ScaleInt = Scale->getAsZExtVal(); 5936 if ((ScaleInt > 0 || (Saturating && Signed)) && 5937 (TLI.isTypeLegal(VT) || 5938 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5939 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5940 Opcode, VT, ScaleInt); 5941 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5942 EVT PromVT; 5943 if (VT.isScalarInteger()) 5944 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5945 else if (VT.isVector()) { 5946 PromVT = VT.getVectorElementType(); 5947 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5948 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5949 } else 5950 llvm_unreachable("Wrong VT for DIVFIX?"); 5951 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5952 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5953 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5954 // For saturating operations, we need to shift up the LHS to get the 5955 // proper saturation width, and then shift down again afterwards. 5956 if (Saturating) 5957 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5958 DAG.getConstant(1, DL, ShiftTy)); 5959 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5960 if (Saturating) 5961 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5962 DAG.getConstant(1, DL, ShiftTy)); 5963 return DAG.getZExtOrTrunc(Res, DL, VT); 5964 } 5965 } 5966 5967 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5968 } 5969 5970 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5971 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5972 static void 5973 getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs, 5974 const SDValue &N) { 5975 switch (N.getOpcode()) { 5976 case ISD::CopyFromReg: { 5977 SDValue Op = N.getOperand(1); 5978 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5979 Op.getValueType().getSizeInBits()); 5980 return; 5981 } 5982 case ISD::BITCAST: 5983 case ISD::AssertZext: 5984 case ISD::AssertSext: 5985 case ISD::TRUNCATE: 5986 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5987 return; 5988 case ISD::BUILD_PAIR: 5989 case ISD::BUILD_VECTOR: 5990 case ISD::CONCAT_VECTORS: 5991 for (SDValue Op : N->op_values()) 5992 getUnderlyingArgRegs(Regs, Op); 5993 return; 5994 default: 5995 return; 5996 } 5997 } 5998 5999 /// If the DbgValueInst is a dbg_value of a function argument, create the 6000 /// corresponding DBG_VALUE machine instruction for it now. At the end of 6001 /// instruction selection, they will be inserted to the entry BB. 6002 /// We don't currently support this for variadic dbg_values, as they shouldn't 6003 /// appear for function arguments or in the prologue. 6004 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 6005 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 6006 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 6007 const Argument *Arg = dyn_cast<Argument>(V); 6008 if (!Arg) 6009 return false; 6010 6011 MachineFunction &MF = DAG.getMachineFunction(); 6012 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6013 6014 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 6015 // we've been asked to pursue. 6016 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 6017 bool Indirect) { 6018 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 6019 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 6020 // pointing at the VReg, which will be patched up later. 6021 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 6022 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 6023 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 6024 /* isKill */ false, /* isDead */ false, 6025 /* isUndef */ false, /* isEarlyClobber */ false, 6026 /* SubReg */ 0, /* isDebug */ true)}); 6027 6028 auto *NewDIExpr = FragExpr; 6029 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 6030 // the DIExpression. 6031 if (Indirect) 6032 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 6033 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 6034 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 6035 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 6036 } else { 6037 // Create a completely standard DBG_VALUE. 6038 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 6039 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 6040 } 6041 }; 6042 6043 if (Kind == FuncArgumentDbgValueKind::Value) { 6044 // ArgDbgValues are hoisted to the beginning of the entry block. So we 6045 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 6046 // the entry block. 6047 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 6048 if (!IsInEntryBlock) 6049 return false; 6050 6051 // ArgDbgValues are hoisted to the beginning of the entry block. So we 6052 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 6053 // variable that also is a param. 6054 // 6055 // Although, if we are at the top of the entry block already, we can still 6056 // emit using ArgDbgValue. This might catch some situations when the 6057 // dbg.value refers to an argument that isn't used in the entry block, so 6058 // any CopyToReg node would be optimized out and the only way to express 6059 // this DBG_VALUE is by using the physical reg (or FI) as done in this 6060 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 6061 // we should only emit as ArgDbgValue if the Variable is an argument to the 6062 // current function, and the dbg.value intrinsic is found in the entry 6063 // block. 6064 bool VariableIsFunctionInputArg = Variable->isParameter() && 6065 !DL->getInlinedAt(); 6066 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 6067 if (!IsInPrologue && !VariableIsFunctionInputArg) 6068 return false; 6069 6070 // Here we assume that a function argument on IR level only can be used to 6071 // describe one input parameter on source level. If we for example have 6072 // source code like this 6073 // 6074 // struct A { long x, y; }; 6075 // void foo(struct A a, long b) { 6076 // ... 6077 // b = a.x; 6078 // ... 6079 // } 6080 // 6081 // and IR like this 6082 // 6083 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 6084 // entry: 6085 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 6086 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 6087 // call void @llvm.dbg.value(metadata i32 %b, "b", 6088 // ... 6089 // call void @llvm.dbg.value(metadata i32 %a1, "b" 6090 // ... 6091 // 6092 // then the last dbg.value is describing a parameter "b" using a value that 6093 // is an argument. But since we already has used %a1 to describe a parameter 6094 // we should not handle that last dbg.value here (that would result in an 6095 // incorrect hoisting of the DBG_VALUE to the function entry). 6096 // Notice that we allow one dbg.value per IR level argument, to accommodate 6097 // for the situation with fragments above. 6098 // If there is no node for the value being handled, we return true to skip 6099 // the normal generation of debug info, as it would kill existing debug 6100 // info for the parameter in case of duplicates. 6101 if (VariableIsFunctionInputArg) { 6102 unsigned ArgNo = Arg->getArgNo(); 6103 if (ArgNo >= FuncInfo.DescribedArgs.size()) 6104 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 6105 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 6106 return !NodeMap[V].getNode(); 6107 FuncInfo.DescribedArgs.set(ArgNo); 6108 } 6109 } 6110 6111 bool IsIndirect = false; 6112 std::optional<MachineOperand> Op; 6113 // Some arguments' frame index is recorded during argument lowering. 6114 int FI = FuncInfo.getArgumentFrameIndex(Arg); 6115 if (FI != std::numeric_limits<int>::max()) 6116 Op = MachineOperand::CreateFI(FI); 6117 6118 SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes; 6119 if (!Op && N.getNode()) { 6120 getUnderlyingArgRegs(ArgRegsAndSizes, N); 6121 Register Reg; 6122 if (ArgRegsAndSizes.size() == 1) 6123 Reg = ArgRegsAndSizes.front().first; 6124 6125 if (Reg && Reg.isVirtual()) { 6126 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6127 Register PR = RegInfo.getLiveInPhysReg(Reg); 6128 if (PR) 6129 Reg = PR; 6130 } 6131 if (Reg) { 6132 Op = MachineOperand::CreateReg(Reg, false); 6133 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6134 } 6135 } 6136 6137 if (!Op && N.getNode()) { 6138 // Check if frame index is available. 6139 SDValue LCandidate = peekThroughBitcasts(N); 6140 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 6141 if (FrameIndexSDNode *FINode = 6142 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 6143 Op = MachineOperand::CreateFI(FINode->getIndex()); 6144 } 6145 6146 if (!Op) { 6147 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 6148 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<Register, TypeSize>> 6149 SplitRegs) { 6150 unsigned Offset = 0; 6151 for (const auto &RegAndSize : SplitRegs) { 6152 // If the expression is already a fragment, the current register 6153 // offset+size might extend beyond the fragment. In this case, only 6154 // the register bits that are inside the fragment are relevant. 6155 int RegFragmentSizeInBits = RegAndSize.second; 6156 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 6157 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 6158 // The register is entirely outside the expression fragment, 6159 // so is irrelevant for debug info. 6160 if (Offset >= ExprFragmentSizeInBits) 6161 break; 6162 // The register is partially outside the expression fragment, only 6163 // the low bits within the fragment are relevant for debug info. 6164 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 6165 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 6166 } 6167 } 6168 6169 auto FragmentExpr = DIExpression::createFragmentExpression( 6170 Expr, Offset, RegFragmentSizeInBits); 6171 Offset += RegAndSize.second; 6172 // If a valid fragment expression cannot be created, the variable's 6173 // correct value cannot be determined and so it is set as Undef. 6174 if (!FragmentExpr) { 6175 SDDbgValue *SDV = DAG.getConstantDbgValue( 6176 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 6177 DAG.AddDbgValue(SDV, false); 6178 continue; 6179 } 6180 MachineInstr *NewMI = 6181 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 6182 Kind != FuncArgumentDbgValueKind::Value); 6183 FuncInfo.ArgDbgValues.push_back(NewMI); 6184 } 6185 }; 6186 6187 // Check if ValueMap has reg number. 6188 DenseMap<const Value *, Register>::const_iterator 6189 VMI = FuncInfo.ValueMap.find(V); 6190 if (VMI != FuncInfo.ValueMap.end()) { 6191 const auto &TLI = DAG.getTargetLoweringInfo(); 6192 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 6193 V->getType(), std::nullopt); 6194 if (RFV.occupiesMultipleRegs()) { 6195 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 6196 return true; 6197 } 6198 6199 Op = MachineOperand::CreateReg(VMI->second, false); 6200 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6201 } else if (ArgRegsAndSizes.size() > 1) { 6202 // This was split due to the calling convention, and no virtual register 6203 // mapping exists for the value. 6204 splitMultiRegDbgValue(ArgRegsAndSizes); 6205 return true; 6206 } 6207 } 6208 6209 if (!Op) 6210 return false; 6211 6212 assert(Variable->isValidLocationForIntrinsic(DL) && 6213 "Expected inlined-at fields to agree"); 6214 MachineInstr *NewMI = nullptr; 6215 6216 if (Op->isReg()) 6217 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 6218 else 6219 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 6220 Variable, Expr); 6221 6222 // Otherwise, use ArgDbgValues. 6223 FuncInfo.ArgDbgValues.push_back(NewMI); 6224 return true; 6225 } 6226 6227 /// Return the appropriate SDDbgValue based on N. 6228 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 6229 DILocalVariable *Variable, 6230 DIExpression *Expr, 6231 const DebugLoc &dl, 6232 unsigned DbgSDNodeOrder) { 6233 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 6234 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 6235 // stack slot locations. 6236 // 6237 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 6238 // debug values here after optimization: 6239 // 6240 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 6241 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 6242 // 6243 // Both describe the direct values of their associated variables. 6244 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 6245 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6246 } 6247 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 6248 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6249 } 6250 6251 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 6252 switch (Intrinsic) { 6253 case Intrinsic::smul_fix: 6254 return ISD::SMULFIX; 6255 case Intrinsic::umul_fix: 6256 return ISD::UMULFIX; 6257 case Intrinsic::smul_fix_sat: 6258 return ISD::SMULFIXSAT; 6259 case Intrinsic::umul_fix_sat: 6260 return ISD::UMULFIXSAT; 6261 case Intrinsic::sdiv_fix: 6262 return ISD::SDIVFIX; 6263 case Intrinsic::udiv_fix: 6264 return ISD::UDIVFIX; 6265 case Intrinsic::sdiv_fix_sat: 6266 return ISD::SDIVFIXSAT; 6267 case Intrinsic::udiv_fix_sat: 6268 return ISD::UDIVFIXSAT; 6269 default: 6270 llvm_unreachable("Unhandled fixed point intrinsic"); 6271 } 6272 } 6273 6274 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6275 const char *FunctionName) { 6276 assert(FunctionName && "FunctionName must not be nullptr"); 6277 SDValue Callee = DAG.getExternalSymbol( 6278 FunctionName, 6279 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6280 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6281 } 6282 6283 /// Given a @llvm.call.preallocated.setup, return the corresponding 6284 /// preallocated call. 6285 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6286 assert(cast<CallBase>(PreallocatedSetup) 6287 ->getCalledFunction() 6288 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6289 "expected call_preallocated_setup Value"); 6290 for (const auto *U : PreallocatedSetup->users()) { 6291 auto *UseCall = cast<CallBase>(U); 6292 const Function *Fn = UseCall->getCalledFunction(); 6293 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6294 return UseCall; 6295 } 6296 } 6297 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6298 } 6299 6300 /// If DI is a debug value with an EntryValue expression, lower it using the 6301 /// corresponding physical register of the associated Argument value 6302 /// (guaranteed to exist by the verifier). 6303 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6304 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6305 DIExpression *Expr, DebugLoc DbgLoc) { 6306 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6307 return false; 6308 6309 // These properties are guaranteed by the verifier. 6310 const Argument *Arg = cast<Argument>(Values[0]); 6311 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6312 6313 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6314 if (ArgIt == FuncInfo.ValueMap.end()) { 6315 LLVM_DEBUG( 6316 dbgs() << "Dropping dbg.value: expression is entry_value but " 6317 "couldn't find an associated register for the Argument\n"); 6318 return true; 6319 } 6320 Register ArgVReg = ArgIt->getSecond(); 6321 6322 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6323 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6324 SDDbgValue *SDV = DAG.getVRegDbgValue( 6325 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6326 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6327 return true; 6328 } 6329 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6330 "couldn't find a physical register\n"); 6331 return true; 6332 } 6333 6334 /// Lower the call to the specified intrinsic function. 6335 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I, 6336 unsigned Intrinsic) { 6337 SDLoc sdl = getCurSDLoc(); 6338 switch (Intrinsic) { 6339 case Intrinsic::experimental_convergence_anchor: 6340 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped)); 6341 break; 6342 case Intrinsic::experimental_convergence_entry: 6343 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped)); 6344 break; 6345 case Intrinsic::experimental_convergence_loop: { 6346 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl); 6347 auto *Token = Bundle->Inputs[0].get(); 6348 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped, 6349 getValue(Token))); 6350 break; 6351 } 6352 } 6353 } 6354 6355 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I, 6356 unsigned IntrinsicID) { 6357 // For now, we're only lowering an 'add' histogram. 6358 // We can add others later, e.g. saturating adds, min/max. 6359 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add && 6360 "Tried to lower unsupported histogram type"); 6361 SDLoc sdl = getCurSDLoc(); 6362 Value *Ptr = I.getOperand(0); 6363 SDValue Inc = getValue(I.getOperand(1)); 6364 SDValue Mask = getValue(I.getOperand(2)); 6365 6366 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6367 DataLayout TargetDL = DAG.getDataLayout(); 6368 EVT VT = Inc.getValueType(); 6369 Align Alignment = DAG.getEVTAlign(VT); 6370 6371 const MDNode *Ranges = getRangeMetadata(I); 6372 6373 SDValue Root = DAG.getRoot(); 6374 SDValue Base; 6375 SDValue Index; 6376 ISD::MemIndexType IndexType; 6377 SDValue Scale; 6378 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 6379 I.getParent(), VT.getScalarStoreSize()); 6380 6381 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 6382 6383 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6384 MachinePointerInfo(AS), 6385 MachineMemOperand::MOLoad | MachineMemOperand::MOStore, 6386 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 6387 6388 if (!UniformBase) { 6389 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6390 Index = getValue(Ptr); 6391 IndexType = ISD::SIGNED_SCALED; 6392 Scale = 6393 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6394 } 6395 6396 EVT IdxVT = Index.getValueType(); 6397 EVT EltTy = IdxVT.getVectorElementType(); 6398 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 6399 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 6400 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 6401 } 6402 6403 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32); 6404 6405 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID}; 6406 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl, 6407 Ops, MMO, IndexType); 6408 6409 setValue(&I, Histogram); 6410 DAG.setRoot(Histogram); 6411 } 6412 6413 /// Lower the call to the specified intrinsic function. 6414 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6415 unsigned Intrinsic) { 6416 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6417 SDLoc sdl = getCurSDLoc(); 6418 DebugLoc dl = getCurDebugLoc(); 6419 SDValue Res; 6420 6421 SDNodeFlags Flags; 6422 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6423 Flags.copyFMF(*FPOp); 6424 6425 switch (Intrinsic) { 6426 default: 6427 // By default, turn this into a target intrinsic node. 6428 visitTargetIntrinsic(I, Intrinsic); 6429 return; 6430 case Intrinsic::vscale: { 6431 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6432 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6433 return; 6434 } 6435 case Intrinsic::vastart: visitVAStart(I); return; 6436 case Intrinsic::vaend: visitVAEnd(I); return; 6437 case Intrinsic::vacopy: visitVACopy(I); return; 6438 case Intrinsic::returnaddress: 6439 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6440 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6441 getValue(I.getArgOperand(0)))); 6442 return; 6443 case Intrinsic::addressofreturnaddress: 6444 setValue(&I, 6445 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6446 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6447 return; 6448 case Intrinsic::sponentry: 6449 setValue(&I, 6450 DAG.getNode(ISD::SPONENTRY, sdl, 6451 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6452 return; 6453 case Intrinsic::frameaddress: 6454 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6455 TLI.getFrameIndexTy(DAG.getDataLayout()), 6456 getValue(I.getArgOperand(0)))); 6457 return; 6458 case Intrinsic::read_volatile_register: 6459 case Intrinsic::read_register: { 6460 Value *Reg = I.getArgOperand(0); 6461 SDValue Chain = getRoot(); 6462 SDValue RegName = 6463 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6464 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6465 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6466 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6467 setValue(&I, Res); 6468 DAG.setRoot(Res.getValue(1)); 6469 return; 6470 } 6471 case Intrinsic::write_register: { 6472 Value *Reg = I.getArgOperand(0); 6473 Value *RegValue = I.getArgOperand(1); 6474 SDValue Chain = getRoot(); 6475 SDValue RegName = 6476 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6477 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6478 RegName, getValue(RegValue))); 6479 return; 6480 } 6481 case Intrinsic::memcpy: { 6482 const auto &MCI = cast<MemCpyInst>(I); 6483 SDValue Op1 = getValue(I.getArgOperand(0)); 6484 SDValue Op2 = getValue(I.getArgOperand(1)); 6485 SDValue Op3 = getValue(I.getArgOperand(2)); 6486 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6487 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6488 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6489 Align Alignment = std::min(DstAlign, SrcAlign); 6490 bool isVol = MCI.isVolatile(); 6491 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6492 // node. 6493 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6494 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6495 /* AlwaysInline */ false, &I, std::nullopt, 6496 MachinePointerInfo(I.getArgOperand(0)), 6497 MachinePointerInfo(I.getArgOperand(1)), 6498 I.getAAMetadata(), AA); 6499 updateDAGForMaybeTailCall(MC); 6500 return; 6501 } 6502 case Intrinsic::memcpy_inline: { 6503 const auto &MCI = cast<MemCpyInlineInst>(I); 6504 SDValue Dst = getValue(I.getArgOperand(0)); 6505 SDValue Src = getValue(I.getArgOperand(1)); 6506 SDValue Size = getValue(I.getArgOperand(2)); 6507 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6508 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6509 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6510 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6511 Align Alignment = std::min(DstAlign, SrcAlign); 6512 bool isVol = MCI.isVolatile(); 6513 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6514 // node. 6515 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6516 /* AlwaysInline */ true, &I, std::nullopt, 6517 MachinePointerInfo(I.getArgOperand(0)), 6518 MachinePointerInfo(I.getArgOperand(1)), 6519 I.getAAMetadata(), AA); 6520 updateDAGForMaybeTailCall(MC); 6521 return; 6522 } 6523 case Intrinsic::memset: { 6524 const auto &MSI = cast<MemSetInst>(I); 6525 SDValue Op1 = getValue(I.getArgOperand(0)); 6526 SDValue Op2 = getValue(I.getArgOperand(1)); 6527 SDValue Op3 = getValue(I.getArgOperand(2)); 6528 // @llvm.memset defines 0 and 1 to both mean no alignment. 6529 Align Alignment = MSI.getDestAlign().valueOrOne(); 6530 bool isVol = MSI.isVolatile(); 6531 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6532 SDValue MS = DAG.getMemset( 6533 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6534 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6535 updateDAGForMaybeTailCall(MS); 6536 return; 6537 } 6538 case Intrinsic::memset_inline: { 6539 const auto &MSII = cast<MemSetInlineInst>(I); 6540 SDValue Dst = getValue(I.getArgOperand(0)); 6541 SDValue Value = getValue(I.getArgOperand(1)); 6542 SDValue Size = getValue(I.getArgOperand(2)); 6543 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6544 // @llvm.memset defines 0 and 1 to both mean no alignment. 6545 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6546 bool isVol = MSII.isVolatile(); 6547 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6548 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6549 /* AlwaysInline */ true, &I, 6550 MachinePointerInfo(I.getArgOperand(0)), 6551 I.getAAMetadata()); 6552 updateDAGForMaybeTailCall(MC); 6553 return; 6554 } 6555 case Intrinsic::memmove: { 6556 const auto &MMI = cast<MemMoveInst>(I); 6557 SDValue Op1 = getValue(I.getArgOperand(0)); 6558 SDValue Op2 = getValue(I.getArgOperand(1)); 6559 SDValue Op3 = getValue(I.getArgOperand(2)); 6560 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6561 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6562 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6563 Align Alignment = std::min(DstAlign, SrcAlign); 6564 bool isVol = MMI.isVolatile(); 6565 // FIXME: Support passing different dest/src alignments to the memmove DAG 6566 // node. 6567 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6568 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I, 6569 /* OverrideTailCall */ std::nullopt, 6570 MachinePointerInfo(I.getArgOperand(0)), 6571 MachinePointerInfo(I.getArgOperand(1)), 6572 I.getAAMetadata(), AA); 6573 updateDAGForMaybeTailCall(MM); 6574 return; 6575 } 6576 case Intrinsic::memcpy_element_unordered_atomic: { 6577 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6578 SDValue Dst = getValue(MI.getRawDest()); 6579 SDValue Src = getValue(MI.getRawSource()); 6580 SDValue Length = getValue(MI.getLength()); 6581 6582 Type *LengthTy = MI.getLength()->getType(); 6583 unsigned ElemSz = MI.getElementSizeInBytes(); 6584 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6585 SDValue MC = 6586 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6587 isTC, MachinePointerInfo(MI.getRawDest()), 6588 MachinePointerInfo(MI.getRawSource())); 6589 updateDAGForMaybeTailCall(MC); 6590 return; 6591 } 6592 case Intrinsic::memmove_element_unordered_atomic: { 6593 auto &MI = cast<AtomicMemMoveInst>(I); 6594 SDValue Dst = getValue(MI.getRawDest()); 6595 SDValue Src = getValue(MI.getRawSource()); 6596 SDValue Length = getValue(MI.getLength()); 6597 6598 Type *LengthTy = MI.getLength()->getType(); 6599 unsigned ElemSz = MI.getElementSizeInBytes(); 6600 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6601 SDValue MC = 6602 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6603 isTC, MachinePointerInfo(MI.getRawDest()), 6604 MachinePointerInfo(MI.getRawSource())); 6605 updateDAGForMaybeTailCall(MC); 6606 return; 6607 } 6608 case Intrinsic::memset_element_unordered_atomic: { 6609 auto &MI = cast<AtomicMemSetInst>(I); 6610 SDValue Dst = getValue(MI.getRawDest()); 6611 SDValue Val = getValue(MI.getValue()); 6612 SDValue Length = getValue(MI.getLength()); 6613 6614 Type *LengthTy = MI.getLength()->getType(); 6615 unsigned ElemSz = MI.getElementSizeInBytes(); 6616 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6617 SDValue MC = 6618 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6619 isTC, MachinePointerInfo(MI.getRawDest())); 6620 updateDAGForMaybeTailCall(MC); 6621 return; 6622 } 6623 case Intrinsic::call_preallocated_setup: { 6624 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6625 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6626 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6627 getRoot(), SrcValue); 6628 setValue(&I, Res); 6629 DAG.setRoot(Res); 6630 return; 6631 } 6632 case Intrinsic::call_preallocated_arg: { 6633 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6634 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6635 SDValue Ops[3]; 6636 Ops[0] = getRoot(); 6637 Ops[1] = SrcValue; 6638 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6639 MVT::i32); // arg index 6640 SDValue Res = DAG.getNode( 6641 ISD::PREALLOCATED_ARG, sdl, 6642 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6643 setValue(&I, Res); 6644 DAG.setRoot(Res.getValue(1)); 6645 return; 6646 } 6647 case Intrinsic::dbg_declare: { 6648 const auto &DI = cast<DbgDeclareInst>(I); 6649 // Debug intrinsics are handled separately in assignment tracking mode. 6650 // Some intrinsics are handled right after Argument lowering. 6651 if (AssignmentTrackingEnabled || 6652 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6653 return; 6654 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6655 DILocalVariable *Variable = DI.getVariable(); 6656 DIExpression *Expression = DI.getExpression(); 6657 dropDanglingDebugInfo(Variable, Expression); 6658 // Assume dbg.declare can not currently use DIArgList, i.e. 6659 // it is non-variadic. 6660 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6661 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6662 DI.getDebugLoc()); 6663 return; 6664 } 6665 case Intrinsic::dbg_label: { 6666 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6667 DILabel *Label = DI.getLabel(); 6668 assert(Label && "Missing label"); 6669 6670 SDDbgLabel *SDV; 6671 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6672 DAG.AddDbgLabel(SDV); 6673 return; 6674 } 6675 case Intrinsic::dbg_assign: { 6676 // Debug intrinsics are handled separately in assignment tracking mode. 6677 if (AssignmentTrackingEnabled) 6678 return; 6679 // If assignment tracking hasn't been enabled then fall through and treat 6680 // the dbg.assign as a dbg.value. 6681 [[fallthrough]]; 6682 } 6683 case Intrinsic::dbg_value: { 6684 // Debug intrinsics are handled separately in assignment tracking mode. 6685 if (AssignmentTrackingEnabled) 6686 return; 6687 const DbgValueInst &DI = cast<DbgValueInst>(I); 6688 assert(DI.getVariable() && "Missing variable"); 6689 6690 DILocalVariable *Variable = DI.getVariable(); 6691 DIExpression *Expression = DI.getExpression(); 6692 dropDanglingDebugInfo(Variable, Expression); 6693 6694 if (DI.isKillLocation()) { 6695 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6696 return; 6697 } 6698 6699 SmallVector<Value *, 4> Values(DI.getValues()); 6700 if (Values.empty()) 6701 return; 6702 6703 bool IsVariadic = DI.hasArgList(); 6704 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6705 SDNodeOrder, IsVariadic)) 6706 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6707 DI.getDebugLoc(), SDNodeOrder); 6708 return; 6709 } 6710 6711 case Intrinsic::eh_typeid_for: { 6712 // Find the type id for the given typeinfo. 6713 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6714 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6715 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6716 setValue(&I, Res); 6717 return; 6718 } 6719 6720 case Intrinsic::eh_return_i32: 6721 case Intrinsic::eh_return_i64: 6722 DAG.getMachineFunction().setCallsEHReturn(true); 6723 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6724 MVT::Other, 6725 getControlRoot(), 6726 getValue(I.getArgOperand(0)), 6727 getValue(I.getArgOperand(1)))); 6728 return; 6729 case Intrinsic::eh_unwind_init: 6730 DAG.getMachineFunction().setCallsUnwindInit(true); 6731 return; 6732 case Intrinsic::eh_dwarf_cfa: 6733 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6734 TLI.getPointerTy(DAG.getDataLayout()), 6735 getValue(I.getArgOperand(0)))); 6736 return; 6737 case Intrinsic::eh_sjlj_callsite: { 6738 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6739 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6740 6741 FuncInfo.setCurrentCallSite(CI->getZExtValue()); 6742 return; 6743 } 6744 case Intrinsic::eh_sjlj_functioncontext: { 6745 // Get and store the index of the function context. 6746 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6747 AllocaInst *FnCtx = 6748 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6749 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6750 MFI.setFunctionContextIndex(FI); 6751 return; 6752 } 6753 case Intrinsic::eh_sjlj_setjmp: { 6754 SDValue Ops[2]; 6755 Ops[0] = getRoot(); 6756 Ops[1] = getValue(I.getArgOperand(0)); 6757 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6758 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6759 setValue(&I, Op.getValue(0)); 6760 DAG.setRoot(Op.getValue(1)); 6761 return; 6762 } 6763 case Intrinsic::eh_sjlj_longjmp: 6764 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6765 getRoot(), getValue(I.getArgOperand(0)))); 6766 return; 6767 case Intrinsic::eh_sjlj_setup_dispatch: 6768 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6769 getRoot())); 6770 return; 6771 case Intrinsic::masked_gather: 6772 visitMaskedGather(I); 6773 return; 6774 case Intrinsic::masked_load: 6775 visitMaskedLoad(I); 6776 return; 6777 case Intrinsic::masked_scatter: 6778 visitMaskedScatter(I); 6779 return; 6780 case Intrinsic::masked_store: 6781 visitMaskedStore(I); 6782 return; 6783 case Intrinsic::masked_expandload: 6784 visitMaskedLoad(I, true /* IsExpanding */); 6785 return; 6786 case Intrinsic::masked_compressstore: 6787 visitMaskedStore(I, true /* IsCompressing */); 6788 return; 6789 case Intrinsic::powi: 6790 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6791 getValue(I.getArgOperand(1)), DAG)); 6792 return; 6793 case Intrinsic::log: 6794 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6795 return; 6796 case Intrinsic::log2: 6797 setValue(&I, 6798 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6799 return; 6800 case Intrinsic::log10: 6801 setValue(&I, 6802 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6803 return; 6804 case Intrinsic::exp: 6805 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6806 return; 6807 case Intrinsic::exp2: 6808 setValue(&I, 6809 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6810 return; 6811 case Intrinsic::pow: 6812 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6813 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6814 return; 6815 case Intrinsic::sqrt: 6816 case Intrinsic::fabs: 6817 case Intrinsic::sin: 6818 case Intrinsic::cos: 6819 case Intrinsic::tan: 6820 case Intrinsic::asin: 6821 case Intrinsic::acos: 6822 case Intrinsic::atan: 6823 case Intrinsic::sinh: 6824 case Intrinsic::cosh: 6825 case Intrinsic::tanh: 6826 case Intrinsic::exp10: 6827 case Intrinsic::floor: 6828 case Intrinsic::ceil: 6829 case Intrinsic::trunc: 6830 case Intrinsic::rint: 6831 case Intrinsic::nearbyint: 6832 case Intrinsic::round: 6833 case Intrinsic::roundeven: 6834 case Intrinsic::canonicalize: { 6835 unsigned Opcode; 6836 // clang-format off 6837 switch (Intrinsic) { 6838 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6839 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6840 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6841 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6842 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6843 case Intrinsic::tan: Opcode = ISD::FTAN; break; 6844 case Intrinsic::asin: Opcode = ISD::FASIN; break; 6845 case Intrinsic::acos: Opcode = ISD::FACOS; break; 6846 case Intrinsic::atan: Opcode = ISD::FATAN; break; 6847 case Intrinsic::sinh: Opcode = ISD::FSINH; break; 6848 case Intrinsic::cosh: Opcode = ISD::FCOSH; break; 6849 case Intrinsic::tanh: Opcode = ISD::FTANH; break; 6850 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6851 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6852 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6853 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6854 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6855 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6856 case Intrinsic::round: Opcode = ISD::FROUND; break; 6857 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6858 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6859 } 6860 // clang-format on 6861 6862 setValue(&I, DAG.getNode(Opcode, sdl, 6863 getValue(I.getArgOperand(0)).getValueType(), 6864 getValue(I.getArgOperand(0)), Flags)); 6865 return; 6866 } 6867 case Intrinsic::atan2: 6868 setValue(&I, DAG.getNode(ISD::FATAN2, sdl, 6869 getValue(I.getArgOperand(0)).getValueType(), 6870 getValue(I.getArgOperand(0)), 6871 getValue(I.getArgOperand(1)), Flags)); 6872 return; 6873 case Intrinsic::lround: 6874 case Intrinsic::llround: 6875 case Intrinsic::lrint: 6876 case Intrinsic::llrint: { 6877 unsigned Opcode; 6878 // clang-format off 6879 switch (Intrinsic) { 6880 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6881 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6882 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6883 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6884 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6885 } 6886 // clang-format on 6887 6888 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6889 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6890 getValue(I.getArgOperand(0)))); 6891 return; 6892 } 6893 case Intrinsic::minnum: 6894 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6895 getValue(I.getArgOperand(0)).getValueType(), 6896 getValue(I.getArgOperand(0)), 6897 getValue(I.getArgOperand(1)), Flags)); 6898 return; 6899 case Intrinsic::maxnum: 6900 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6901 getValue(I.getArgOperand(0)).getValueType(), 6902 getValue(I.getArgOperand(0)), 6903 getValue(I.getArgOperand(1)), Flags)); 6904 return; 6905 case Intrinsic::minimum: 6906 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6907 getValue(I.getArgOperand(0)).getValueType(), 6908 getValue(I.getArgOperand(0)), 6909 getValue(I.getArgOperand(1)), Flags)); 6910 return; 6911 case Intrinsic::maximum: 6912 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6913 getValue(I.getArgOperand(0)).getValueType(), 6914 getValue(I.getArgOperand(0)), 6915 getValue(I.getArgOperand(1)), Flags)); 6916 return; 6917 case Intrinsic::minimumnum: 6918 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl, 6919 getValue(I.getArgOperand(0)).getValueType(), 6920 getValue(I.getArgOperand(0)), 6921 getValue(I.getArgOperand(1)), Flags)); 6922 return; 6923 case Intrinsic::maximumnum: 6924 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl, 6925 getValue(I.getArgOperand(0)).getValueType(), 6926 getValue(I.getArgOperand(0)), 6927 getValue(I.getArgOperand(1)), Flags)); 6928 return; 6929 case Intrinsic::copysign: 6930 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6931 getValue(I.getArgOperand(0)).getValueType(), 6932 getValue(I.getArgOperand(0)), 6933 getValue(I.getArgOperand(1)), Flags)); 6934 return; 6935 case Intrinsic::ldexp: 6936 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6937 getValue(I.getArgOperand(0)).getValueType(), 6938 getValue(I.getArgOperand(0)), 6939 getValue(I.getArgOperand(1)), Flags)); 6940 return; 6941 case Intrinsic::sincos: 6942 case Intrinsic::frexp: { 6943 unsigned Opcode; 6944 switch (Intrinsic) { 6945 default: 6946 llvm_unreachable("unexpected intrinsic"); 6947 case Intrinsic::sincos: 6948 Opcode = ISD::FSINCOS; 6949 break; 6950 case Intrinsic::frexp: 6951 Opcode = ISD::FFREXP; 6952 break; 6953 } 6954 SmallVector<EVT, 2> ValueVTs; 6955 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6956 SDVTList VTs = DAG.getVTList(ValueVTs); 6957 setValue( 6958 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags)); 6959 return; 6960 } 6961 case Intrinsic::arithmetic_fence: { 6962 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6963 getValue(I.getArgOperand(0)).getValueType(), 6964 getValue(I.getArgOperand(0)), Flags)); 6965 return; 6966 } 6967 case Intrinsic::fma: 6968 setValue(&I, DAG.getNode( 6969 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6970 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6971 getValue(I.getArgOperand(2)), Flags)); 6972 return; 6973 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6974 case Intrinsic::INTRINSIC: 6975 #include "llvm/IR/ConstrainedOps.def" 6976 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6977 return; 6978 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6979 #include "llvm/IR/VPIntrinsics.def" 6980 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6981 return; 6982 case Intrinsic::fptrunc_round: { 6983 // Get the last argument, the metadata and convert it to an integer in the 6984 // call 6985 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6986 std::optional<RoundingMode> RoundMode = 6987 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6988 6989 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6990 6991 // Propagate fast-math-flags from IR to node(s). 6992 SDNodeFlags Flags; 6993 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6994 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6995 6996 SDValue Result; 6997 Result = DAG.getNode( 6998 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6999 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32)); 7000 setValue(&I, Result); 7001 7002 return; 7003 } 7004 case Intrinsic::fmuladd: { 7005 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7006 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7007 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7008 setValue(&I, DAG.getNode(ISD::FMA, sdl, 7009 getValue(I.getArgOperand(0)).getValueType(), 7010 getValue(I.getArgOperand(0)), 7011 getValue(I.getArgOperand(1)), 7012 getValue(I.getArgOperand(2)), Flags)); 7013 } else { 7014 // TODO: Intrinsic calls should have fast-math-flags. 7015 SDValue Mul = DAG.getNode( 7016 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 7017 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 7018 SDValue Add = DAG.getNode(ISD::FADD, sdl, 7019 getValue(I.getArgOperand(0)).getValueType(), 7020 Mul, getValue(I.getArgOperand(2)), Flags); 7021 setValue(&I, Add); 7022 } 7023 return; 7024 } 7025 case Intrinsic::convert_to_fp16: 7026 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 7027 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 7028 getValue(I.getArgOperand(0)), 7029 DAG.getTargetConstant(0, sdl, 7030 MVT::i32)))); 7031 return; 7032 case Intrinsic::convert_from_fp16: 7033 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 7034 TLI.getValueType(DAG.getDataLayout(), I.getType()), 7035 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 7036 getValue(I.getArgOperand(0))))); 7037 return; 7038 case Intrinsic::fptosi_sat: { 7039 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7040 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 7041 getValue(I.getArgOperand(0)), 7042 DAG.getValueType(VT.getScalarType()))); 7043 return; 7044 } 7045 case Intrinsic::fptoui_sat: { 7046 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7047 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 7048 getValue(I.getArgOperand(0)), 7049 DAG.getValueType(VT.getScalarType()))); 7050 return; 7051 } 7052 case Intrinsic::set_rounding: 7053 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 7054 {getRoot(), getValue(I.getArgOperand(0))}); 7055 setValue(&I, Res); 7056 DAG.setRoot(Res.getValue(0)); 7057 return; 7058 case Intrinsic::is_fpclass: { 7059 const DataLayout DLayout = DAG.getDataLayout(); 7060 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 7061 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 7062 FPClassTest Test = static_cast<FPClassTest>( 7063 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 7064 MachineFunction &MF = DAG.getMachineFunction(); 7065 const Function &F = MF.getFunction(); 7066 SDValue Op = getValue(I.getArgOperand(0)); 7067 SDNodeFlags Flags; 7068 Flags.setNoFPExcept( 7069 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 7070 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 7071 // expansion can use illegal types. Making expansion early allows 7072 // legalizing these types prior to selection. 7073 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) && 7074 !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) { 7075 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 7076 setValue(&I, Result); 7077 return; 7078 } 7079 7080 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 7081 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 7082 setValue(&I, V); 7083 return; 7084 } 7085 case Intrinsic::get_fpenv: { 7086 const DataLayout DLayout = DAG.getDataLayout(); 7087 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 7088 Align TempAlign = DAG.getEVTAlign(EnvVT); 7089 SDValue Chain = getRoot(); 7090 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 7091 // and temporary storage in stack. 7092 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 7093 Res = DAG.getNode( 7094 ISD::GET_FPENV, sdl, 7095 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7096 MVT::Other), 7097 Chain); 7098 } else { 7099 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7100 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7101 auto MPI = 7102 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7103 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7104 MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(), 7105 TempAlign); 7106 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7107 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 7108 } 7109 setValue(&I, Res); 7110 DAG.setRoot(Res.getValue(1)); 7111 return; 7112 } 7113 case Intrinsic::set_fpenv: { 7114 const DataLayout DLayout = DAG.getDataLayout(); 7115 SDValue Env = getValue(I.getArgOperand(0)); 7116 EVT EnvVT = Env.getValueType(); 7117 Align TempAlign = DAG.getEVTAlign(EnvVT); 7118 SDValue Chain = getRoot(); 7119 // If SET_FPENV is custom or legal, use it. Otherwise use loading 7120 // environment from memory. 7121 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 7122 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 7123 } else { 7124 // Allocate space in stack, copy environment bits into it and use this 7125 // memory in SET_FPENV_MEM. 7126 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7127 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7128 auto MPI = 7129 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7130 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 7131 MachineMemOperand::MOStore); 7132 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7133 MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(), 7134 TempAlign); 7135 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7136 } 7137 DAG.setRoot(Chain); 7138 return; 7139 } 7140 case Intrinsic::reset_fpenv: 7141 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 7142 return; 7143 case Intrinsic::get_fpmode: 7144 Res = DAG.getNode( 7145 ISD::GET_FPMODE, sdl, 7146 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7147 MVT::Other), 7148 DAG.getRoot()); 7149 setValue(&I, Res); 7150 DAG.setRoot(Res.getValue(1)); 7151 return; 7152 case Intrinsic::set_fpmode: 7153 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 7154 getValue(I.getArgOperand(0))); 7155 DAG.setRoot(Res); 7156 return; 7157 case Intrinsic::reset_fpmode: { 7158 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 7159 DAG.setRoot(Res); 7160 return; 7161 } 7162 case Intrinsic::pcmarker: { 7163 SDValue Tmp = getValue(I.getArgOperand(0)); 7164 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 7165 return; 7166 } 7167 case Intrinsic::readcyclecounter: { 7168 SDValue Op = getRoot(); 7169 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 7170 DAG.getVTList(MVT::i64, MVT::Other), Op); 7171 setValue(&I, Res); 7172 DAG.setRoot(Res.getValue(1)); 7173 return; 7174 } 7175 case Intrinsic::readsteadycounter: { 7176 SDValue Op = getRoot(); 7177 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 7178 DAG.getVTList(MVT::i64, MVT::Other), Op); 7179 setValue(&I, Res); 7180 DAG.setRoot(Res.getValue(1)); 7181 return; 7182 } 7183 case Intrinsic::bitreverse: 7184 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 7185 getValue(I.getArgOperand(0)).getValueType(), 7186 getValue(I.getArgOperand(0)))); 7187 return; 7188 case Intrinsic::bswap: 7189 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 7190 getValue(I.getArgOperand(0)).getValueType(), 7191 getValue(I.getArgOperand(0)))); 7192 return; 7193 case Intrinsic::cttz: { 7194 SDValue Arg = getValue(I.getArgOperand(0)); 7195 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7196 EVT Ty = Arg.getValueType(); 7197 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 7198 sdl, Ty, Arg)); 7199 return; 7200 } 7201 case Intrinsic::ctlz: { 7202 SDValue Arg = getValue(I.getArgOperand(0)); 7203 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7204 EVT Ty = Arg.getValueType(); 7205 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 7206 sdl, Ty, Arg)); 7207 return; 7208 } 7209 case Intrinsic::ctpop: { 7210 SDValue Arg = getValue(I.getArgOperand(0)); 7211 EVT Ty = Arg.getValueType(); 7212 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 7213 return; 7214 } 7215 case Intrinsic::fshl: 7216 case Intrinsic::fshr: { 7217 bool IsFSHL = Intrinsic == Intrinsic::fshl; 7218 SDValue X = getValue(I.getArgOperand(0)); 7219 SDValue Y = getValue(I.getArgOperand(1)); 7220 SDValue Z = getValue(I.getArgOperand(2)); 7221 EVT VT = X.getValueType(); 7222 7223 if (X == Y) { 7224 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 7225 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 7226 } else { 7227 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 7228 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 7229 } 7230 return; 7231 } 7232 case Intrinsic::sadd_sat: { 7233 SDValue Op1 = getValue(I.getArgOperand(0)); 7234 SDValue Op2 = getValue(I.getArgOperand(1)); 7235 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7236 return; 7237 } 7238 case Intrinsic::uadd_sat: { 7239 SDValue Op1 = getValue(I.getArgOperand(0)); 7240 SDValue Op2 = getValue(I.getArgOperand(1)); 7241 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7242 return; 7243 } 7244 case Intrinsic::ssub_sat: { 7245 SDValue Op1 = getValue(I.getArgOperand(0)); 7246 SDValue Op2 = getValue(I.getArgOperand(1)); 7247 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7248 return; 7249 } 7250 case Intrinsic::usub_sat: { 7251 SDValue Op1 = getValue(I.getArgOperand(0)); 7252 SDValue Op2 = getValue(I.getArgOperand(1)); 7253 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7254 return; 7255 } 7256 case Intrinsic::sshl_sat: { 7257 SDValue Op1 = getValue(I.getArgOperand(0)); 7258 SDValue Op2 = getValue(I.getArgOperand(1)); 7259 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7260 return; 7261 } 7262 case Intrinsic::ushl_sat: { 7263 SDValue Op1 = getValue(I.getArgOperand(0)); 7264 SDValue Op2 = getValue(I.getArgOperand(1)); 7265 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7266 return; 7267 } 7268 case Intrinsic::smul_fix: 7269 case Intrinsic::umul_fix: 7270 case Intrinsic::smul_fix_sat: 7271 case Intrinsic::umul_fix_sat: { 7272 SDValue Op1 = getValue(I.getArgOperand(0)); 7273 SDValue Op2 = getValue(I.getArgOperand(1)); 7274 SDValue Op3 = getValue(I.getArgOperand(2)); 7275 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7276 Op1.getValueType(), Op1, Op2, Op3)); 7277 return; 7278 } 7279 case Intrinsic::sdiv_fix: 7280 case Intrinsic::udiv_fix: 7281 case Intrinsic::sdiv_fix_sat: 7282 case Intrinsic::udiv_fix_sat: { 7283 SDValue Op1 = getValue(I.getArgOperand(0)); 7284 SDValue Op2 = getValue(I.getArgOperand(1)); 7285 SDValue Op3 = getValue(I.getArgOperand(2)); 7286 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7287 Op1, Op2, Op3, DAG, TLI)); 7288 return; 7289 } 7290 case Intrinsic::smax: { 7291 SDValue Op1 = getValue(I.getArgOperand(0)); 7292 SDValue Op2 = getValue(I.getArgOperand(1)); 7293 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 7294 return; 7295 } 7296 case Intrinsic::smin: { 7297 SDValue Op1 = getValue(I.getArgOperand(0)); 7298 SDValue Op2 = getValue(I.getArgOperand(1)); 7299 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 7300 return; 7301 } 7302 case Intrinsic::umax: { 7303 SDValue Op1 = getValue(I.getArgOperand(0)); 7304 SDValue Op2 = getValue(I.getArgOperand(1)); 7305 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 7306 return; 7307 } 7308 case Intrinsic::umin: { 7309 SDValue Op1 = getValue(I.getArgOperand(0)); 7310 SDValue Op2 = getValue(I.getArgOperand(1)); 7311 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 7312 return; 7313 } 7314 case Intrinsic::abs: { 7315 // TODO: Preserve "int min is poison" arg in SDAG? 7316 SDValue Op1 = getValue(I.getArgOperand(0)); 7317 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 7318 return; 7319 } 7320 case Intrinsic::scmp: { 7321 SDValue Op1 = getValue(I.getArgOperand(0)); 7322 SDValue Op2 = getValue(I.getArgOperand(1)); 7323 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7324 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2)); 7325 break; 7326 } 7327 case Intrinsic::ucmp: { 7328 SDValue Op1 = getValue(I.getArgOperand(0)); 7329 SDValue Op2 = getValue(I.getArgOperand(1)); 7330 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7331 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2)); 7332 break; 7333 } 7334 case Intrinsic::stacksave: { 7335 SDValue Op = getRoot(); 7336 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7337 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 7338 setValue(&I, Res); 7339 DAG.setRoot(Res.getValue(1)); 7340 return; 7341 } 7342 case Intrinsic::stackrestore: 7343 Res = getValue(I.getArgOperand(0)); 7344 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 7345 return; 7346 case Intrinsic::get_dynamic_area_offset: { 7347 SDValue Op = getRoot(); 7348 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7349 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7350 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 7351 // target. 7352 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 7353 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 7354 " intrinsic!"); 7355 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 7356 Op); 7357 DAG.setRoot(Op); 7358 setValue(&I, Res); 7359 return; 7360 } 7361 case Intrinsic::stackguard: { 7362 MachineFunction &MF = DAG.getMachineFunction(); 7363 const Module &M = *MF.getFunction().getParent(); 7364 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7365 SDValue Chain = getRoot(); 7366 if (TLI.useLoadStackGuardNode(M)) { 7367 Res = getLoadStackGuard(DAG, sdl, Chain); 7368 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 7369 } else { 7370 const Value *Global = TLI.getSDagStackGuard(M); 7371 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7372 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7373 MachinePointerInfo(Global, 0), Align, 7374 MachineMemOperand::MOVolatile); 7375 } 7376 if (TLI.useStackGuardXorFP()) 7377 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7378 DAG.setRoot(Chain); 7379 setValue(&I, Res); 7380 return; 7381 } 7382 case Intrinsic::stackprotector: { 7383 // Emit code into the DAG to store the stack guard onto the stack. 7384 MachineFunction &MF = DAG.getMachineFunction(); 7385 MachineFrameInfo &MFI = MF.getFrameInfo(); 7386 const Module &M = *MF.getFunction().getParent(); 7387 SDValue Src, Chain = getRoot(); 7388 7389 if (TLI.useLoadStackGuardNode(M)) 7390 Src = getLoadStackGuard(DAG, sdl, Chain); 7391 else 7392 Src = getValue(I.getArgOperand(0)); // The guard's value. 7393 7394 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7395 7396 int FI = FuncInfo.StaticAllocaMap[Slot]; 7397 MFI.setStackProtectorIndex(FI); 7398 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7399 7400 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7401 7402 // Store the stack protector onto the stack. 7403 Res = DAG.getStore( 7404 Chain, sdl, Src, FIN, 7405 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7406 MaybeAlign(), MachineMemOperand::MOVolatile); 7407 setValue(&I, Res); 7408 DAG.setRoot(Res); 7409 return; 7410 } 7411 case Intrinsic::objectsize: 7412 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7413 7414 case Intrinsic::is_constant: 7415 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7416 7417 case Intrinsic::annotation: 7418 case Intrinsic::ptr_annotation: 7419 case Intrinsic::launder_invariant_group: 7420 case Intrinsic::strip_invariant_group: 7421 // Drop the intrinsic, but forward the value 7422 setValue(&I, getValue(I.getOperand(0))); 7423 return; 7424 7425 case Intrinsic::assume: 7426 case Intrinsic::experimental_noalias_scope_decl: 7427 case Intrinsic::var_annotation: 7428 case Intrinsic::sideeffect: 7429 // Discard annotate attributes, noalias scope declarations, assumptions, and 7430 // artificial side-effects. 7431 return; 7432 7433 case Intrinsic::codeview_annotation: { 7434 // Emit a label associated with this metadata. 7435 MachineFunction &MF = DAG.getMachineFunction(); 7436 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true); 7437 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7438 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7439 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7440 DAG.setRoot(Res); 7441 return; 7442 } 7443 7444 case Intrinsic::init_trampoline: { 7445 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7446 7447 SDValue Ops[6]; 7448 Ops[0] = getRoot(); 7449 Ops[1] = getValue(I.getArgOperand(0)); 7450 Ops[2] = getValue(I.getArgOperand(1)); 7451 Ops[3] = getValue(I.getArgOperand(2)); 7452 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7453 Ops[5] = DAG.getSrcValue(F); 7454 7455 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7456 7457 DAG.setRoot(Res); 7458 return; 7459 } 7460 case Intrinsic::adjust_trampoline: 7461 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7462 TLI.getPointerTy(DAG.getDataLayout()), 7463 getValue(I.getArgOperand(0)))); 7464 return; 7465 case Intrinsic::gcroot: { 7466 assert(DAG.getMachineFunction().getFunction().hasGC() && 7467 "only valid in functions with gc specified, enforced by Verifier"); 7468 assert(GFI && "implied by previous"); 7469 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7470 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7471 7472 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7473 GFI->addStackRoot(FI->getIndex(), TypeMap); 7474 return; 7475 } 7476 case Intrinsic::gcread: 7477 case Intrinsic::gcwrite: 7478 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7479 case Intrinsic::get_rounding: 7480 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7481 setValue(&I, Res); 7482 DAG.setRoot(Res.getValue(1)); 7483 return; 7484 7485 case Intrinsic::expect: 7486 // Just replace __builtin_expect(exp, c) with EXP. 7487 setValue(&I, getValue(I.getArgOperand(0))); 7488 return; 7489 7490 case Intrinsic::ubsantrap: 7491 case Intrinsic::debugtrap: 7492 case Intrinsic::trap: { 7493 StringRef TrapFuncName = 7494 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7495 if (TrapFuncName.empty()) { 7496 switch (Intrinsic) { 7497 case Intrinsic::trap: 7498 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7499 break; 7500 case Intrinsic::debugtrap: 7501 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7502 break; 7503 case Intrinsic::ubsantrap: 7504 DAG.setRoot(DAG.getNode( 7505 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7506 DAG.getTargetConstant( 7507 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7508 MVT::i32))); 7509 break; 7510 default: llvm_unreachable("unknown trap intrinsic"); 7511 } 7512 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(), 7513 I.hasFnAttr(Attribute::NoMerge)); 7514 return; 7515 } 7516 TargetLowering::ArgListTy Args; 7517 if (Intrinsic == Intrinsic::ubsantrap) { 7518 Args.push_back(TargetLoweringBase::ArgListEntry()); 7519 Args[0].Val = I.getArgOperand(0); 7520 Args[0].Node = getValue(Args[0].Val); 7521 Args[0].Ty = Args[0].Val->getType(); 7522 } 7523 7524 TargetLowering::CallLoweringInfo CLI(DAG); 7525 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7526 CallingConv::C, I.getType(), 7527 DAG.getExternalSymbol(TrapFuncName.data(), 7528 TLI.getPointerTy(DAG.getDataLayout())), 7529 std::move(Args)); 7530 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge); 7531 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7532 DAG.setRoot(Result.second); 7533 return; 7534 } 7535 7536 case Intrinsic::allow_runtime_check: 7537 case Intrinsic::allow_ubsan_check: 7538 setValue(&I, getValue(ConstantInt::getTrue(I.getType()))); 7539 return; 7540 7541 case Intrinsic::uadd_with_overflow: 7542 case Intrinsic::sadd_with_overflow: 7543 case Intrinsic::usub_with_overflow: 7544 case Intrinsic::ssub_with_overflow: 7545 case Intrinsic::umul_with_overflow: 7546 case Intrinsic::smul_with_overflow: { 7547 ISD::NodeType Op; 7548 switch (Intrinsic) { 7549 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7550 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7551 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7552 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7553 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7554 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7555 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7556 } 7557 SDValue Op1 = getValue(I.getArgOperand(0)); 7558 SDValue Op2 = getValue(I.getArgOperand(1)); 7559 7560 EVT ResultVT = Op1.getValueType(); 7561 EVT OverflowVT = MVT::i1; 7562 if (ResultVT.isVector()) 7563 OverflowVT = EVT::getVectorVT( 7564 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7565 7566 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7567 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7568 return; 7569 } 7570 case Intrinsic::prefetch: { 7571 SDValue Ops[5]; 7572 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7573 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7574 Ops[0] = DAG.getRoot(); 7575 Ops[1] = getValue(I.getArgOperand(0)); 7576 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7577 MVT::i32); 7578 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7579 MVT::i32); 7580 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7581 MVT::i32); 7582 SDValue Result = DAG.getMemIntrinsicNode( 7583 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7584 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7585 /* align */ std::nullopt, Flags); 7586 7587 // Chain the prefetch in parallel with any pending loads, to stay out of 7588 // the way of later optimizations. 7589 PendingLoads.push_back(Result); 7590 Result = getRoot(); 7591 DAG.setRoot(Result); 7592 return; 7593 } 7594 case Intrinsic::lifetime_start: 7595 case Intrinsic::lifetime_end: { 7596 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7597 // Stack coloring is not enabled in O0, discard region information. 7598 if (TM.getOptLevel() == CodeGenOptLevel::None) 7599 return; 7600 7601 const int64_t ObjectSize = 7602 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7603 Value *const ObjectPtr = I.getArgOperand(1); 7604 SmallVector<const Value *, 4> Allocas; 7605 getUnderlyingObjects(ObjectPtr, Allocas); 7606 7607 for (const Value *Alloca : Allocas) { 7608 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7609 7610 // Could not find an Alloca. 7611 if (!LifetimeObject) 7612 continue; 7613 7614 // First check that the Alloca is static, otherwise it won't have a 7615 // valid frame index. 7616 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7617 if (SI == FuncInfo.StaticAllocaMap.end()) 7618 return; 7619 7620 const int FrameIndex = SI->second; 7621 int64_t Offset; 7622 if (GetPointerBaseWithConstantOffset( 7623 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7624 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7625 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7626 Offset); 7627 DAG.setRoot(Res); 7628 } 7629 return; 7630 } 7631 case Intrinsic::pseudoprobe: { 7632 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7633 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7634 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7635 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7636 DAG.setRoot(Res); 7637 return; 7638 } 7639 case Intrinsic::invariant_start: 7640 // Discard region information. 7641 setValue(&I, 7642 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7643 return; 7644 case Intrinsic::invariant_end: 7645 // Discard region information. 7646 return; 7647 case Intrinsic::clear_cache: { 7648 SDValue InputChain = DAG.getRoot(); 7649 SDValue StartVal = getValue(I.getArgOperand(0)); 7650 SDValue EndVal = getValue(I.getArgOperand(1)); 7651 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other), 7652 {InputChain, StartVal, EndVal}); 7653 setValue(&I, Res); 7654 DAG.setRoot(Res); 7655 return; 7656 } 7657 case Intrinsic::donothing: 7658 case Intrinsic::seh_try_begin: 7659 case Intrinsic::seh_scope_begin: 7660 case Intrinsic::seh_try_end: 7661 case Intrinsic::seh_scope_end: 7662 // ignore 7663 return; 7664 case Intrinsic::experimental_stackmap: 7665 visitStackmap(I); 7666 return; 7667 case Intrinsic::experimental_patchpoint_void: 7668 case Intrinsic::experimental_patchpoint: 7669 visitPatchpoint(I); 7670 return; 7671 case Intrinsic::experimental_gc_statepoint: 7672 LowerStatepoint(cast<GCStatepointInst>(I)); 7673 return; 7674 case Intrinsic::experimental_gc_result: 7675 visitGCResult(cast<GCResultInst>(I)); 7676 return; 7677 case Intrinsic::experimental_gc_relocate: 7678 visitGCRelocate(cast<GCRelocateInst>(I)); 7679 return; 7680 case Intrinsic::instrprof_cover: 7681 llvm_unreachable("instrprof failed to lower a cover"); 7682 case Intrinsic::instrprof_increment: 7683 llvm_unreachable("instrprof failed to lower an increment"); 7684 case Intrinsic::instrprof_timestamp: 7685 llvm_unreachable("instrprof failed to lower a timestamp"); 7686 case Intrinsic::instrprof_value_profile: 7687 llvm_unreachable("instrprof failed to lower a value profiling call"); 7688 case Intrinsic::instrprof_mcdc_parameters: 7689 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7690 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7691 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7692 case Intrinsic::localescape: { 7693 MachineFunction &MF = DAG.getMachineFunction(); 7694 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7695 7696 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7697 // is the same on all targets. 7698 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7699 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7700 if (isa<ConstantPointerNull>(Arg)) 7701 continue; // Skip null pointers. They represent a hole in index space. 7702 AllocaInst *Slot = cast<AllocaInst>(Arg); 7703 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7704 "can only escape static allocas"); 7705 int FI = FuncInfo.StaticAllocaMap[Slot]; 7706 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol( 7707 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7708 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7709 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7710 .addSym(FrameAllocSym) 7711 .addFrameIndex(FI); 7712 } 7713 7714 return; 7715 } 7716 7717 case Intrinsic::localrecover: { 7718 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7719 MachineFunction &MF = DAG.getMachineFunction(); 7720 7721 // Get the symbol that defines the frame offset. 7722 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7723 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7724 unsigned IdxVal = 7725 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7726 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol( 7727 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7728 7729 Value *FP = I.getArgOperand(1); 7730 SDValue FPVal = getValue(FP); 7731 EVT PtrVT = FPVal.getValueType(); 7732 7733 // Create a MCSymbol for the label to avoid any target lowering 7734 // that would make this PC relative. 7735 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7736 SDValue OffsetVal = 7737 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7738 7739 // Add the offset to the FP. 7740 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7741 setValue(&I, Add); 7742 7743 return; 7744 } 7745 7746 case Intrinsic::fake_use: { 7747 Value *V = I.getArgOperand(0); 7748 SDValue Ops[2]; 7749 // For Values not declared or previously used in this basic block, the 7750 // NodeMap will not have an entry, and `getValue` will assert if V has no 7751 // valid register value. 7752 auto FakeUseValue = [&]() -> SDValue { 7753 SDValue &N = NodeMap[V]; 7754 if (N.getNode()) 7755 return N; 7756 7757 // If there's a virtual register allocated and initialized for this 7758 // value, use it. 7759 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 7760 return copyFromReg; 7761 // FIXME: Do we want to preserve constants? It seems pointless. 7762 if (isa<Constant>(V)) 7763 return getValue(V); 7764 return SDValue(); 7765 }(); 7766 if (!FakeUseValue || FakeUseValue.isUndef()) 7767 return; 7768 Ops[0] = getRoot(); 7769 Ops[1] = FakeUseValue; 7770 // Also, do not translate a fake use with an undef operand, or any other 7771 // empty SDValues. 7772 if (!Ops[1] || Ops[1].isUndef()) 7773 return; 7774 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops)); 7775 return; 7776 } 7777 7778 case Intrinsic::eh_exceptionpointer: 7779 case Intrinsic::eh_exceptioncode: { 7780 // Get the exception pointer vreg, copy from it, and resize it to fit. 7781 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7782 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7783 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7784 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7785 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7786 if (Intrinsic == Intrinsic::eh_exceptioncode) 7787 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7788 setValue(&I, N); 7789 return; 7790 } 7791 case Intrinsic::xray_customevent: { 7792 // Here we want to make sure that the intrinsic behaves as if it has a 7793 // specific calling convention. 7794 const auto &Triple = DAG.getTarget().getTargetTriple(); 7795 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7796 return; 7797 7798 SmallVector<SDValue, 8> Ops; 7799 7800 // We want to say that we always want the arguments in registers. 7801 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7802 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7803 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7804 SDValue Chain = getRoot(); 7805 Ops.push_back(LogEntryVal); 7806 Ops.push_back(StrSizeVal); 7807 Ops.push_back(Chain); 7808 7809 // We need to enforce the calling convention for the callsite, so that 7810 // argument ordering is enforced correctly, and that register allocation can 7811 // see that some registers may be assumed clobbered and have to preserve 7812 // them across calls to the intrinsic. 7813 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7814 sdl, NodeTys, Ops); 7815 SDValue patchableNode = SDValue(MN, 0); 7816 DAG.setRoot(patchableNode); 7817 setValue(&I, patchableNode); 7818 return; 7819 } 7820 case Intrinsic::xray_typedevent: { 7821 // Here we want to make sure that the intrinsic behaves as if it has a 7822 // specific calling convention. 7823 const auto &Triple = DAG.getTarget().getTargetTriple(); 7824 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7825 return; 7826 7827 SmallVector<SDValue, 8> Ops; 7828 7829 // We want to say that we always want the arguments in registers. 7830 // It's unclear to me how manipulating the selection DAG here forces callers 7831 // to provide arguments in registers instead of on the stack. 7832 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7833 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7834 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7835 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7836 SDValue Chain = getRoot(); 7837 Ops.push_back(LogTypeId); 7838 Ops.push_back(LogEntryVal); 7839 Ops.push_back(StrSizeVal); 7840 Ops.push_back(Chain); 7841 7842 // We need to enforce the calling convention for the callsite, so that 7843 // argument ordering is enforced correctly, and that register allocation can 7844 // see that some registers may be assumed clobbered and have to preserve 7845 // them across calls to the intrinsic. 7846 MachineSDNode *MN = DAG.getMachineNode( 7847 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7848 SDValue patchableNode = SDValue(MN, 0); 7849 DAG.setRoot(patchableNode); 7850 setValue(&I, patchableNode); 7851 return; 7852 } 7853 case Intrinsic::experimental_deoptimize: 7854 LowerDeoptimizeCall(&I); 7855 return; 7856 case Intrinsic::stepvector: 7857 visitStepVector(I); 7858 return; 7859 case Intrinsic::vector_reduce_fadd: 7860 case Intrinsic::vector_reduce_fmul: 7861 case Intrinsic::vector_reduce_add: 7862 case Intrinsic::vector_reduce_mul: 7863 case Intrinsic::vector_reduce_and: 7864 case Intrinsic::vector_reduce_or: 7865 case Intrinsic::vector_reduce_xor: 7866 case Intrinsic::vector_reduce_smax: 7867 case Intrinsic::vector_reduce_smin: 7868 case Intrinsic::vector_reduce_umax: 7869 case Intrinsic::vector_reduce_umin: 7870 case Intrinsic::vector_reduce_fmax: 7871 case Intrinsic::vector_reduce_fmin: 7872 case Intrinsic::vector_reduce_fmaximum: 7873 case Intrinsic::vector_reduce_fminimum: 7874 visitVectorReduce(I, Intrinsic); 7875 return; 7876 7877 case Intrinsic::icall_branch_funnel: { 7878 SmallVector<SDValue, 16> Ops; 7879 Ops.push_back(getValue(I.getArgOperand(0))); 7880 7881 int64_t Offset; 7882 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7883 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7884 if (!Base) 7885 report_fatal_error( 7886 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7887 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7888 7889 struct BranchFunnelTarget { 7890 int64_t Offset; 7891 SDValue Target; 7892 }; 7893 SmallVector<BranchFunnelTarget, 8> Targets; 7894 7895 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7896 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7897 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7898 if (ElemBase != Base) 7899 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7900 "to the same GlobalValue"); 7901 7902 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7903 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7904 if (!GA) 7905 report_fatal_error( 7906 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7907 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7908 GA->getGlobal(), sdl, Val.getValueType(), 7909 GA->getOffset())}); 7910 } 7911 llvm::sort(Targets, 7912 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7913 return T1.Offset < T2.Offset; 7914 }); 7915 7916 for (auto &T : Targets) { 7917 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7918 Ops.push_back(T.Target); 7919 } 7920 7921 Ops.push_back(DAG.getRoot()); // Chain 7922 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7923 MVT::Other, Ops), 7924 0); 7925 DAG.setRoot(N); 7926 setValue(&I, N); 7927 HasTailCall = true; 7928 return; 7929 } 7930 7931 case Intrinsic::wasm_landingpad_index: 7932 // Information this intrinsic contained has been transferred to 7933 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7934 // delete it now. 7935 return; 7936 7937 case Intrinsic::aarch64_settag: 7938 case Intrinsic::aarch64_settag_zero: { 7939 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7940 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7941 SDValue Val = TSI.EmitTargetCodeForSetTag( 7942 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7943 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7944 ZeroMemory); 7945 DAG.setRoot(Val); 7946 setValue(&I, Val); 7947 return; 7948 } 7949 case Intrinsic::amdgcn_cs_chain: { 7950 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7951 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7952 "Non-zero flags not supported yet"); 7953 7954 // At this point we don't care if it's amdgpu_cs_chain or 7955 // amdgpu_cs_chain_preserve. 7956 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7957 7958 Type *RetTy = I.getType(); 7959 assert(RetTy->isVoidTy() && "Should not return"); 7960 7961 SDValue Callee = getValue(I.getOperand(0)); 7962 7963 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7964 // We'll also tack the value of the EXEC mask at the end. 7965 TargetLowering::ArgListTy Args; 7966 Args.reserve(3); 7967 7968 for (unsigned Idx : {2, 3, 1}) { 7969 TargetLowering::ArgListEntry Arg; 7970 Arg.Node = getValue(I.getOperand(Idx)); 7971 Arg.Ty = I.getOperand(Idx)->getType(); 7972 Arg.setAttributes(&I, Idx); 7973 Args.push_back(Arg); 7974 } 7975 7976 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7977 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7978 Args[2].IsInReg = true; // EXEC should be inreg 7979 7980 TargetLowering::CallLoweringInfo CLI(DAG); 7981 CLI.setDebugLoc(getCurSDLoc()) 7982 .setChain(getRoot()) 7983 .setCallee(CC, RetTy, Callee, std::move(Args)) 7984 .setNoReturn(true) 7985 .setTailCall(true) 7986 .setConvergent(I.isConvergent()); 7987 CLI.CB = &I; 7988 std::pair<SDValue, SDValue> Result = 7989 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7990 (void)Result; 7991 assert(!Result.first.getNode() && !Result.second.getNode() && 7992 "Should've lowered as tail call"); 7993 7994 HasTailCall = true; 7995 return; 7996 } 7997 case Intrinsic::ptrmask: { 7998 SDValue Ptr = getValue(I.getOperand(0)); 7999 SDValue Mask = getValue(I.getOperand(1)); 8000 8001 // On arm64_32, pointers are 32 bits when stored in memory, but 8002 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to 8003 // match the index type, but the pointer is 64 bits, so the the mask must be 8004 // zero-extended up to 64 bits to match the pointer. 8005 EVT PtrVT = 8006 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 8007 EVT MemVT = 8008 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 8009 assert(PtrVT == Ptr.getValueType()); 8010 assert(MemVT == Mask.getValueType()); 8011 if (MemVT != PtrVT) 8012 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT); 8013 8014 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 8015 return; 8016 } 8017 case Intrinsic::threadlocal_address: { 8018 setValue(&I, getValue(I.getOperand(0))); 8019 return; 8020 } 8021 case Intrinsic::get_active_lane_mask: { 8022 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8023 SDValue Index = getValue(I.getOperand(0)); 8024 EVT ElementVT = Index.getValueType(); 8025 8026 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 8027 visitTargetIntrinsic(I, Intrinsic); 8028 return; 8029 } 8030 8031 SDValue TripCount = getValue(I.getOperand(1)); 8032 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 8033 CCVT.getVectorElementCount()); 8034 8035 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 8036 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 8037 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 8038 SDValue VectorInduction = DAG.getNode( 8039 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 8040 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 8041 VectorTripCount, ISD::CondCode::SETULT); 8042 setValue(&I, SetCC); 8043 return; 8044 } 8045 case Intrinsic::experimental_get_vector_length: { 8046 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 8047 "Expected positive VF"); 8048 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 8049 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 8050 8051 SDValue Count = getValue(I.getOperand(0)); 8052 EVT CountVT = Count.getValueType(); 8053 8054 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 8055 visitTargetIntrinsic(I, Intrinsic); 8056 return; 8057 } 8058 8059 // Expand to a umin between the trip count and the maximum elements the type 8060 // can hold. 8061 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8062 8063 // Extend the trip count to at least the result VT. 8064 if (CountVT.bitsLT(VT)) { 8065 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 8066 CountVT = VT; 8067 } 8068 8069 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 8070 ElementCount::get(VF, IsScalable)); 8071 8072 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 8073 // Clip to the result type if needed. 8074 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 8075 8076 setValue(&I, Trunc); 8077 return; 8078 } 8079 case Intrinsic::experimental_vector_partial_reduce_add: { 8080 8081 if (!TLI.shouldExpandPartialReductionIntrinsic(cast<IntrinsicInst>(&I))) { 8082 visitTargetIntrinsic(I, Intrinsic); 8083 return; 8084 } 8085 8086 setValue(&I, DAG.getPartialReduceAdd(sdl, EVT::getEVT(I.getType()), 8087 getValue(I.getOperand(0)), 8088 getValue(I.getOperand(1)))); 8089 return; 8090 } 8091 case Intrinsic::experimental_cttz_elts: { 8092 auto DL = getCurSDLoc(); 8093 SDValue Op = getValue(I.getOperand(0)); 8094 EVT OpVT = Op.getValueType(); 8095 8096 if (!TLI.shouldExpandCttzElements(OpVT)) { 8097 visitTargetIntrinsic(I, Intrinsic); 8098 return; 8099 } 8100 8101 if (OpVT.getScalarType() != MVT::i1) { 8102 // Compare the input vector elements to zero & use to count trailing zeros 8103 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 8104 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 8105 OpVT.getVectorElementCount()); 8106 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 8107 } 8108 8109 // If the zero-is-poison flag is set, we can assume the upper limit 8110 // of the result is VF-1. 8111 bool ZeroIsPoison = 8112 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero(); 8113 ConstantRange VScaleRange(1, true); // Dummy value. 8114 if (isa<ScalableVectorType>(I.getOperand(0)->getType())) 8115 VScaleRange = getVScaleRange(I.getCaller(), 64); 8116 unsigned EltWidth = TLI.getBitWidthForCttzElements( 8117 I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange); 8118 8119 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 8120 8121 // Create the new vector type & get the vector length 8122 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 8123 OpVT.getVectorElementCount()); 8124 8125 SDValue VL = 8126 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 8127 8128 SDValue StepVec = DAG.getStepVector(DL, NewVT); 8129 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 8130 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 8131 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 8132 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 8133 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 8134 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 8135 8136 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8137 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 8138 8139 setValue(&I, Ret); 8140 return; 8141 } 8142 case Intrinsic::vector_insert: { 8143 SDValue Vec = getValue(I.getOperand(0)); 8144 SDValue SubVec = getValue(I.getOperand(1)); 8145 SDValue Index = getValue(I.getOperand(2)); 8146 8147 // The intrinsic's index type is i64, but the SDNode requires an index type 8148 // suitable for the target. Convert the index as required. 8149 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8150 if (Index.getValueType() != VectorIdxTy) 8151 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 8152 8153 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8154 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 8155 Index)); 8156 return; 8157 } 8158 case Intrinsic::vector_extract: { 8159 SDValue Vec = getValue(I.getOperand(0)); 8160 SDValue Index = getValue(I.getOperand(1)); 8161 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8162 8163 // The intrinsic's index type is i64, but the SDNode requires an index type 8164 // suitable for the target. Convert the index as required. 8165 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8166 if (Index.getValueType() != VectorIdxTy) 8167 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 8168 8169 setValue(&I, 8170 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 8171 return; 8172 } 8173 case Intrinsic::vector_reverse: 8174 visitVectorReverse(I); 8175 return; 8176 case Intrinsic::vector_splice: 8177 visitVectorSplice(I); 8178 return; 8179 case Intrinsic::callbr_landingpad: 8180 visitCallBrLandingPad(I); 8181 return; 8182 case Intrinsic::vector_interleave2: 8183 visitVectorInterleave(I); 8184 return; 8185 case Intrinsic::vector_deinterleave2: 8186 visitVectorDeinterleave(I); 8187 return; 8188 case Intrinsic::experimental_vector_compress: 8189 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl, 8190 getValue(I.getArgOperand(0)).getValueType(), 8191 getValue(I.getArgOperand(0)), 8192 getValue(I.getArgOperand(1)), 8193 getValue(I.getArgOperand(2)), Flags)); 8194 return; 8195 case Intrinsic::experimental_convergence_anchor: 8196 case Intrinsic::experimental_convergence_entry: 8197 case Intrinsic::experimental_convergence_loop: 8198 visitConvergenceControl(I, Intrinsic); 8199 return; 8200 case Intrinsic::experimental_vector_histogram_add: { 8201 visitVectorHistogram(I, Intrinsic); 8202 return; 8203 } 8204 } 8205 } 8206 8207 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 8208 const ConstrainedFPIntrinsic &FPI) { 8209 SDLoc sdl = getCurSDLoc(); 8210 8211 // We do not need to serialize constrained FP intrinsics against 8212 // each other or against (nonvolatile) loads, so they can be 8213 // chained like loads. 8214 SDValue Chain = DAG.getRoot(); 8215 SmallVector<SDValue, 4> Opers; 8216 Opers.push_back(Chain); 8217 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I) 8218 Opers.push_back(getValue(FPI.getArgOperand(I))); 8219 8220 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 8221 assert(Result.getNode()->getNumValues() == 2); 8222 8223 // Push node to the appropriate list so that future instructions can be 8224 // chained up correctly. 8225 SDValue OutChain = Result.getValue(1); 8226 switch (EB) { 8227 case fp::ExceptionBehavior::ebIgnore: 8228 // The only reason why ebIgnore nodes still need to be chained is that 8229 // they might depend on the current rounding mode, and therefore must 8230 // not be moved across instruction that may change that mode. 8231 [[fallthrough]]; 8232 case fp::ExceptionBehavior::ebMayTrap: 8233 // These must not be moved across calls or instructions that may change 8234 // floating-point exception masks. 8235 PendingConstrainedFP.push_back(OutChain); 8236 break; 8237 case fp::ExceptionBehavior::ebStrict: 8238 // These must not be moved across calls or instructions that may change 8239 // floating-point exception masks or read floating-point exception flags. 8240 // In addition, they cannot be optimized out even if unused. 8241 PendingConstrainedFPStrict.push_back(OutChain); 8242 break; 8243 } 8244 }; 8245 8246 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8247 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 8248 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 8249 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 8250 8251 SDNodeFlags Flags; 8252 if (EB == fp::ExceptionBehavior::ebIgnore) 8253 Flags.setNoFPExcept(true); 8254 8255 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 8256 Flags.copyFMF(*FPOp); 8257 8258 unsigned Opcode; 8259 switch (FPI.getIntrinsicID()) { 8260 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8261 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8262 case Intrinsic::INTRINSIC: \ 8263 Opcode = ISD::STRICT_##DAGN; \ 8264 break; 8265 #include "llvm/IR/ConstrainedOps.def" 8266 case Intrinsic::experimental_constrained_fmuladd: { 8267 Opcode = ISD::STRICT_FMA; 8268 // Break fmuladd into fmul and fadd. 8269 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 8270 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 8271 Opers.pop_back(); 8272 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 8273 pushOutChain(Mul, EB); 8274 Opcode = ISD::STRICT_FADD; 8275 Opers.clear(); 8276 Opers.push_back(Mul.getValue(1)); 8277 Opers.push_back(Mul.getValue(0)); 8278 Opers.push_back(getValue(FPI.getArgOperand(2))); 8279 } 8280 break; 8281 } 8282 } 8283 8284 // A few strict DAG nodes carry additional operands that are not 8285 // set up by the default code above. 8286 switch (Opcode) { 8287 default: break; 8288 case ISD::STRICT_FP_ROUND: 8289 Opers.push_back( 8290 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 8291 break; 8292 case ISD::STRICT_FSETCC: 8293 case ISD::STRICT_FSETCCS: { 8294 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 8295 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 8296 if (TM.Options.NoNaNsFPMath) 8297 Condition = getFCmpCodeWithoutNaN(Condition); 8298 Opers.push_back(DAG.getCondCode(Condition)); 8299 break; 8300 } 8301 } 8302 8303 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 8304 pushOutChain(Result, EB); 8305 8306 SDValue FPResult = Result.getValue(0); 8307 setValue(&FPI, FPResult); 8308 } 8309 8310 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 8311 std::optional<unsigned> ResOPC; 8312 switch (VPIntrin.getIntrinsicID()) { 8313 case Intrinsic::vp_ctlz: { 8314 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8315 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 8316 break; 8317 } 8318 case Intrinsic::vp_cttz: { 8319 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8320 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 8321 break; 8322 } 8323 case Intrinsic::vp_cttz_elts: { 8324 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8325 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS; 8326 break; 8327 } 8328 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 8329 case Intrinsic::VPID: \ 8330 ResOPC = ISD::VPSD; \ 8331 break; 8332 #include "llvm/IR/VPIntrinsics.def" 8333 } 8334 8335 if (!ResOPC) 8336 llvm_unreachable( 8337 "Inconsistency: no SDNode available for this VPIntrinsic!"); 8338 8339 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 8340 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 8341 if (VPIntrin.getFastMathFlags().allowReassoc()) 8342 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 8343 : ISD::VP_REDUCE_FMUL; 8344 } 8345 8346 return *ResOPC; 8347 } 8348 8349 void SelectionDAGBuilder::visitVPLoad( 8350 const VPIntrinsic &VPIntrin, EVT VT, 8351 const SmallVectorImpl<SDValue> &OpValues) { 8352 SDLoc DL = getCurSDLoc(); 8353 Value *PtrOperand = VPIntrin.getArgOperand(0); 8354 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8355 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8356 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8357 SDValue LD; 8358 // Do not serialize variable-length loads of constant memory with 8359 // anything. 8360 if (!Alignment) 8361 Alignment = DAG.getEVTAlign(VT); 8362 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8363 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8364 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8365 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8366 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8367 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8368 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 8369 MMO, false /*IsExpanding */); 8370 if (AddToChain) 8371 PendingLoads.push_back(LD.getValue(1)); 8372 setValue(&VPIntrin, LD); 8373 } 8374 8375 void SelectionDAGBuilder::visitVPGather( 8376 const VPIntrinsic &VPIntrin, EVT VT, 8377 const SmallVectorImpl<SDValue> &OpValues) { 8378 SDLoc DL = getCurSDLoc(); 8379 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8380 Value *PtrOperand = VPIntrin.getArgOperand(0); 8381 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8382 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8383 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8384 SDValue LD; 8385 if (!Alignment) 8386 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8387 unsigned AS = 8388 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8389 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8390 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8391 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8392 SDValue Base, Index, Scale; 8393 ISD::MemIndexType IndexType; 8394 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8395 this, VPIntrin.getParent(), 8396 VT.getScalarStoreSize()); 8397 if (!UniformBase) { 8398 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8399 Index = getValue(PtrOperand); 8400 IndexType = ISD::SIGNED_SCALED; 8401 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8402 } 8403 EVT IdxVT = Index.getValueType(); 8404 EVT EltTy = IdxVT.getVectorElementType(); 8405 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8406 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8407 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8408 } 8409 LD = DAG.getGatherVP( 8410 DAG.getVTList(VT, MVT::Other), VT, DL, 8411 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 8412 IndexType); 8413 PendingLoads.push_back(LD.getValue(1)); 8414 setValue(&VPIntrin, LD); 8415 } 8416 8417 void SelectionDAGBuilder::visitVPStore( 8418 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8419 SDLoc DL = getCurSDLoc(); 8420 Value *PtrOperand = VPIntrin.getArgOperand(1); 8421 EVT VT = OpValues[0].getValueType(); 8422 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8423 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8424 SDValue ST; 8425 if (!Alignment) 8426 Alignment = DAG.getEVTAlign(VT); 8427 SDValue Ptr = OpValues[1]; 8428 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 8429 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8430 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8431 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8432 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 8433 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 8434 /* IsTruncating */ false, /*IsCompressing*/ false); 8435 DAG.setRoot(ST); 8436 setValue(&VPIntrin, ST); 8437 } 8438 8439 void SelectionDAGBuilder::visitVPScatter( 8440 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8441 SDLoc DL = getCurSDLoc(); 8442 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8443 Value *PtrOperand = VPIntrin.getArgOperand(1); 8444 EVT VT = OpValues[0].getValueType(); 8445 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8446 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8447 SDValue ST; 8448 if (!Alignment) 8449 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8450 unsigned AS = 8451 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8452 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8453 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8454 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8455 SDValue Base, Index, Scale; 8456 ISD::MemIndexType IndexType; 8457 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8458 this, VPIntrin.getParent(), 8459 VT.getScalarStoreSize()); 8460 if (!UniformBase) { 8461 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8462 Index = getValue(PtrOperand); 8463 IndexType = ISD::SIGNED_SCALED; 8464 Scale = 8465 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8466 } 8467 EVT IdxVT = Index.getValueType(); 8468 EVT EltTy = IdxVT.getVectorElementType(); 8469 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8470 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8471 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8472 } 8473 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8474 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8475 OpValues[2], OpValues[3]}, 8476 MMO, IndexType); 8477 DAG.setRoot(ST); 8478 setValue(&VPIntrin, ST); 8479 } 8480 8481 void SelectionDAGBuilder::visitVPStridedLoad( 8482 const VPIntrinsic &VPIntrin, EVT VT, 8483 const SmallVectorImpl<SDValue> &OpValues) { 8484 SDLoc DL = getCurSDLoc(); 8485 Value *PtrOperand = VPIntrin.getArgOperand(0); 8486 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8487 if (!Alignment) 8488 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8489 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8490 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8491 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8492 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8493 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8494 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8495 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8496 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8497 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8498 8499 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8500 OpValues[2], OpValues[3], MMO, 8501 false /*IsExpanding*/); 8502 8503 if (AddToChain) 8504 PendingLoads.push_back(LD.getValue(1)); 8505 setValue(&VPIntrin, LD); 8506 } 8507 8508 void SelectionDAGBuilder::visitVPStridedStore( 8509 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8510 SDLoc DL = getCurSDLoc(); 8511 Value *PtrOperand = VPIntrin.getArgOperand(1); 8512 EVT VT = OpValues[0].getValueType(); 8513 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8514 if (!Alignment) 8515 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8516 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8517 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8518 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8519 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8520 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8521 8522 SDValue ST = DAG.getStridedStoreVP( 8523 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8524 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8525 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8526 /*IsCompressing*/ false); 8527 8528 DAG.setRoot(ST); 8529 setValue(&VPIntrin, ST); 8530 } 8531 8532 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8533 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8534 SDLoc DL = getCurSDLoc(); 8535 8536 ISD::CondCode Condition; 8537 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8538 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8539 if (IsFP) { 8540 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8541 // flags, but calls that don't return floating-point types can't be 8542 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8543 Condition = getFCmpCondCode(CondCode); 8544 if (TM.Options.NoNaNsFPMath) 8545 Condition = getFCmpCodeWithoutNaN(Condition); 8546 } else { 8547 Condition = getICmpCondCode(CondCode); 8548 } 8549 8550 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8551 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8552 // #2 is the condition code 8553 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8554 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8555 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8556 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8557 "Unexpected target EVL type"); 8558 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8559 8560 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8561 VPIntrin.getType()); 8562 setValue(&VPIntrin, 8563 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8564 } 8565 8566 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8567 const VPIntrinsic &VPIntrin) { 8568 SDLoc DL = getCurSDLoc(); 8569 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8570 8571 auto IID = VPIntrin.getIntrinsicID(); 8572 8573 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8574 return visitVPCmp(*CmpI); 8575 8576 SmallVector<EVT, 4> ValueVTs; 8577 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8578 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8579 SDVTList VTs = DAG.getVTList(ValueVTs); 8580 8581 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8582 8583 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8584 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8585 "Unexpected target EVL type"); 8586 8587 // Request operands. 8588 SmallVector<SDValue, 7> OpValues; 8589 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8590 auto Op = getValue(VPIntrin.getArgOperand(I)); 8591 if (I == EVLParamPos) 8592 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8593 OpValues.push_back(Op); 8594 } 8595 8596 switch (Opcode) { 8597 default: { 8598 SDNodeFlags SDFlags; 8599 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8600 SDFlags.copyFMF(*FPMO); 8601 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8602 setValue(&VPIntrin, Result); 8603 break; 8604 } 8605 case ISD::VP_LOAD: 8606 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8607 break; 8608 case ISD::VP_GATHER: 8609 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8610 break; 8611 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8612 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8613 break; 8614 case ISD::VP_STORE: 8615 visitVPStore(VPIntrin, OpValues); 8616 break; 8617 case ISD::VP_SCATTER: 8618 visitVPScatter(VPIntrin, OpValues); 8619 break; 8620 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8621 visitVPStridedStore(VPIntrin, OpValues); 8622 break; 8623 case ISD::VP_FMULADD: { 8624 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8625 SDNodeFlags SDFlags; 8626 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8627 SDFlags.copyFMF(*FPMO); 8628 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8629 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8630 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8631 } else { 8632 SDValue Mul = DAG.getNode( 8633 ISD::VP_FMUL, DL, VTs, 8634 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8635 SDValue Add = 8636 DAG.getNode(ISD::VP_FADD, DL, VTs, 8637 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8638 setValue(&VPIntrin, Add); 8639 } 8640 break; 8641 } 8642 case ISD::VP_IS_FPCLASS: { 8643 const DataLayout DLayout = DAG.getDataLayout(); 8644 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8645 auto Constant = OpValues[1]->getAsZExtVal(); 8646 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8647 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8648 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8649 setValue(&VPIntrin, V); 8650 return; 8651 } 8652 case ISD::VP_INTTOPTR: { 8653 SDValue N = OpValues[0]; 8654 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8655 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8656 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8657 OpValues[2]); 8658 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8659 OpValues[2]); 8660 setValue(&VPIntrin, N); 8661 break; 8662 } 8663 case ISD::VP_PTRTOINT: { 8664 SDValue N = OpValues[0]; 8665 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8666 VPIntrin.getType()); 8667 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8668 VPIntrin.getOperand(0)->getType()); 8669 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8670 OpValues[2]); 8671 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8672 OpValues[2]); 8673 setValue(&VPIntrin, N); 8674 break; 8675 } 8676 case ISD::VP_ABS: 8677 case ISD::VP_CTLZ: 8678 case ISD::VP_CTLZ_ZERO_UNDEF: 8679 case ISD::VP_CTTZ: 8680 case ISD::VP_CTTZ_ZERO_UNDEF: 8681 case ISD::VP_CTTZ_ELTS_ZERO_UNDEF: 8682 case ISD::VP_CTTZ_ELTS: { 8683 SDValue Result = 8684 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8685 setValue(&VPIntrin, Result); 8686 break; 8687 } 8688 } 8689 } 8690 8691 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8692 const BasicBlock *EHPadBB, 8693 MCSymbol *&BeginLabel) { 8694 MachineFunction &MF = DAG.getMachineFunction(); 8695 8696 // Insert a label before the invoke call to mark the try range. This can be 8697 // used to detect deletion of the invoke via the MachineModuleInfo. 8698 BeginLabel = MF.getContext().createTempSymbol(); 8699 8700 // For SjLj, keep track of which landing pads go with which invokes 8701 // so as to maintain the ordering of pads in the LSDA. 8702 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite(); 8703 if (CallSiteIndex) { 8704 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8705 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex); 8706 8707 // Now that the call site is handled, stop tracking it. 8708 FuncInfo.setCurrentCallSite(0); 8709 } 8710 8711 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8712 } 8713 8714 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8715 const BasicBlock *EHPadBB, 8716 MCSymbol *BeginLabel) { 8717 assert(BeginLabel && "BeginLabel should've been set"); 8718 8719 MachineFunction &MF = DAG.getMachineFunction(); 8720 8721 // Insert a label at the end of the invoke call to mark the try range. This 8722 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8723 MCSymbol *EndLabel = MF.getContext().createTempSymbol(); 8724 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8725 8726 // Inform MachineModuleInfo of range. 8727 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8728 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8729 // actually use outlined funclets and their LSDA info style. 8730 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8731 assert(II && "II should've been set"); 8732 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8733 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8734 } else if (!isScopedEHPersonality(Pers)) { 8735 assert(EHPadBB); 8736 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel); 8737 } 8738 8739 return Chain; 8740 } 8741 8742 std::pair<SDValue, SDValue> 8743 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8744 const BasicBlock *EHPadBB) { 8745 MCSymbol *BeginLabel = nullptr; 8746 8747 if (EHPadBB) { 8748 // Both PendingLoads and PendingExports must be flushed here; 8749 // this call might not return. 8750 (void)getRoot(); 8751 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8752 CLI.setChain(getRoot()); 8753 } 8754 8755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8756 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8757 8758 assert((CLI.IsTailCall || Result.second.getNode()) && 8759 "Non-null chain expected with non-tail call!"); 8760 assert((Result.second.getNode() || !Result.first.getNode()) && 8761 "Null value expected with tail call!"); 8762 8763 if (!Result.second.getNode()) { 8764 // As a special case, a null chain means that a tail call has been emitted 8765 // and the DAG root is already updated. 8766 HasTailCall = true; 8767 8768 // Since there's no actual continuation from this block, nothing can be 8769 // relying on us setting vregs for them. 8770 PendingExports.clear(); 8771 } else { 8772 DAG.setRoot(Result.second); 8773 } 8774 8775 if (EHPadBB) { 8776 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8777 BeginLabel)); 8778 Result.second = getRoot(); 8779 } 8780 8781 return Result; 8782 } 8783 8784 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8785 bool isTailCall, bool isMustTailCall, 8786 const BasicBlock *EHPadBB, 8787 const TargetLowering::PtrAuthInfo *PAI) { 8788 auto &DL = DAG.getDataLayout(); 8789 FunctionType *FTy = CB.getFunctionType(); 8790 Type *RetTy = CB.getType(); 8791 8792 TargetLowering::ArgListTy Args; 8793 Args.reserve(CB.arg_size()); 8794 8795 const Value *SwiftErrorVal = nullptr; 8796 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8797 8798 if (isTailCall) { 8799 // Avoid emitting tail calls in functions with the disable-tail-calls 8800 // attribute. 8801 auto *Caller = CB.getParent()->getParent(); 8802 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8803 "true" && !isMustTailCall) 8804 isTailCall = false; 8805 8806 // We can't tail call inside a function with a swifterror argument. Lowering 8807 // does not support this yet. It would have to move into the swifterror 8808 // register before the call. 8809 if (TLI.supportSwiftError() && 8810 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8811 isTailCall = false; 8812 } 8813 8814 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8815 TargetLowering::ArgListEntry Entry; 8816 const Value *V = *I; 8817 8818 // Skip empty types 8819 if (V->getType()->isEmptyTy()) 8820 continue; 8821 8822 SDValue ArgNode = getValue(V); 8823 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8824 8825 Entry.setAttributes(&CB, I - CB.arg_begin()); 8826 8827 // Use swifterror virtual register as input to the call. 8828 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8829 SwiftErrorVal = V; 8830 // We find the virtual register for the actual swifterror argument. 8831 // Instead of using the Value, we use the virtual register instead. 8832 Entry.Node = 8833 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8834 EVT(TLI.getPointerTy(DL))); 8835 } 8836 8837 Args.push_back(Entry); 8838 8839 // If we have an explicit sret argument that is an Instruction, (i.e., it 8840 // might point to function-local memory), we can't meaningfully tail-call. 8841 if (Entry.IsSRet && isa<Instruction>(V)) 8842 isTailCall = false; 8843 } 8844 8845 // If call site has a cfguardtarget operand bundle, create and add an 8846 // additional ArgListEntry. 8847 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8848 TargetLowering::ArgListEntry Entry; 8849 Value *V = Bundle->Inputs[0]; 8850 SDValue ArgNode = getValue(V); 8851 Entry.Node = ArgNode; 8852 Entry.Ty = V->getType(); 8853 Entry.IsCFGuardTarget = true; 8854 Args.push_back(Entry); 8855 } 8856 8857 // Check if target-independent constraints permit a tail call here. 8858 // Target-dependent constraints are checked within TLI->LowerCallTo. 8859 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8860 isTailCall = false; 8861 8862 // Disable tail calls if there is an swifterror argument. Targets have not 8863 // been updated to support tail calls. 8864 if (TLI.supportSwiftError() && SwiftErrorVal) 8865 isTailCall = false; 8866 8867 ConstantInt *CFIType = nullptr; 8868 if (CB.isIndirectCall()) { 8869 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8870 if (!TLI.supportKCFIBundles()) 8871 report_fatal_error( 8872 "Target doesn't support calls with kcfi operand bundles."); 8873 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8874 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8875 } 8876 } 8877 8878 SDValue ConvControlToken; 8879 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) { 8880 auto *Token = Bundle->Inputs[0].get(); 8881 ConvControlToken = getValue(Token); 8882 } 8883 8884 TargetLowering::CallLoweringInfo CLI(DAG); 8885 CLI.setDebugLoc(getCurSDLoc()) 8886 .setChain(getRoot()) 8887 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8888 .setTailCall(isTailCall) 8889 .setConvergent(CB.isConvergent()) 8890 .setIsPreallocated( 8891 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8892 .setCFIType(CFIType) 8893 .setConvergenceControlToken(ConvControlToken); 8894 8895 // Set the pointer authentication info if we have it. 8896 if (PAI) { 8897 if (!TLI.supportPtrAuthBundles()) 8898 report_fatal_error( 8899 "This target doesn't support calls with ptrauth operand bundles."); 8900 CLI.setPtrAuth(*PAI); 8901 } 8902 8903 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8904 8905 if (Result.first.getNode()) { 8906 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8907 setValue(&CB, Result.first); 8908 } 8909 8910 // The last element of CLI.InVals has the SDValue for swifterror return. 8911 // Here we copy it to a virtual register and update SwiftErrorMap for 8912 // book-keeping. 8913 if (SwiftErrorVal && TLI.supportSwiftError()) { 8914 // Get the last element of InVals. 8915 SDValue Src = CLI.InVals.back(); 8916 Register VReg = 8917 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8918 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8919 DAG.setRoot(CopyNode); 8920 } 8921 } 8922 8923 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8924 SelectionDAGBuilder &Builder) { 8925 // Check to see if this load can be trivially constant folded, e.g. if the 8926 // input is from a string literal. 8927 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8928 // Cast pointer to the type we really want to load. 8929 Type *LoadTy = 8930 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8931 if (LoadVT.isVector()) 8932 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8933 8934 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8935 PointerType::getUnqual(LoadTy)); 8936 8937 if (const Constant *LoadCst = 8938 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8939 LoadTy, Builder.DAG.getDataLayout())) 8940 return Builder.getValue(LoadCst); 8941 } 8942 8943 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8944 // still constant memory, the input chain can be the entry node. 8945 SDValue Root; 8946 bool ConstantMemory = false; 8947 8948 // Do not serialize (non-volatile) loads of constant memory with anything. 8949 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8950 Root = Builder.DAG.getEntryNode(); 8951 ConstantMemory = true; 8952 } else { 8953 // Do not serialize non-volatile loads against each other. 8954 Root = Builder.DAG.getRoot(); 8955 } 8956 8957 SDValue Ptr = Builder.getValue(PtrVal); 8958 SDValue LoadVal = 8959 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8960 MachinePointerInfo(PtrVal), Align(1)); 8961 8962 if (!ConstantMemory) 8963 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8964 return LoadVal; 8965 } 8966 8967 /// Record the value for an instruction that produces an integer result, 8968 /// converting the type where necessary. 8969 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8970 SDValue Value, 8971 bool IsSigned) { 8972 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8973 I.getType(), true); 8974 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8975 setValue(&I, Value); 8976 } 8977 8978 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8979 /// true and lower it. Otherwise return false, and it will be lowered like a 8980 /// normal call. 8981 /// The caller already checked that \p I calls the appropriate LibFunc with a 8982 /// correct prototype. 8983 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8984 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8985 const Value *Size = I.getArgOperand(2); 8986 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8987 if (CSize && CSize->getZExtValue() == 0) { 8988 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8989 I.getType(), true); 8990 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8991 return true; 8992 } 8993 8994 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8995 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8996 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8997 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8998 if (Res.first.getNode()) { 8999 processIntegerCallValue(I, Res.first, true); 9000 PendingLoads.push_back(Res.second); 9001 return true; 9002 } 9003 9004 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 9005 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 9006 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 9007 return false; 9008 9009 // If the target has a fast compare for the given size, it will return a 9010 // preferred load type for that size. Require that the load VT is legal and 9011 // that the target supports unaligned loads of that type. Otherwise, return 9012 // INVALID. 9013 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 9014 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9015 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 9016 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 9017 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 9018 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 9019 // TODO: Check alignment of src and dest ptrs. 9020 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 9021 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 9022 if (!TLI.isTypeLegal(LVT) || 9023 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 9024 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 9025 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 9026 } 9027 9028 return LVT; 9029 }; 9030 9031 // This turns into unaligned loads. We only do this if the target natively 9032 // supports the MVT we'll be loading or if it is small enough (<= 4) that 9033 // we'll only produce a small number of byte loads. 9034 MVT LoadVT; 9035 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 9036 switch (NumBitsToCompare) { 9037 default: 9038 return false; 9039 case 16: 9040 LoadVT = MVT::i16; 9041 break; 9042 case 32: 9043 LoadVT = MVT::i32; 9044 break; 9045 case 64: 9046 case 128: 9047 case 256: 9048 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 9049 break; 9050 } 9051 9052 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 9053 return false; 9054 9055 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 9056 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 9057 9058 // Bitcast to a wide integer type if the loads are vectors. 9059 if (LoadVT.isVector()) { 9060 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 9061 LoadL = DAG.getBitcast(CmpVT, LoadL); 9062 LoadR = DAG.getBitcast(CmpVT, LoadR); 9063 } 9064 9065 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 9066 processIntegerCallValue(I, Cmp, false); 9067 return true; 9068 } 9069 9070 /// See if we can lower a memchr call into an optimized form. If so, return 9071 /// true and lower it. Otherwise return false, and it will be lowered like a 9072 /// normal call. 9073 /// The caller already checked that \p I calls the appropriate LibFunc with a 9074 /// correct prototype. 9075 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 9076 const Value *Src = I.getArgOperand(0); 9077 const Value *Char = I.getArgOperand(1); 9078 const Value *Length = I.getArgOperand(2); 9079 9080 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9081 std::pair<SDValue, SDValue> Res = 9082 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 9083 getValue(Src), getValue(Char), getValue(Length), 9084 MachinePointerInfo(Src)); 9085 if (Res.first.getNode()) { 9086 setValue(&I, Res.first); 9087 PendingLoads.push_back(Res.second); 9088 return true; 9089 } 9090 9091 return false; 9092 } 9093 9094 /// See if we can lower a mempcpy call into an optimized form. If so, return 9095 /// true and lower it. Otherwise return false, and it will be lowered like a 9096 /// normal call. 9097 /// The caller already checked that \p I calls the appropriate LibFunc with a 9098 /// correct prototype. 9099 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 9100 SDValue Dst = getValue(I.getArgOperand(0)); 9101 SDValue Src = getValue(I.getArgOperand(1)); 9102 SDValue Size = getValue(I.getArgOperand(2)); 9103 9104 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 9105 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 9106 // DAG::getMemcpy needs Alignment to be defined. 9107 Align Alignment = std::min(DstAlign, SrcAlign); 9108 9109 SDLoc sdl = getCurSDLoc(); 9110 9111 // In the mempcpy context we need to pass in a false value for isTailCall 9112 // because the return pointer needs to be adjusted by the size of 9113 // the copied memory. 9114 SDValue Root = getMemoryRoot(); 9115 SDValue MC = DAG.getMemcpy( 9116 Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr, 9117 std::nullopt, MachinePointerInfo(I.getArgOperand(0)), 9118 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata()); 9119 assert(MC.getNode() != nullptr && 9120 "** memcpy should not be lowered as TailCall in mempcpy context **"); 9121 DAG.setRoot(MC); 9122 9123 // Check if Size needs to be truncated or extended. 9124 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 9125 9126 // Adjust return pointer to point just past the last dst byte. 9127 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 9128 Dst, Size); 9129 setValue(&I, DstPlusSize); 9130 return true; 9131 } 9132 9133 /// See if we can lower a strcpy call into an optimized form. If so, return 9134 /// true and lower it, otherwise return false and it will be lowered like a 9135 /// normal call. 9136 /// The caller already checked that \p I calls the appropriate LibFunc with a 9137 /// correct prototype. 9138 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 9139 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9140 9141 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9142 std::pair<SDValue, SDValue> Res = 9143 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 9144 getValue(Arg0), getValue(Arg1), 9145 MachinePointerInfo(Arg0), 9146 MachinePointerInfo(Arg1), isStpcpy); 9147 if (Res.first.getNode()) { 9148 setValue(&I, Res.first); 9149 DAG.setRoot(Res.second); 9150 return true; 9151 } 9152 9153 return false; 9154 } 9155 9156 /// See if we can lower a strcmp call into an optimized form. If so, return 9157 /// true and lower it, otherwise return false and it will be lowered like a 9158 /// normal call. 9159 /// The caller already checked that \p I calls the appropriate LibFunc with a 9160 /// correct prototype. 9161 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 9162 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9163 9164 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9165 std::pair<SDValue, SDValue> Res = 9166 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 9167 getValue(Arg0), getValue(Arg1), 9168 MachinePointerInfo(Arg0), 9169 MachinePointerInfo(Arg1)); 9170 if (Res.first.getNode()) { 9171 processIntegerCallValue(I, Res.first, true); 9172 PendingLoads.push_back(Res.second); 9173 return true; 9174 } 9175 9176 return false; 9177 } 9178 9179 /// See if we can lower a strlen call into an optimized form. If so, return 9180 /// true and lower it, otherwise return false and it will be lowered like a 9181 /// normal call. 9182 /// The caller already checked that \p I calls the appropriate LibFunc with a 9183 /// correct prototype. 9184 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 9185 const Value *Arg0 = I.getArgOperand(0); 9186 9187 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9188 std::pair<SDValue, SDValue> Res = 9189 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 9190 getValue(Arg0), MachinePointerInfo(Arg0)); 9191 if (Res.first.getNode()) { 9192 processIntegerCallValue(I, Res.first, false); 9193 PendingLoads.push_back(Res.second); 9194 return true; 9195 } 9196 9197 return false; 9198 } 9199 9200 /// See if we can lower a strnlen call into an optimized form. If so, return 9201 /// true and lower it, otherwise return false and it will be lowered like a 9202 /// normal call. 9203 /// The caller already checked that \p I calls the appropriate LibFunc with a 9204 /// correct prototype. 9205 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 9206 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9207 9208 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9209 std::pair<SDValue, SDValue> Res = 9210 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 9211 getValue(Arg0), getValue(Arg1), 9212 MachinePointerInfo(Arg0)); 9213 if (Res.first.getNode()) { 9214 processIntegerCallValue(I, Res.first, false); 9215 PendingLoads.push_back(Res.second); 9216 return true; 9217 } 9218 9219 return false; 9220 } 9221 9222 /// See if we can lower a unary floating-point operation into an SDNode with 9223 /// the specified Opcode. If so, return true and lower it, otherwise return 9224 /// false and it will be lowered like a normal call. 9225 /// The caller already checked that \p I calls the appropriate LibFunc with a 9226 /// correct prototype. 9227 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 9228 unsigned Opcode) { 9229 // We already checked this call's prototype; verify it doesn't modify errno. 9230 if (!I.onlyReadsMemory()) 9231 return false; 9232 9233 SDNodeFlags Flags; 9234 Flags.copyFMF(cast<FPMathOperator>(I)); 9235 9236 SDValue Tmp = getValue(I.getArgOperand(0)); 9237 setValue(&I, 9238 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 9239 return true; 9240 } 9241 9242 /// See if we can lower a binary floating-point operation into an SDNode with 9243 /// the specified Opcode. If so, return true and lower it. Otherwise return 9244 /// false, and it will be lowered like a normal call. 9245 /// The caller already checked that \p I calls the appropriate LibFunc with a 9246 /// correct prototype. 9247 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 9248 unsigned Opcode) { 9249 // We already checked this call's prototype; verify it doesn't modify errno. 9250 if (!I.onlyReadsMemory()) 9251 return false; 9252 9253 SDNodeFlags Flags; 9254 Flags.copyFMF(cast<FPMathOperator>(I)); 9255 9256 SDValue Tmp0 = getValue(I.getArgOperand(0)); 9257 SDValue Tmp1 = getValue(I.getArgOperand(1)); 9258 EVT VT = Tmp0.getValueType(); 9259 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 9260 return true; 9261 } 9262 9263 void SelectionDAGBuilder::visitCall(const CallInst &I) { 9264 // Handle inline assembly differently. 9265 if (I.isInlineAsm()) { 9266 visitInlineAsm(I); 9267 return; 9268 } 9269 9270 diagnoseDontCall(I); 9271 9272 if (Function *F = I.getCalledFunction()) { 9273 if (F->isDeclaration()) { 9274 // Is this an LLVM intrinsic or a target-specific intrinsic? 9275 unsigned IID = F->getIntrinsicID(); 9276 if (!IID) 9277 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 9278 IID = II->getIntrinsicID(F); 9279 9280 if (IID) { 9281 visitIntrinsicCall(I, IID); 9282 return; 9283 } 9284 } 9285 9286 // Check for well-known libc/libm calls. If the function is internal, it 9287 // can't be a library call. Don't do the check if marked as nobuiltin for 9288 // some reason or the call site requires strict floating point semantics. 9289 LibFunc Func; 9290 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 9291 F->hasName() && LibInfo->getLibFunc(*F, Func) && 9292 LibInfo->hasOptimizedCodeGen(Func)) { 9293 switch (Func) { 9294 default: break; 9295 case LibFunc_bcmp: 9296 if (visitMemCmpBCmpCall(I)) 9297 return; 9298 break; 9299 case LibFunc_copysign: 9300 case LibFunc_copysignf: 9301 case LibFunc_copysignl: 9302 // We already checked this call's prototype; verify it doesn't modify 9303 // errno. 9304 if (I.onlyReadsMemory()) { 9305 SDValue LHS = getValue(I.getArgOperand(0)); 9306 SDValue RHS = getValue(I.getArgOperand(1)); 9307 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 9308 LHS.getValueType(), LHS, RHS)); 9309 return; 9310 } 9311 break; 9312 case LibFunc_fabs: 9313 case LibFunc_fabsf: 9314 case LibFunc_fabsl: 9315 if (visitUnaryFloatCall(I, ISD::FABS)) 9316 return; 9317 break; 9318 case LibFunc_fmin: 9319 case LibFunc_fminf: 9320 case LibFunc_fminl: 9321 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 9322 return; 9323 break; 9324 case LibFunc_fmax: 9325 case LibFunc_fmaxf: 9326 case LibFunc_fmaxl: 9327 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 9328 return; 9329 break; 9330 case LibFunc_fminimum_num: 9331 case LibFunc_fminimum_numf: 9332 case LibFunc_fminimum_numl: 9333 if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM)) 9334 return; 9335 break; 9336 case LibFunc_fmaximum_num: 9337 case LibFunc_fmaximum_numf: 9338 case LibFunc_fmaximum_numl: 9339 if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM)) 9340 return; 9341 break; 9342 case LibFunc_sin: 9343 case LibFunc_sinf: 9344 case LibFunc_sinl: 9345 if (visitUnaryFloatCall(I, ISD::FSIN)) 9346 return; 9347 break; 9348 case LibFunc_cos: 9349 case LibFunc_cosf: 9350 case LibFunc_cosl: 9351 if (visitUnaryFloatCall(I, ISD::FCOS)) 9352 return; 9353 break; 9354 case LibFunc_tan: 9355 case LibFunc_tanf: 9356 case LibFunc_tanl: 9357 if (visitUnaryFloatCall(I, ISD::FTAN)) 9358 return; 9359 break; 9360 case LibFunc_asin: 9361 case LibFunc_asinf: 9362 case LibFunc_asinl: 9363 if (visitUnaryFloatCall(I, ISD::FASIN)) 9364 return; 9365 break; 9366 case LibFunc_acos: 9367 case LibFunc_acosf: 9368 case LibFunc_acosl: 9369 if (visitUnaryFloatCall(I, ISD::FACOS)) 9370 return; 9371 break; 9372 case LibFunc_atan: 9373 case LibFunc_atanf: 9374 case LibFunc_atanl: 9375 if (visitUnaryFloatCall(I, ISD::FATAN)) 9376 return; 9377 break; 9378 case LibFunc_atan2: 9379 case LibFunc_atan2f: 9380 case LibFunc_atan2l: 9381 if (visitBinaryFloatCall(I, ISD::FATAN2)) 9382 return; 9383 break; 9384 case LibFunc_sinh: 9385 case LibFunc_sinhf: 9386 case LibFunc_sinhl: 9387 if (visitUnaryFloatCall(I, ISD::FSINH)) 9388 return; 9389 break; 9390 case LibFunc_cosh: 9391 case LibFunc_coshf: 9392 case LibFunc_coshl: 9393 if (visitUnaryFloatCall(I, ISD::FCOSH)) 9394 return; 9395 break; 9396 case LibFunc_tanh: 9397 case LibFunc_tanhf: 9398 case LibFunc_tanhl: 9399 if (visitUnaryFloatCall(I, ISD::FTANH)) 9400 return; 9401 break; 9402 case LibFunc_sqrt: 9403 case LibFunc_sqrtf: 9404 case LibFunc_sqrtl: 9405 case LibFunc_sqrt_finite: 9406 case LibFunc_sqrtf_finite: 9407 case LibFunc_sqrtl_finite: 9408 if (visitUnaryFloatCall(I, ISD::FSQRT)) 9409 return; 9410 break; 9411 case LibFunc_floor: 9412 case LibFunc_floorf: 9413 case LibFunc_floorl: 9414 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 9415 return; 9416 break; 9417 case LibFunc_nearbyint: 9418 case LibFunc_nearbyintf: 9419 case LibFunc_nearbyintl: 9420 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 9421 return; 9422 break; 9423 case LibFunc_ceil: 9424 case LibFunc_ceilf: 9425 case LibFunc_ceill: 9426 if (visitUnaryFloatCall(I, ISD::FCEIL)) 9427 return; 9428 break; 9429 case LibFunc_rint: 9430 case LibFunc_rintf: 9431 case LibFunc_rintl: 9432 if (visitUnaryFloatCall(I, ISD::FRINT)) 9433 return; 9434 break; 9435 case LibFunc_round: 9436 case LibFunc_roundf: 9437 case LibFunc_roundl: 9438 if (visitUnaryFloatCall(I, ISD::FROUND)) 9439 return; 9440 break; 9441 case LibFunc_trunc: 9442 case LibFunc_truncf: 9443 case LibFunc_truncl: 9444 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 9445 return; 9446 break; 9447 case LibFunc_log2: 9448 case LibFunc_log2f: 9449 case LibFunc_log2l: 9450 if (visitUnaryFloatCall(I, ISD::FLOG2)) 9451 return; 9452 break; 9453 case LibFunc_exp2: 9454 case LibFunc_exp2f: 9455 case LibFunc_exp2l: 9456 if (visitUnaryFloatCall(I, ISD::FEXP2)) 9457 return; 9458 break; 9459 case LibFunc_exp10: 9460 case LibFunc_exp10f: 9461 case LibFunc_exp10l: 9462 if (visitUnaryFloatCall(I, ISD::FEXP10)) 9463 return; 9464 break; 9465 case LibFunc_ldexp: 9466 case LibFunc_ldexpf: 9467 case LibFunc_ldexpl: 9468 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 9469 return; 9470 break; 9471 case LibFunc_memcmp: 9472 if (visitMemCmpBCmpCall(I)) 9473 return; 9474 break; 9475 case LibFunc_mempcpy: 9476 if (visitMemPCpyCall(I)) 9477 return; 9478 break; 9479 case LibFunc_memchr: 9480 if (visitMemChrCall(I)) 9481 return; 9482 break; 9483 case LibFunc_strcpy: 9484 if (visitStrCpyCall(I, false)) 9485 return; 9486 break; 9487 case LibFunc_stpcpy: 9488 if (visitStrCpyCall(I, true)) 9489 return; 9490 break; 9491 case LibFunc_strcmp: 9492 if (visitStrCmpCall(I)) 9493 return; 9494 break; 9495 case LibFunc_strlen: 9496 if (visitStrLenCall(I)) 9497 return; 9498 break; 9499 case LibFunc_strnlen: 9500 if (visitStrNLenCall(I)) 9501 return; 9502 break; 9503 } 9504 } 9505 } 9506 9507 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 9508 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr); 9509 return; 9510 } 9511 9512 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9513 // have to do anything here to lower funclet bundles. 9514 // CFGuardTarget bundles are lowered in LowerCallTo. 9515 assert(!I.hasOperandBundlesOtherThan( 9516 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9517 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9518 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi, 9519 LLVMContext::OB_convergencectrl}) && 9520 "Cannot lower calls with arbitrary operand bundles!"); 9521 9522 SDValue Callee = getValue(I.getCalledOperand()); 9523 9524 if (I.hasDeoptState()) 9525 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9526 else 9527 // Check if we can potentially perform a tail call. More detailed checking 9528 // is be done within LowerCallTo, after more information about the call is 9529 // known. 9530 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9531 } 9532 9533 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle( 9534 const CallBase &CB, const BasicBlock *EHPadBB) { 9535 auto PAB = CB.getOperandBundle("ptrauth"); 9536 const Value *CalleeV = CB.getCalledOperand(); 9537 9538 // Gather the call ptrauth data from the operand bundle: 9539 // [ i32 <key>, i64 <discriminator> ] 9540 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]); 9541 const Value *Discriminator = PAB->Inputs[1]; 9542 9543 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key"); 9544 assert(Discriminator->getType()->isIntegerTy(64) && 9545 "Invalid ptrauth discriminator"); 9546 9547 // Look through ptrauth constants to find the raw callee. 9548 // Do a direct unauthenticated call if we found it and everything matches. 9549 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV)) 9550 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator, 9551 DAG.getDataLayout())) 9552 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(), 9553 CB.isMustTailCall(), EHPadBB); 9554 9555 // Functions should never be ptrauth-called directly. 9556 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call"); 9557 9558 // Otherwise, do an authenticated indirect call. 9559 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(), 9560 getValue(Discriminator)}; 9561 9562 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(), 9563 EHPadBB, &PAI); 9564 } 9565 9566 namespace { 9567 9568 /// AsmOperandInfo - This contains information for each constraint that we are 9569 /// lowering. 9570 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9571 public: 9572 /// CallOperand - If this is the result output operand or a clobber 9573 /// this is null, otherwise it is the incoming operand to the CallInst. 9574 /// This gets modified as the asm is processed. 9575 SDValue CallOperand; 9576 9577 /// AssignedRegs - If this is a register or register class operand, this 9578 /// contains the set of register corresponding to the operand. 9579 RegsForValue AssignedRegs; 9580 9581 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9582 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9583 } 9584 9585 /// Whether or not this operand accesses memory 9586 bool hasMemory(const TargetLowering &TLI) const { 9587 // Indirect operand accesses access memory. 9588 if (isIndirect) 9589 return true; 9590 9591 for (const auto &Code : Codes) 9592 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9593 return true; 9594 9595 return false; 9596 } 9597 }; 9598 9599 9600 } // end anonymous namespace 9601 9602 /// Make sure that the output operand \p OpInfo and its corresponding input 9603 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9604 /// out). 9605 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9606 SDISelAsmOperandInfo &MatchingOpInfo, 9607 SelectionDAG &DAG) { 9608 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9609 return; 9610 9611 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9612 const auto &TLI = DAG.getTargetLoweringInfo(); 9613 9614 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9615 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9616 OpInfo.ConstraintVT); 9617 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9618 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9619 MatchingOpInfo.ConstraintVT); 9620 const bool OutOpIsIntOrFP = 9621 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint(); 9622 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() || 9623 MatchingOpInfo.ConstraintVT.isFloatingPoint(); 9624 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) { 9625 // FIXME: error out in a more elegant fashion 9626 report_fatal_error("Unsupported asm: input constraint" 9627 " with a matching output constraint of" 9628 " incompatible type!"); 9629 } 9630 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9631 } 9632 9633 /// Get a direct memory input to behave well as an indirect operand. 9634 /// This may introduce stores, hence the need for a \p Chain. 9635 /// \return The (possibly updated) chain. 9636 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9637 SDISelAsmOperandInfo &OpInfo, 9638 SelectionDAG &DAG) { 9639 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9640 9641 // If we don't have an indirect input, put it in the constpool if we can, 9642 // otherwise spill it to a stack slot. 9643 // TODO: This isn't quite right. We need to handle these according to 9644 // the addressing mode that the constraint wants. Also, this may take 9645 // an additional register for the computation and we don't want that 9646 // either. 9647 9648 // If the operand is a float, integer, or vector constant, spill to a 9649 // constant pool entry to get its address. 9650 const Value *OpVal = OpInfo.CallOperandVal; 9651 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9652 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9653 OpInfo.CallOperand = DAG.getConstantPool( 9654 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9655 return Chain; 9656 } 9657 9658 // Otherwise, create a stack slot and emit a store to it before the asm. 9659 Type *Ty = OpVal->getType(); 9660 auto &DL = DAG.getDataLayout(); 9661 TypeSize TySize = DL.getTypeAllocSize(Ty); 9662 MachineFunction &MF = DAG.getMachineFunction(); 9663 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 9664 int StackID = 0; 9665 if (TySize.isScalable()) 9666 StackID = TFI->getStackIDForScalableVectors(); 9667 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(), 9668 DL.getPrefTypeAlign(Ty), false, 9669 nullptr, StackID); 9670 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9671 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9672 MachinePointerInfo::getFixedStack(MF, SSFI), 9673 TLI.getMemValueType(DL, Ty)); 9674 OpInfo.CallOperand = StackSlot; 9675 9676 return Chain; 9677 } 9678 9679 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9680 /// specified operand. We prefer to assign virtual registers, to allow the 9681 /// register allocator to handle the assignment process. However, if the asm 9682 /// uses features that we can't model on machineinstrs, we have SDISel do the 9683 /// allocation. This produces generally horrible, but correct, code. 9684 /// 9685 /// OpInfo describes the operand 9686 /// RefOpInfo describes the matching operand if any, the operand otherwise 9687 static std::optional<unsigned> 9688 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9689 SDISelAsmOperandInfo &OpInfo, 9690 SDISelAsmOperandInfo &RefOpInfo) { 9691 LLVMContext &Context = *DAG.getContext(); 9692 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9693 9694 MachineFunction &MF = DAG.getMachineFunction(); 9695 SmallVector<Register, 4> Regs; 9696 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9697 9698 // No work to do for memory/address operands. 9699 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9700 OpInfo.ConstraintType == TargetLowering::C_Address) 9701 return std::nullopt; 9702 9703 // If this is a constraint for a single physreg, or a constraint for a 9704 // register class, find it. 9705 unsigned AssignedReg; 9706 const TargetRegisterClass *RC; 9707 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9708 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9709 // RC is unset only on failure. Return immediately. 9710 if (!RC) 9711 return std::nullopt; 9712 9713 // Get the actual register value type. This is important, because the user 9714 // may have asked for (e.g.) the AX register in i32 type. We need to 9715 // remember that AX is actually i16 to get the right extension. 9716 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9717 9718 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9719 // If this is an FP operand in an integer register (or visa versa), or more 9720 // generally if the operand value disagrees with the register class we plan 9721 // to stick it in, fix the operand type. 9722 // 9723 // If this is an input value, the bitcast to the new type is done now. 9724 // Bitcast for output value is done at the end of visitInlineAsm(). 9725 if ((OpInfo.Type == InlineAsm::isOutput || 9726 OpInfo.Type == InlineAsm::isInput) && 9727 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9728 // Try to convert to the first EVT that the reg class contains. If the 9729 // types are identical size, use a bitcast to convert (e.g. two differing 9730 // vector types). Note: output bitcast is done at the end of 9731 // visitInlineAsm(). 9732 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9733 // Exclude indirect inputs while they are unsupported because the code 9734 // to perform the load is missing and thus OpInfo.CallOperand still 9735 // refers to the input address rather than the pointed-to value. 9736 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9737 OpInfo.CallOperand = 9738 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9739 OpInfo.ConstraintVT = RegVT; 9740 // If the operand is an FP value and we want it in integer registers, 9741 // use the corresponding integer type. This turns an f64 value into 9742 // i64, which can be passed with two i32 values on a 32-bit machine. 9743 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9744 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9745 if (OpInfo.Type == InlineAsm::isInput) 9746 OpInfo.CallOperand = 9747 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9748 OpInfo.ConstraintVT = VT; 9749 } 9750 } 9751 } 9752 9753 // No need to allocate a matching input constraint since the constraint it's 9754 // matching to has already been allocated. 9755 if (OpInfo.isMatchingInputConstraint()) 9756 return std::nullopt; 9757 9758 EVT ValueVT = OpInfo.ConstraintVT; 9759 if (OpInfo.ConstraintVT == MVT::Other) 9760 ValueVT = RegVT; 9761 9762 // Initialize NumRegs. 9763 unsigned NumRegs = 1; 9764 if (OpInfo.ConstraintVT != MVT::Other) 9765 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9766 9767 // If this is a constraint for a specific physical register, like {r17}, 9768 // assign it now. 9769 9770 // If this associated to a specific register, initialize iterator to correct 9771 // place. If virtual, make sure we have enough registers 9772 9773 // Initialize iterator if necessary 9774 TargetRegisterClass::iterator I = RC->begin(); 9775 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9776 9777 // Do not check for single registers. 9778 if (AssignedReg) { 9779 I = std::find(I, RC->end(), AssignedReg); 9780 if (I == RC->end()) { 9781 // RC does not contain the selected register, which indicates a 9782 // mismatch between the register and the required type/bitwidth. 9783 return {AssignedReg}; 9784 } 9785 } 9786 9787 for (; NumRegs; --NumRegs, ++I) { 9788 assert(I != RC->end() && "Ran out of registers to allocate!"); 9789 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9790 Regs.push_back(R); 9791 } 9792 9793 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9794 return std::nullopt; 9795 } 9796 9797 static unsigned 9798 findMatchingInlineAsmOperand(unsigned OperandNo, 9799 const std::vector<SDValue> &AsmNodeOperands) { 9800 // Scan until we find the definition we already emitted of this operand. 9801 unsigned CurOp = InlineAsm::Op_FirstOperand; 9802 for (; OperandNo; --OperandNo) { 9803 // Advance to the next operand. 9804 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9805 const InlineAsm::Flag F(OpFlag); 9806 assert( 9807 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9808 "Skipped past definitions?"); 9809 CurOp += F.getNumOperandRegisters() + 1; 9810 } 9811 return CurOp; 9812 } 9813 9814 namespace { 9815 9816 class ExtraFlags { 9817 unsigned Flags = 0; 9818 9819 public: 9820 explicit ExtraFlags(const CallBase &Call) { 9821 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9822 if (IA->hasSideEffects()) 9823 Flags |= InlineAsm::Extra_HasSideEffects; 9824 if (IA->isAlignStack()) 9825 Flags |= InlineAsm::Extra_IsAlignStack; 9826 if (Call.isConvergent()) 9827 Flags |= InlineAsm::Extra_IsConvergent; 9828 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9829 } 9830 9831 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9832 // Ideally, we would only check against memory constraints. However, the 9833 // meaning of an Other constraint can be target-specific and we can't easily 9834 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9835 // for Other constraints as well. 9836 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9837 OpInfo.ConstraintType == TargetLowering::C_Other) { 9838 if (OpInfo.Type == InlineAsm::isInput) 9839 Flags |= InlineAsm::Extra_MayLoad; 9840 else if (OpInfo.Type == InlineAsm::isOutput) 9841 Flags |= InlineAsm::Extra_MayStore; 9842 else if (OpInfo.Type == InlineAsm::isClobber) 9843 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9844 } 9845 } 9846 9847 unsigned get() const { return Flags; } 9848 }; 9849 9850 } // end anonymous namespace 9851 9852 static bool isFunction(SDValue Op) { 9853 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9854 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9855 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9856 9857 // In normal "call dllimport func" instruction (non-inlineasm) it force 9858 // indirect access by specifing call opcode. And usually specially print 9859 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9860 // not do in this way now. (In fact, this is similar with "Data Access" 9861 // action). So here we ignore dllimport function. 9862 if (Fn && !Fn->hasDLLImportStorageClass()) 9863 return true; 9864 } 9865 } 9866 return false; 9867 } 9868 9869 /// visitInlineAsm - Handle a call to an InlineAsm object. 9870 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9871 const BasicBlock *EHPadBB) { 9872 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9873 9874 /// ConstraintOperands - Information about all of the constraints. 9875 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9876 9877 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9878 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9879 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9880 9881 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9882 // AsmDialect, MayLoad, MayStore). 9883 bool HasSideEffect = IA->hasSideEffects(); 9884 ExtraFlags ExtraInfo(Call); 9885 9886 for (auto &T : TargetConstraints) { 9887 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9888 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9889 9890 if (OpInfo.CallOperandVal) 9891 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9892 9893 if (!HasSideEffect) 9894 HasSideEffect = OpInfo.hasMemory(TLI); 9895 9896 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9897 // FIXME: Could we compute this on OpInfo rather than T? 9898 9899 // Compute the constraint code and ConstraintType to use. 9900 TLI.ComputeConstraintToUse(T, SDValue()); 9901 9902 if (T.ConstraintType == TargetLowering::C_Immediate && 9903 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9904 // We've delayed emitting a diagnostic like the "n" constraint because 9905 // inlining could cause an integer showing up. 9906 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9907 "' expects an integer constant " 9908 "expression"); 9909 9910 ExtraInfo.update(T); 9911 } 9912 9913 // We won't need to flush pending loads if this asm doesn't touch 9914 // memory and is nonvolatile. 9915 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9916 9917 bool EmitEHLabels = isa<InvokeInst>(Call); 9918 if (EmitEHLabels) { 9919 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9920 } 9921 bool IsCallBr = isa<CallBrInst>(Call); 9922 9923 if (IsCallBr || EmitEHLabels) { 9924 // If this is a callbr or invoke we need to flush pending exports since 9925 // inlineasm_br and invoke are terminators. 9926 // We need to do this before nodes are glued to the inlineasm_br node. 9927 Chain = getControlRoot(); 9928 } 9929 9930 MCSymbol *BeginLabel = nullptr; 9931 if (EmitEHLabels) { 9932 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9933 } 9934 9935 int OpNo = -1; 9936 SmallVector<StringRef> AsmStrs; 9937 IA->collectAsmStrs(AsmStrs); 9938 9939 // Second pass over the constraints: compute which constraint option to use. 9940 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9941 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9942 OpNo++; 9943 9944 // If this is an output operand with a matching input operand, look up the 9945 // matching input. If their types mismatch, e.g. one is an integer, the 9946 // other is floating point, or their sizes are different, flag it as an 9947 // error. 9948 if (OpInfo.hasMatchingInput()) { 9949 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9950 patchMatchingInput(OpInfo, Input, DAG); 9951 } 9952 9953 // Compute the constraint code and ConstraintType to use. 9954 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9955 9956 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9957 OpInfo.Type == InlineAsm::isClobber) || 9958 OpInfo.ConstraintType == TargetLowering::C_Address) 9959 continue; 9960 9961 // In Linux PIC model, there are 4 cases about value/label addressing: 9962 // 9963 // 1: Function call or Label jmp inside the module. 9964 // 2: Data access (such as global variable, static variable) inside module. 9965 // 3: Function call or Label jmp outside the module. 9966 // 4: Data access (such as global variable) outside the module. 9967 // 9968 // Due to current llvm inline asm architecture designed to not "recognize" 9969 // the asm code, there are quite troubles for us to treat mem addressing 9970 // differently for same value/adress used in different instuctions. 9971 // For example, in pic model, call a func may in plt way or direclty 9972 // pc-related, but lea/mov a function adress may use got. 9973 // 9974 // Here we try to "recognize" function call for the case 1 and case 3 in 9975 // inline asm. And try to adjust the constraint for them. 9976 // 9977 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9978 // label, so here we don't handle jmp function label now, but we need to 9979 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9980 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9981 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9982 TM.getCodeModel() != CodeModel::Large) { 9983 OpInfo.isIndirect = false; 9984 OpInfo.ConstraintType = TargetLowering::C_Address; 9985 } 9986 9987 // If this is a memory input, and if the operand is not indirect, do what we 9988 // need to provide an address for the memory input. 9989 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9990 !OpInfo.isIndirect) { 9991 assert((OpInfo.isMultipleAlternative || 9992 (OpInfo.Type == InlineAsm::isInput)) && 9993 "Can only indirectify direct input operands!"); 9994 9995 // Memory operands really want the address of the value. 9996 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9997 9998 // There is no longer a Value* corresponding to this operand. 9999 OpInfo.CallOperandVal = nullptr; 10000 10001 // It is now an indirect operand. 10002 OpInfo.isIndirect = true; 10003 } 10004 10005 } 10006 10007 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 10008 std::vector<SDValue> AsmNodeOperands; 10009 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 10010 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 10011 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 10012 10013 // If we have a !srcloc metadata node associated with it, we want to attach 10014 // this to the ultimately generated inline asm machineinstr. To do this, we 10015 // pass in the third operand as this (potentially null) inline asm MDNode. 10016 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 10017 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 10018 10019 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 10020 // bits as operand 3. 10021 AsmNodeOperands.push_back(DAG.getTargetConstant( 10022 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10023 10024 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 10025 // this, assign virtual and physical registers for inputs and otput. 10026 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10027 // Assign Registers. 10028 SDISelAsmOperandInfo &RefOpInfo = 10029 OpInfo.isMatchingInputConstraint() 10030 ? ConstraintOperands[OpInfo.getMatchedOperand()] 10031 : OpInfo; 10032 const auto RegError = 10033 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 10034 if (RegError) { 10035 const MachineFunction &MF = DAG.getMachineFunction(); 10036 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 10037 const char *RegName = TRI.getName(*RegError); 10038 emitInlineAsmError(Call, "register '" + Twine(RegName) + 10039 "' allocated for constraint '" + 10040 Twine(OpInfo.ConstraintCode) + 10041 "' does not match required type"); 10042 return; 10043 } 10044 10045 auto DetectWriteToReservedRegister = [&]() { 10046 const MachineFunction &MF = DAG.getMachineFunction(); 10047 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 10048 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 10049 if (Register::isPhysicalRegister(Reg) && 10050 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 10051 const char *RegName = TRI.getName(Reg); 10052 emitInlineAsmError(Call, "write to reserved register '" + 10053 Twine(RegName) + "'"); 10054 return true; 10055 } 10056 } 10057 return false; 10058 }; 10059 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 10060 (OpInfo.Type == InlineAsm::isInput && 10061 !OpInfo.isMatchingInputConstraint())) && 10062 "Only address as input operand is allowed."); 10063 10064 switch (OpInfo.Type) { 10065 case InlineAsm::isOutput: 10066 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 10067 const InlineAsm::ConstraintCode ConstraintID = 10068 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10069 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10070 "Failed to convert memory constraint code to constraint id."); 10071 10072 // Add information to the INLINEASM node to know about this output. 10073 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 10074 OpFlags.setMemConstraint(ConstraintID); 10075 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 10076 MVT::i32)); 10077 AsmNodeOperands.push_back(OpInfo.CallOperand); 10078 } else { 10079 // Otherwise, this outputs to a register (directly for C_Register / 10080 // C_RegisterClass, and a target-defined fashion for 10081 // C_Immediate/C_Other). Find a register that we can use. 10082 if (OpInfo.AssignedRegs.Regs.empty()) { 10083 emitInlineAsmError( 10084 Call, "couldn't allocate output register for constraint '" + 10085 Twine(OpInfo.ConstraintCode) + "'"); 10086 return; 10087 } 10088 10089 if (DetectWriteToReservedRegister()) 10090 return; 10091 10092 // Add information to the INLINEASM node to know that this register is 10093 // set. 10094 OpInfo.AssignedRegs.AddInlineAsmOperands( 10095 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 10096 : InlineAsm::Kind::RegDef, 10097 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 10098 } 10099 break; 10100 10101 case InlineAsm::isInput: 10102 case InlineAsm::isLabel: { 10103 SDValue InOperandVal = OpInfo.CallOperand; 10104 10105 if (OpInfo.isMatchingInputConstraint()) { 10106 // If this is required to match an output register we have already set, 10107 // just use its register. 10108 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 10109 AsmNodeOperands); 10110 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 10111 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 10112 if (OpInfo.isIndirect) { 10113 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 10114 emitInlineAsmError(Call, "inline asm not supported yet: " 10115 "don't know how to handle tied " 10116 "indirect register inputs"); 10117 return; 10118 } 10119 10120 SmallVector<Register, 4> Regs; 10121 MachineFunction &MF = DAG.getMachineFunction(); 10122 MachineRegisterInfo &MRI = MF.getRegInfo(); 10123 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 10124 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 10125 Register TiedReg = R->getReg(); 10126 MVT RegVT = R->getSimpleValueType(0); 10127 const TargetRegisterClass *RC = 10128 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 10129 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 10130 : TRI.getMinimalPhysRegClass(TiedReg); 10131 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 10132 Regs.push_back(MRI.createVirtualRegister(RC)); 10133 10134 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 10135 10136 SDLoc dl = getCurSDLoc(); 10137 // Use the produced MatchedRegs object to 10138 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 10139 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 10140 OpInfo.getMatchedOperand(), dl, DAG, 10141 AsmNodeOperands); 10142 break; 10143 } 10144 10145 assert(Flag.isMemKind() && "Unknown matching constraint!"); 10146 assert(Flag.getNumOperandRegisters() == 1 && 10147 "Unexpected number of operands"); 10148 // Add information to the INLINEASM node to know about this input. 10149 // See InlineAsm.h isUseOperandTiedToDef. 10150 Flag.clearMemConstraint(); 10151 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 10152 AsmNodeOperands.push_back(DAG.getTargetConstant( 10153 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10154 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 10155 break; 10156 } 10157 10158 // Treat indirect 'X' constraint as memory. 10159 if (OpInfo.ConstraintType == TargetLowering::C_Other && 10160 OpInfo.isIndirect) 10161 OpInfo.ConstraintType = TargetLowering::C_Memory; 10162 10163 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 10164 OpInfo.ConstraintType == TargetLowering::C_Other) { 10165 std::vector<SDValue> Ops; 10166 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 10167 Ops, DAG); 10168 if (Ops.empty()) { 10169 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 10170 if (isa<ConstantSDNode>(InOperandVal)) { 10171 emitInlineAsmError(Call, "value out of range for constraint '" + 10172 Twine(OpInfo.ConstraintCode) + "'"); 10173 return; 10174 } 10175 10176 emitInlineAsmError(Call, 10177 "invalid operand for inline asm constraint '" + 10178 Twine(OpInfo.ConstraintCode) + "'"); 10179 return; 10180 } 10181 10182 // Add information to the INLINEASM node to know about this input. 10183 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 10184 AsmNodeOperands.push_back(DAG.getTargetConstant( 10185 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10186 llvm::append_range(AsmNodeOperands, Ops); 10187 break; 10188 } 10189 10190 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 10191 assert((OpInfo.isIndirect || 10192 OpInfo.ConstraintType != TargetLowering::C_Memory) && 10193 "Operand must be indirect to be a mem!"); 10194 assert(InOperandVal.getValueType() == 10195 TLI.getPointerTy(DAG.getDataLayout()) && 10196 "Memory operands expect pointer values"); 10197 10198 const InlineAsm::ConstraintCode ConstraintID = 10199 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10200 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10201 "Failed to convert memory constraint code to constraint id."); 10202 10203 // Add information to the INLINEASM node to know about this input. 10204 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 10205 ResOpType.setMemConstraint(ConstraintID); 10206 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 10207 getCurSDLoc(), 10208 MVT::i32)); 10209 AsmNodeOperands.push_back(InOperandVal); 10210 break; 10211 } 10212 10213 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 10214 const InlineAsm::ConstraintCode ConstraintID = 10215 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10216 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10217 "Failed to convert memory constraint code to constraint id."); 10218 10219 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 10220 10221 SDValue AsmOp = InOperandVal; 10222 if (isFunction(InOperandVal)) { 10223 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 10224 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 10225 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 10226 InOperandVal.getValueType(), 10227 GA->getOffset()); 10228 } 10229 10230 // Add information to the INLINEASM node to know about this input. 10231 ResOpType.setMemConstraint(ConstraintID); 10232 10233 AsmNodeOperands.push_back( 10234 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 10235 10236 AsmNodeOperands.push_back(AsmOp); 10237 break; 10238 } 10239 10240 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 10241 OpInfo.ConstraintType != TargetLowering::C_Register) { 10242 emitInlineAsmError(Call, "unknown asm constraint '" + 10243 Twine(OpInfo.ConstraintCode) + "'"); 10244 return; 10245 } 10246 10247 // TODO: Support this. 10248 if (OpInfo.isIndirect) { 10249 emitInlineAsmError( 10250 Call, "Don't know how to handle indirect register inputs yet " 10251 "for constraint '" + 10252 Twine(OpInfo.ConstraintCode) + "'"); 10253 return; 10254 } 10255 10256 // Copy the input into the appropriate registers. 10257 if (OpInfo.AssignedRegs.Regs.empty()) { 10258 emitInlineAsmError(Call, 10259 "couldn't allocate input reg for constraint '" + 10260 Twine(OpInfo.ConstraintCode) + "'"); 10261 return; 10262 } 10263 10264 if (DetectWriteToReservedRegister()) 10265 return; 10266 10267 SDLoc dl = getCurSDLoc(); 10268 10269 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 10270 &Call); 10271 10272 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 10273 0, dl, DAG, AsmNodeOperands); 10274 break; 10275 } 10276 case InlineAsm::isClobber: 10277 // Add the clobbered value to the operand list, so that the register 10278 // allocator is aware that the physreg got clobbered. 10279 if (!OpInfo.AssignedRegs.Regs.empty()) 10280 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 10281 false, 0, getCurSDLoc(), DAG, 10282 AsmNodeOperands); 10283 break; 10284 } 10285 } 10286 10287 // Finish up input operands. Set the input chain and add the flag last. 10288 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 10289 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 10290 10291 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 10292 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 10293 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 10294 Glue = Chain.getValue(1); 10295 10296 // Do additional work to generate outputs. 10297 10298 SmallVector<EVT, 1> ResultVTs; 10299 SmallVector<SDValue, 1> ResultValues; 10300 SmallVector<SDValue, 8> OutChains; 10301 10302 llvm::Type *CallResultType = Call.getType(); 10303 ArrayRef<Type *> ResultTypes; 10304 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 10305 ResultTypes = StructResult->elements(); 10306 else if (!CallResultType->isVoidTy()) 10307 ResultTypes = ArrayRef(CallResultType); 10308 10309 auto CurResultType = ResultTypes.begin(); 10310 auto handleRegAssign = [&](SDValue V) { 10311 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 10312 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 10313 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 10314 ++CurResultType; 10315 // If the type of the inline asm call site return value is different but has 10316 // same size as the type of the asm output bitcast it. One example of this 10317 // is for vectors with different width / number of elements. This can 10318 // happen for register classes that can contain multiple different value 10319 // types. The preg or vreg allocated may not have the same VT as was 10320 // expected. 10321 // 10322 // This can also happen for a return value that disagrees with the register 10323 // class it is put in, eg. a double in a general-purpose register on a 10324 // 32-bit machine. 10325 if (ResultVT != V.getValueType() && 10326 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 10327 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 10328 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 10329 V.getValueType().isInteger()) { 10330 // If a result value was tied to an input value, the computed result 10331 // may have a wider width than the expected result. Extract the 10332 // relevant portion. 10333 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 10334 } 10335 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 10336 ResultVTs.push_back(ResultVT); 10337 ResultValues.push_back(V); 10338 }; 10339 10340 // Deal with output operands. 10341 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10342 if (OpInfo.Type == InlineAsm::isOutput) { 10343 SDValue Val; 10344 // Skip trivial output operands. 10345 if (OpInfo.AssignedRegs.Regs.empty()) 10346 continue; 10347 10348 switch (OpInfo.ConstraintType) { 10349 case TargetLowering::C_Register: 10350 case TargetLowering::C_RegisterClass: 10351 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 10352 Chain, &Glue, &Call); 10353 break; 10354 case TargetLowering::C_Immediate: 10355 case TargetLowering::C_Other: 10356 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 10357 OpInfo, DAG); 10358 break; 10359 case TargetLowering::C_Memory: 10360 break; // Already handled. 10361 case TargetLowering::C_Address: 10362 break; // Silence warning. 10363 case TargetLowering::C_Unknown: 10364 assert(false && "Unexpected unknown constraint"); 10365 } 10366 10367 // Indirect output manifest as stores. Record output chains. 10368 if (OpInfo.isIndirect) { 10369 const Value *Ptr = OpInfo.CallOperandVal; 10370 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 10371 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 10372 MachinePointerInfo(Ptr)); 10373 OutChains.push_back(Store); 10374 } else { 10375 // generate CopyFromRegs to associated registers. 10376 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 10377 if (Val.getOpcode() == ISD::MERGE_VALUES) { 10378 for (const SDValue &V : Val->op_values()) 10379 handleRegAssign(V); 10380 } else 10381 handleRegAssign(Val); 10382 } 10383 } 10384 } 10385 10386 // Set results. 10387 if (!ResultValues.empty()) { 10388 assert(CurResultType == ResultTypes.end() && 10389 "Mismatch in number of ResultTypes"); 10390 assert(ResultValues.size() == ResultTypes.size() && 10391 "Mismatch in number of output operands in asm result"); 10392 10393 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10394 DAG.getVTList(ResultVTs), ResultValues); 10395 setValue(&Call, V); 10396 } 10397 10398 // Collect store chains. 10399 if (!OutChains.empty()) 10400 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 10401 10402 if (EmitEHLabels) { 10403 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 10404 } 10405 10406 // Only Update Root if inline assembly has a memory effect. 10407 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 10408 EmitEHLabels) 10409 DAG.setRoot(Chain); 10410 } 10411 10412 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 10413 const Twine &Message) { 10414 LLVMContext &Ctx = *DAG.getContext(); 10415 Ctx.emitError(&Call, Message); 10416 10417 // Make sure we leave the DAG in a valid state 10418 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10419 SmallVector<EVT, 1> ValueVTs; 10420 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 10421 10422 if (ValueVTs.empty()) 10423 return; 10424 10425 SmallVector<SDValue, 1> Ops; 10426 for (const EVT &VT : ValueVTs) 10427 Ops.push_back(DAG.getUNDEF(VT)); 10428 10429 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 10430 } 10431 10432 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 10433 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 10434 MVT::Other, getRoot(), 10435 getValue(I.getArgOperand(0)), 10436 DAG.getSrcValue(I.getArgOperand(0)))); 10437 } 10438 10439 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 10440 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10441 const DataLayout &DL = DAG.getDataLayout(); 10442 SDValue V = DAG.getVAArg( 10443 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 10444 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 10445 DL.getABITypeAlign(I.getType()).value()); 10446 DAG.setRoot(V.getValue(1)); 10447 10448 if (I.getType()->isPointerTy()) 10449 V = DAG.getPtrExtOrTrunc( 10450 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 10451 setValue(&I, V); 10452 } 10453 10454 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 10455 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 10456 MVT::Other, getRoot(), 10457 getValue(I.getArgOperand(0)), 10458 DAG.getSrcValue(I.getArgOperand(0)))); 10459 } 10460 10461 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 10462 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 10463 MVT::Other, getRoot(), 10464 getValue(I.getArgOperand(0)), 10465 getValue(I.getArgOperand(1)), 10466 DAG.getSrcValue(I.getArgOperand(0)), 10467 DAG.getSrcValue(I.getArgOperand(1)))); 10468 } 10469 10470 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 10471 const Instruction &I, 10472 SDValue Op) { 10473 std::optional<ConstantRange> CR = getRange(I); 10474 10475 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped()) 10476 return Op; 10477 10478 APInt Lo = CR->getUnsignedMin(); 10479 if (!Lo.isMinValue()) 10480 return Op; 10481 10482 APInt Hi = CR->getUnsignedMax(); 10483 unsigned Bits = std::max(Hi.getActiveBits(), 10484 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 10485 10486 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 10487 10488 SDLoc SL = getCurSDLoc(); 10489 10490 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 10491 DAG.getValueType(SmallVT)); 10492 unsigned NumVals = Op.getNode()->getNumValues(); 10493 if (NumVals == 1) 10494 return ZExt; 10495 10496 SmallVector<SDValue, 4> Ops; 10497 10498 Ops.push_back(ZExt); 10499 for (unsigned I = 1; I != NumVals; ++I) 10500 Ops.push_back(Op.getValue(I)); 10501 10502 return DAG.getMergeValues(Ops, SL); 10503 } 10504 10505 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 10506 /// the call being lowered. 10507 /// 10508 /// This is a helper for lowering intrinsics that follow a target calling 10509 /// convention or require stack pointer adjustment. Only a subset of the 10510 /// intrinsic's operands need to participate in the calling convention. 10511 void SelectionDAGBuilder::populateCallLoweringInfo( 10512 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 10513 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 10514 AttributeSet RetAttrs, bool IsPatchPoint) { 10515 TargetLowering::ArgListTy Args; 10516 Args.reserve(NumArgs); 10517 10518 // Populate the argument list. 10519 // Attributes for args start at offset 1, after the return attribute. 10520 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 10521 ArgI != ArgE; ++ArgI) { 10522 const Value *V = Call->getOperand(ArgI); 10523 10524 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 10525 10526 TargetLowering::ArgListEntry Entry; 10527 Entry.Node = getValue(V); 10528 Entry.Ty = V->getType(); 10529 Entry.setAttributes(Call, ArgI); 10530 Args.push_back(Entry); 10531 } 10532 10533 CLI.setDebugLoc(getCurSDLoc()) 10534 .setChain(getRoot()) 10535 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 10536 RetAttrs) 10537 .setDiscardResult(Call->use_empty()) 10538 .setIsPatchPoint(IsPatchPoint) 10539 .setIsPreallocated( 10540 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 10541 } 10542 10543 /// Add a stack map intrinsic call's live variable operands to a stackmap 10544 /// or patchpoint target node's operand list. 10545 /// 10546 /// Constants are converted to TargetConstants purely as an optimization to 10547 /// avoid constant materialization and register allocation. 10548 /// 10549 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 10550 /// generate addess computation nodes, and so FinalizeISel can convert the 10551 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10552 /// address materialization and register allocation, but may also be required 10553 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10554 /// alloca in the entry block, then the runtime may assume that the alloca's 10555 /// StackMap location can be read immediately after compilation and that the 10556 /// location is valid at any point during execution (this is similar to the 10557 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10558 /// only available in a register, then the runtime would need to trap when 10559 /// execution reaches the StackMap in order to read the alloca's location. 10560 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10561 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10562 SelectionDAGBuilder &Builder) { 10563 SelectionDAG &DAG = Builder.DAG; 10564 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10565 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10566 10567 // Things on the stack are pointer-typed, meaning that they are already 10568 // legal and can be emitted directly to target nodes. 10569 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10570 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10571 } else { 10572 // Otherwise emit a target independent node to be legalised. 10573 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10574 } 10575 } 10576 } 10577 10578 /// Lower llvm.experimental.stackmap. 10579 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10580 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10581 // [live variables...]) 10582 10583 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10584 10585 SDValue Chain, InGlue, Callee; 10586 SmallVector<SDValue, 32> Ops; 10587 10588 SDLoc DL = getCurSDLoc(); 10589 Callee = getValue(CI.getCalledOperand()); 10590 10591 // The stackmap intrinsic only records the live variables (the arguments 10592 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10593 // intrinsic, this won't be lowered to a function call. This means we don't 10594 // have to worry about calling conventions and target specific lowering code. 10595 // Instead we perform the call lowering right here. 10596 // 10597 // chain, flag = CALLSEQ_START(chain, 0, 0) 10598 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10599 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10600 // 10601 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10602 InGlue = Chain.getValue(1); 10603 10604 // Add the STACKMAP operands, starting with DAG house-keeping. 10605 Ops.push_back(Chain); 10606 Ops.push_back(InGlue); 10607 10608 // Add the <id>, <numShadowBytes> operands. 10609 // 10610 // These do not require legalisation, and can be emitted directly to target 10611 // constant nodes. 10612 SDValue ID = getValue(CI.getArgOperand(0)); 10613 assert(ID.getValueType() == MVT::i64); 10614 SDValue IDConst = 10615 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10616 Ops.push_back(IDConst); 10617 10618 SDValue Shad = getValue(CI.getArgOperand(1)); 10619 assert(Shad.getValueType() == MVT::i32); 10620 SDValue ShadConst = 10621 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10622 Ops.push_back(ShadConst); 10623 10624 // Add the live variables. 10625 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10626 10627 // Create the STACKMAP node. 10628 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10629 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10630 InGlue = Chain.getValue(1); 10631 10632 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10633 10634 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10635 10636 // Set the root to the target-lowered call chain. 10637 DAG.setRoot(Chain); 10638 10639 // Inform the Frame Information that we have a stackmap in this function. 10640 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10641 } 10642 10643 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10644 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10645 const BasicBlock *EHPadBB) { 10646 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>, 10647 // i32 <numBytes>, 10648 // i8* <target>, 10649 // i32 <numArgs>, 10650 // [Args...], 10651 // [live variables...]) 10652 10653 CallingConv::ID CC = CB.getCallingConv(); 10654 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10655 bool HasDef = !CB.getType()->isVoidTy(); 10656 SDLoc dl = getCurSDLoc(); 10657 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10658 10659 // Handle immediate and symbolic callees. 10660 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10661 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10662 /*isTarget=*/true); 10663 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10664 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10665 SDLoc(SymbolicCallee), 10666 SymbolicCallee->getValueType(0)); 10667 10668 // Get the real number of arguments participating in the call <numArgs> 10669 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10670 unsigned NumArgs = NArgVal->getAsZExtVal(); 10671 10672 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10673 // Intrinsics include all meta-operands up to but not including CC. 10674 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10675 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10676 "Not enough arguments provided to the patchpoint intrinsic"); 10677 10678 // For AnyRegCC the arguments are lowered later on manually. 10679 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10680 Type *ReturnTy = 10681 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10682 10683 TargetLowering::CallLoweringInfo CLI(DAG); 10684 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10685 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10686 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10687 10688 SDNode *CallEnd = Result.second.getNode(); 10689 if (CallEnd->getOpcode() == ISD::EH_LABEL) 10690 CallEnd = CallEnd->getOperand(0).getNode(); 10691 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10692 CallEnd = CallEnd->getOperand(0).getNode(); 10693 10694 /// Get a call instruction from the call sequence chain. 10695 /// Tail calls are not allowed. 10696 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10697 "Expected a callseq node."); 10698 SDNode *Call = CallEnd->getOperand(0).getNode(); 10699 bool HasGlue = Call->getGluedNode(); 10700 10701 // Replace the target specific call node with the patchable intrinsic. 10702 SmallVector<SDValue, 8> Ops; 10703 10704 // Push the chain. 10705 Ops.push_back(*(Call->op_begin())); 10706 10707 // Optionally, push the glue (if any). 10708 if (HasGlue) 10709 Ops.push_back(*(Call->op_end() - 1)); 10710 10711 // Push the register mask info. 10712 if (HasGlue) 10713 Ops.push_back(*(Call->op_end() - 2)); 10714 else 10715 Ops.push_back(*(Call->op_end() - 1)); 10716 10717 // Add the <id> and <numBytes> constants. 10718 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10719 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10720 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10721 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10722 10723 // Add the callee. 10724 Ops.push_back(Callee); 10725 10726 // Adjust <numArgs> to account for any arguments that have been passed on the 10727 // stack instead. 10728 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10729 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10730 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10731 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10732 10733 // Add the calling convention 10734 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10735 10736 // Add the arguments we omitted previously. The register allocator should 10737 // place these in any free register. 10738 if (IsAnyRegCC) 10739 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10740 Ops.push_back(getValue(CB.getArgOperand(i))); 10741 10742 // Push the arguments from the call instruction. 10743 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10744 Ops.append(Call->op_begin() + 2, e); 10745 10746 // Push live variables for the stack map. 10747 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10748 10749 SDVTList NodeTys; 10750 if (IsAnyRegCC && HasDef) { 10751 // Create the return types based on the intrinsic definition 10752 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10753 SmallVector<EVT, 3> ValueVTs; 10754 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10755 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10756 10757 // There is always a chain and a glue type at the end 10758 ValueVTs.push_back(MVT::Other); 10759 ValueVTs.push_back(MVT::Glue); 10760 NodeTys = DAG.getVTList(ValueVTs); 10761 } else 10762 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10763 10764 // Replace the target specific call node with a PATCHPOINT node. 10765 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10766 10767 // Update the NodeMap. 10768 if (HasDef) { 10769 if (IsAnyRegCC) 10770 setValue(&CB, SDValue(PPV.getNode(), 0)); 10771 else 10772 setValue(&CB, Result.first); 10773 } 10774 10775 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10776 // call sequence. Furthermore the location of the chain and glue can change 10777 // when the AnyReg calling convention is used and the intrinsic returns a 10778 // value. 10779 if (IsAnyRegCC && HasDef) { 10780 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10781 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10782 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10783 } else 10784 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10785 DAG.DeleteNode(Call); 10786 10787 // Inform the Frame Information that we have a patchpoint in this function. 10788 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10789 } 10790 10791 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10792 unsigned Intrinsic) { 10793 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10794 SDValue Op1 = getValue(I.getArgOperand(0)); 10795 SDValue Op2; 10796 if (I.arg_size() > 1) 10797 Op2 = getValue(I.getArgOperand(1)); 10798 SDLoc dl = getCurSDLoc(); 10799 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10800 SDValue Res; 10801 SDNodeFlags SDFlags; 10802 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10803 SDFlags.copyFMF(*FPMO); 10804 10805 switch (Intrinsic) { 10806 case Intrinsic::vector_reduce_fadd: 10807 if (SDFlags.hasAllowReassociation()) 10808 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10809 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10810 SDFlags); 10811 else 10812 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10813 break; 10814 case Intrinsic::vector_reduce_fmul: 10815 if (SDFlags.hasAllowReassociation()) 10816 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10817 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10818 SDFlags); 10819 else 10820 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10821 break; 10822 case Intrinsic::vector_reduce_add: 10823 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10824 break; 10825 case Intrinsic::vector_reduce_mul: 10826 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10827 break; 10828 case Intrinsic::vector_reduce_and: 10829 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10830 break; 10831 case Intrinsic::vector_reduce_or: 10832 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10833 break; 10834 case Intrinsic::vector_reduce_xor: 10835 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10836 break; 10837 case Intrinsic::vector_reduce_smax: 10838 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10839 break; 10840 case Intrinsic::vector_reduce_smin: 10841 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10842 break; 10843 case Intrinsic::vector_reduce_umax: 10844 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10845 break; 10846 case Intrinsic::vector_reduce_umin: 10847 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10848 break; 10849 case Intrinsic::vector_reduce_fmax: 10850 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10851 break; 10852 case Intrinsic::vector_reduce_fmin: 10853 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10854 break; 10855 case Intrinsic::vector_reduce_fmaximum: 10856 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10857 break; 10858 case Intrinsic::vector_reduce_fminimum: 10859 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10860 break; 10861 default: 10862 llvm_unreachable("Unhandled vector reduce intrinsic"); 10863 } 10864 setValue(&I, Res); 10865 } 10866 10867 /// Returns an AttributeList representing the attributes applied to the return 10868 /// value of the given call. 10869 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10870 SmallVector<Attribute::AttrKind, 2> Attrs; 10871 if (CLI.RetSExt) 10872 Attrs.push_back(Attribute::SExt); 10873 if (CLI.RetZExt) 10874 Attrs.push_back(Attribute::ZExt); 10875 if (CLI.IsInReg) 10876 Attrs.push_back(Attribute::InReg); 10877 10878 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10879 Attrs); 10880 } 10881 10882 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10883 /// implementation, which just calls LowerCall. 10884 /// FIXME: When all targets are 10885 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10886 std::pair<SDValue, SDValue> 10887 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10888 // Handle the incoming return values from the call. 10889 CLI.Ins.clear(); 10890 Type *OrigRetTy = CLI.RetTy; 10891 SmallVector<EVT, 4> RetTys; 10892 SmallVector<TypeSize, 4> Offsets; 10893 auto &DL = CLI.DAG.getDataLayout(); 10894 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 10895 10896 if (CLI.IsPostTypeLegalization) { 10897 // If we are lowering a libcall after legalization, split the return type. 10898 SmallVector<EVT, 4> OldRetTys; 10899 SmallVector<TypeSize, 4> OldOffsets; 10900 RetTys.swap(OldRetTys); 10901 Offsets.swap(OldOffsets); 10902 10903 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10904 EVT RetVT = OldRetTys[i]; 10905 uint64_t Offset = OldOffsets[i]; 10906 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10907 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10908 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10909 RetTys.append(NumRegs, RegisterVT); 10910 for (unsigned j = 0; j != NumRegs; ++j) 10911 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ)); 10912 } 10913 } 10914 10915 SmallVector<ISD::OutputArg, 4> Outs; 10916 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10917 10918 bool CanLowerReturn = 10919 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10920 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10921 10922 SDValue DemoteStackSlot; 10923 int DemoteStackIdx = -100; 10924 if (!CanLowerReturn) { 10925 // FIXME: equivalent assert? 10926 // assert(!CS.hasInAllocaArgument() && 10927 // "sret demotion is incompatible with inalloca"); 10928 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10929 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10930 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10931 DemoteStackIdx = 10932 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10933 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10934 DL.getAllocaAddrSpace()); 10935 10936 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10937 ArgListEntry Entry; 10938 Entry.Node = DemoteStackSlot; 10939 Entry.Ty = StackSlotPtrType; 10940 Entry.IsSExt = false; 10941 Entry.IsZExt = false; 10942 Entry.IsInReg = false; 10943 Entry.IsSRet = true; 10944 Entry.IsNest = false; 10945 Entry.IsByVal = false; 10946 Entry.IsByRef = false; 10947 Entry.IsReturned = false; 10948 Entry.IsSwiftSelf = false; 10949 Entry.IsSwiftAsync = false; 10950 Entry.IsSwiftError = false; 10951 Entry.IsCFGuardTarget = false; 10952 Entry.Alignment = Alignment; 10953 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10954 CLI.NumFixedArgs += 1; 10955 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10956 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10957 10958 // sret demotion isn't compatible with tail-calls, since the sret argument 10959 // points into the callers stack frame. 10960 CLI.IsTailCall = false; 10961 } else { 10962 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10963 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10964 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10965 ISD::ArgFlagsTy Flags; 10966 if (NeedsRegBlock) { 10967 Flags.setInConsecutiveRegs(); 10968 if (I == RetTys.size() - 1) 10969 Flags.setInConsecutiveRegsLast(); 10970 } 10971 EVT VT = RetTys[I]; 10972 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10973 CLI.CallConv, VT); 10974 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10975 CLI.CallConv, VT); 10976 for (unsigned i = 0; i != NumRegs; ++i) { 10977 ISD::InputArg MyFlags; 10978 MyFlags.Flags = Flags; 10979 MyFlags.VT = RegisterVT; 10980 MyFlags.ArgVT = VT; 10981 MyFlags.Used = CLI.IsReturnValueUsed; 10982 if (CLI.RetTy->isPointerTy()) { 10983 MyFlags.Flags.setPointer(); 10984 MyFlags.Flags.setPointerAddrSpace( 10985 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10986 } 10987 if (CLI.RetSExt) 10988 MyFlags.Flags.setSExt(); 10989 if (CLI.RetZExt) 10990 MyFlags.Flags.setZExt(); 10991 if (CLI.IsInReg) 10992 MyFlags.Flags.setInReg(); 10993 CLI.Ins.push_back(MyFlags); 10994 } 10995 } 10996 } 10997 10998 // We push in swifterror return as the last element of CLI.Ins. 10999 ArgListTy &Args = CLI.getArgs(); 11000 if (supportSwiftError()) { 11001 for (const ArgListEntry &Arg : Args) { 11002 if (Arg.IsSwiftError) { 11003 ISD::InputArg MyFlags; 11004 MyFlags.VT = getPointerTy(DL); 11005 MyFlags.ArgVT = EVT(getPointerTy(DL)); 11006 MyFlags.Flags.setSwiftError(); 11007 CLI.Ins.push_back(MyFlags); 11008 } 11009 } 11010 } 11011 11012 // Handle all of the outgoing arguments. 11013 CLI.Outs.clear(); 11014 CLI.OutVals.clear(); 11015 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 11016 SmallVector<EVT, 4> ValueVTs; 11017 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 11018 // FIXME: Split arguments if CLI.IsPostTypeLegalization 11019 Type *FinalType = Args[i].Ty; 11020 if (Args[i].IsByVal) 11021 FinalType = Args[i].IndirectType; 11022 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 11023 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 11024 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 11025 ++Value) { 11026 EVT VT = ValueVTs[Value]; 11027 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 11028 SDValue Op = SDValue(Args[i].Node.getNode(), 11029 Args[i].Node.getResNo() + Value); 11030 ISD::ArgFlagsTy Flags; 11031 11032 // Certain targets (such as MIPS), may have a different ABI alignment 11033 // for a type depending on the context. Give the target a chance to 11034 // specify the alignment it wants. 11035 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 11036 Flags.setOrigAlign(OriginalAlignment); 11037 11038 if (Args[i].Ty->isPointerTy()) { 11039 Flags.setPointer(); 11040 Flags.setPointerAddrSpace( 11041 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 11042 } 11043 if (Args[i].IsZExt) 11044 Flags.setZExt(); 11045 if (Args[i].IsSExt) 11046 Flags.setSExt(); 11047 if (Args[i].IsNoExt) 11048 Flags.setNoExt(); 11049 if (Args[i].IsInReg) { 11050 // If we are using vectorcall calling convention, a structure that is 11051 // passed InReg - is surely an HVA 11052 if (CLI.CallConv == CallingConv::X86_VectorCall && 11053 isa<StructType>(FinalType)) { 11054 // The first value of a structure is marked 11055 if (0 == Value) 11056 Flags.setHvaStart(); 11057 Flags.setHva(); 11058 } 11059 // Set InReg Flag 11060 Flags.setInReg(); 11061 } 11062 if (Args[i].IsSRet) 11063 Flags.setSRet(); 11064 if (Args[i].IsSwiftSelf) 11065 Flags.setSwiftSelf(); 11066 if (Args[i].IsSwiftAsync) 11067 Flags.setSwiftAsync(); 11068 if (Args[i].IsSwiftError) 11069 Flags.setSwiftError(); 11070 if (Args[i].IsCFGuardTarget) 11071 Flags.setCFGuardTarget(); 11072 if (Args[i].IsByVal) 11073 Flags.setByVal(); 11074 if (Args[i].IsByRef) 11075 Flags.setByRef(); 11076 if (Args[i].IsPreallocated) { 11077 Flags.setPreallocated(); 11078 // Set the byval flag for CCAssignFn callbacks that don't know about 11079 // preallocated. This way we can know how many bytes we should've 11080 // allocated and how many bytes a callee cleanup function will pop. If 11081 // we port preallocated to more targets, we'll have to add custom 11082 // preallocated handling in the various CC lowering callbacks. 11083 Flags.setByVal(); 11084 } 11085 if (Args[i].IsInAlloca) { 11086 Flags.setInAlloca(); 11087 // Set the byval flag for CCAssignFn callbacks that don't know about 11088 // inalloca. This way we can know how many bytes we should've allocated 11089 // and how many bytes a callee cleanup function will pop. If we port 11090 // inalloca to more targets, we'll have to add custom inalloca handling 11091 // in the various CC lowering callbacks. 11092 Flags.setByVal(); 11093 } 11094 Align MemAlign; 11095 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 11096 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 11097 Flags.setByValSize(FrameSize); 11098 11099 // info is not there but there are cases it cannot get right. 11100 if (auto MA = Args[i].Alignment) 11101 MemAlign = *MA; 11102 else 11103 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 11104 } else if (auto MA = Args[i].Alignment) { 11105 MemAlign = *MA; 11106 } else { 11107 MemAlign = OriginalAlignment; 11108 } 11109 Flags.setMemAlign(MemAlign); 11110 if (Args[i].IsNest) 11111 Flags.setNest(); 11112 if (NeedsRegBlock) 11113 Flags.setInConsecutiveRegs(); 11114 11115 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11116 CLI.CallConv, VT); 11117 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11118 CLI.CallConv, VT); 11119 SmallVector<SDValue, 4> Parts(NumParts); 11120 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 11121 11122 if (Args[i].IsSExt) 11123 ExtendKind = ISD::SIGN_EXTEND; 11124 else if (Args[i].IsZExt) 11125 ExtendKind = ISD::ZERO_EXTEND; 11126 11127 // Conservatively only handle 'returned' on non-vectors that can be lowered, 11128 // for now. 11129 if (Args[i].IsReturned && !Op.getValueType().isVector() && 11130 CanLowerReturn) { 11131 assert((CLI.RetTy == Args[i].Ty || 11132 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 11133 CLI.RetTy->getPointerAddressSpace() == 11134 Args[i].Ty->getPointerAddressSpace())) && 11135 RetTys.size() == NumValues && "unexpected use of 'returned'"); 11136 // Before passing 'returned' to the target lowering code, ensure that 11137 // either the register MVT and the actual EVT are the same size or that 11138 // the return value and argument are extended in the same way; in these 11139 // cases it's safe to pass the argument register value unchanged as the 11140 // return register value (although it's at the target's option whether 11141 // to do so) 11142 // TODO: allow code generation to take advantage of partially preserved 11143 // registers rather than clobbering the entire register when the 11144 // parameter extension method is not compatible with the return 11145 // extension method 11146 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 11147 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 11148 CLI.RetZExt == Args[i].IsZExt)) 11149 Flags.setReturned(); 11150 } 11151 11152 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 11153 CLI.CallConv, ExtendKind); 11154 11155 for (unsigned j = 0; j != NumParts; ++j) { 11156 // if it isn't first piece, alignment must be 1 11157 // For scalable vectors the scalable part is currently handled 11158 // by individual targets, so we just use the known minimum size here. 11159 ISD::OutputArg MyFlags( 11160 Flags, Parts[j].getValueType().getSimpleVT(), VT, 11161 i < CLI.NumFixedArgs, i, 11162 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 11163 if (NumParts > 1 && j == 0) 11164 MyFlags.Flags.setSplit(); 11165 else if (j != 0) { 11166 MyFlags.Flags.setOrigAlign(Align(1)); 11167 if (j == NumParts - 1) 11168 MyFlags.Flags.setSplitEnd(); 11169 } 11170 11171 CLI.Outs.push_back(MyFlags); 11172 CLI.OutVals.push_back(Parts[j]); 11173 } 11174 11175 if (NeedsRegBlock && Value == NumValues - 1) 11176 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 11177 } 11178 } 11179 11180 SmallVector<SDValue, 4> InVals; 11181 CLI.Chain = LowerCall(CLI, InVals); 11182 11183 // Update CLI.InVals to use outside of this function. 11184 CLI.InVals = InVals; 11185 11186 // Verify that the target's LowerCall behaved as expected. 11187 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 11188 "LowerCall didn't return a valid chain!"); 11189 assert((!CLI.IsTailCall || InVals.empty()) && 11190 "LowerCall emitted a return value for a tail call!"); 11191 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 11192 "LowerCall didn't emit the correct number of values!"); 11193 11194 // For a tail call, the return value is merely live-out and there aren't 11195 // any nodes in the DAG representing it. Return a special value to 11196 // indicate that a tail call has been emitted and no more Instructions 11197 // should be processed in the current block. 11198 if (CLI.IsTailCall) { 11199 CLI.DAG.setRoot(CLI.Chain); 11200 return std::make_pair(SDValue(), SDValue()); 11201 } 11202 11203 #ifndef NDEBUG 11204 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 11205 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 11206 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 11207 "LowerCall emitted a value with the wrong type!"); 11208 } 11209 #endif 11210 11211 SmallVector<SDValue, 4> ReturnValues; 11212 if (!CanLowerReturn) { 11213 // The instruction result is the result of loading from the 11214 // hidden sret parameter. 11215 SmallVector<EVT, 1> PVTs; 11216 Type *PtrRetTy = 11217 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 11218 11219 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 11220 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 11221 EVT PtrVT = PVTs[0]; 11222 11223 unsigned NumValues = RetTys.size(); 11224 ReturnValues.resize(NumValues); 11225 SmallVector<SDValue, 4> Chains(NumValues); 11226 11227 // An aggregate return value cannot wrap around the address space, so 11228 // offsets to its parts don't wrap either. 11229 MachineFunction &MF = CLI.DAG.getMachineFunction(); 11230 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 11231 for (unsigned i = 0; i < NumValues; ++i) { 11232 SDValue Add = 11233 CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 11234 CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT), 11235 SDNodeFlags::NoUnsignedWrap); 11236 SDValue L = CLI.DAG.getLoad( 11237 RetTys[i], CLI.DL, CLI.Chain, Add, 11238 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 11239 DemoteStackIdx, Offsets[i]), 11240 HiddenSRetAlign); 11241 ReturnValues[i] = L; 11242 Chains[i] = L.getValue(1); 11243 } 11244 11245 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 11246 } else { 11247 // Collect the legal value parts into potentially illegal values 11248 // that correspond to the original function's return values. 11249 std::optional<ISD::NodeType> AssertOp; 11250 if (CLI.RetSExt) 11251 AssertOp = ISD::AssertSext; 11252 else if (CLI.RetZExt) 11253 AssertOp = ISD::AssertZext; 11254 unsigned CurReg = 0; 11255 for (EVT VT : RetTys) { 11256 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11257 CLI.CallConv, VT); 11258 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11259 CLI.CallConv, VT); 11260 11261 ReturnValues.push_back(getCopyFromParts( 11262 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 11263 CLI.Chain, CLI.CallConv, AssertOp)); 11264 CurReg += NumRegs; 11265 } 11266 11267 // For a function returning void, there is no return value. We can't create 11268 // such a node, so we just return a null return value in that case. In 11269 // that case, nothing will actually look at the value. 11270 if (ReturnValues.empty()) 11271 return std::make_pair(SDValue(), CLI.Chain); 11272 } 11273 11274 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 11275 CLI.DAG.getVTList(RetTys), ReturnValues); 11276 return std::make_pair(Res, CLI.Chain); 11277 } 11278 11279 /// Places new result values for the node in Results (their number 11280 /// and types must exactly match those of the original return values of 11281 /// the node), or leaves Results empty, which indicates that the node is not 11282 /// to be custom lowered after all. 11283 void TargetLowering::LowerOperationWrapper(SDNode *N, 11284 SmallVectorImpl<SDValue> &Results, 11285 SelectionDAG &DAG) const { 11286 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 11287 11288 if (!Res.getNode()) 11289 return; 11290 11291 // If the original node has one result, take the return value from 11292 // LowerOperation as is. It might not be result number 0. 11293 if (N->getNumValues() == 1) { 11294 Results.push_back(Res); 11295 return; 11296 } 11297 11298 // If the original node has multiple results, then the return node should 11299 // have the same number of results. 11300 assert((N->getNumValues() == Res->getNumValues()) && 11301 "Lowering returned the wrong number of results!"); 11302 11303 // Places new result values base on N result number. 11304 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 11305 Results.push_back(Res.getValue(I)); 11306 } 11307 11308 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11309 llvm_unreachable("LowerOperation not implemented for this target!"); 11310 } 11311 11312 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 11313 unsigned Reg, 11314 ISD::NodeType ExtendType) { 11315 SDValue Op = getNonRegisterValue(V); 11316 assert((Op.getOpcode() != ISD::CopyFromReg || 11317 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 11318 "Copy from a reg to the same reg!"); 11319 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 11320 11321 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11322 // If this is an InlineAsm we have to match the registers required, not the 11323 // notional registers required by the type. 11324 11325 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 11326 std::nullopt); // This is not an ABI copy. 11327 SDValue Chain = DAG.getEntryNode(); 11328 11329 if (ExtendType == ISD::ANY_EXTEND) { 11330 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 11331 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 11332 ExtendType = PreferredExtendIt->second; 11333 } 11334 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 11335 PendingExports.push_back(Chain); 11336 } 11337 11338 #include "llvm/CodeGen/SelectionDAGISel.h" 11339 11340 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 11341 /// entry block, return true. This includes arguments used by switches, since 11342 /// the switch may expand into multiple basic blocks. 11343 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 11344 // With FastISel active, we may be splitting blocks, so force creation 11345 // of virtual registers for all non-dead arguments. 11346 if (FastISel) 11347 return A->use_empty(); 11348 11349 const BasicBlock &Entry = A->getParent()->front(); 11350 for (const User *U : A->users()) 11351 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 11352 return false; // Use not in entry block. 11353 11354 return true; 11355 } 11356 11357 using ArgCopyElisionMapTy = 11358 DenseMap<const Argument *, 11359 std::pair<const AllocaInst *, const StoreInst *>>; 11360 11361 /// Scan the entry block of the function in FuncInfo for arguments that look 11362 /// like copies into a local alloca. Record any copied arguments in 11363 /// ArgCopyElisionCandidates. 11364 static void 11365 findArgumentCopyElisionCandidates(const DataLayout &DL, 11366 FunctionLoweringInfo *FuncInfo, 11367 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 11368 // Record the state of every static alloca used in the entry block. Argument 11369 // allocas are all used in the entry block, so we need approximately as many 11370 // entries as we have arguments. 11371 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 11372 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 11373 unsigned NumArgs = FuncInfo->Fn->arg_size(); 11374 StaticAllocas.reserve(NumArgs * 2); 11375 11376 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 11377 if (!V) 11378 return nullptr; 11379 V = V->stripPointerCasts(); 11380 const auto *AI = dyn_cast<AllocaInst>(V); 11381 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 11382 return nullptr; 11383 auto Iter = StaticAllocas.insert({AI, Unknown}); 11384 return &Iter.first->second; 11385 }; 11386 11387 // Look for stores of arguments to static allocas. Look through bitcasts and 11388 // GEPs to handle type coercions, as long as the alloca is fully initialized 11389 // by the store. Any non-store use of an alloca escapes it and any subsequent 11390 // unanalyzed store might write it. 11391 // FIXME: Handle structs initialized with multiple stores. 11392 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 11393 // Look for stores, and handle non-store uses conservatively. 11394 const auto *SI = dyn_cast<StoreInst>(&I); 11395 if (!SI) { 11396 // We will look through cast uses, so ignore them completely. 11397 if (I.isCast()) 11398 continue; 11399 // Ignore debug info and pseudo op intrinsics, they don't escape or store 11400 // to allocas. 11401 if (I.isDebugOrPseudoInst()) 11402 continue; 11403 // This is an unknown instruction. Assume it escapes or writes to all 11404 // static alloca operands. 11405 for (const Use &U : I.operands()) { 11406 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 11407 *Info = StaticAllocaInfo::Clobbered; 11408 } 11409 continue; 11410 } 11411 11412 // If the stored value is a static alloca, mark it as escaped. 11413 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 11414 *Info = StaticAllocaInfo::Clobbered; 11415 11416 // Check if the destination is a static alloca. 11417 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 11418 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 11419 if (!Info) 11420 continue; 11421 const AllocaInst *AI = cast<AllocaInst>(Dst); 11422 11423 // Skip allocas that have been initialized or clobbered. 11424 if (*Info != StaticAllocaInfo::Unknown) 11425 continue; 11426 11427 // Check if the stored value is an argument, and that this store fully 11428 // initializes the alloca. 11429 // If the argument type has padding bits we can't directly forward a pointer 11430 // as the upper bits may contain garbage. 11431 // Don't elide copies from the same argument twice. 11432 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 11433 const auto *Arg = dyn_cast<Argument>(Val); 11434 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 11435 Arg->getType()->isEmptyTy() || 11436 DL.getTypeStoreSize(Arg->getType()) != 11437 DL.getTypeAllocSize(AI->getAllocatedType()) || 11438 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 11439 ArgCopyElisionCandidates.count(Arg)) { 11440 *Info = StaticAllocaInfo::Clobbered; 11441 continue; 11442 } 11443 11444 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 11445 << '\n'); 11446 11447 // Mark this alloca and store for argument copy elision. 11448 *Info = StaticAllocaInfo::Elidable; 11449 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 11450 11451 // Stop scanning if we've seen all arguments. This will happen early in -O0 11452 // builds, which is useful, because -O0 builds have large entry blocks and 11453 // many allocas. 11454 if (ArgCopyElisionCandidates.size() == NumArgs) 11455 break; 11456 } 11457 } 11458 11459 /// Try to elide argument copies from memory into a local alloca. Succeeds if 11460 /// ArgVal is a load from a suitable fixed stack object. 11461 static void tryToElideArgumentCopy( 11462 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 11463 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 11464 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 11465 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 11466 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 11467 // Check if this is a load from a fixed stack object. 11468 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 11469 if (!LNode) 11470 return; 11471 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 11472 if (!FINode) 11473 return; 11474 11475 // Check that the fixed stack object is the right size and alignment. 11476 // Look at the alignment that the user wrote on the alloca instead of looking 11477 // at the stack object. 11478 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 11479 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 11480 const AllocaInst *AI = ArgCopyIter->second.first; 11481 int FixedIndex = FINode->getIndex(); 11482 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 11483 int OldIndex = AllocaIndex; 11484 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 11485 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 11486 LLVM_DEBUG( 11487 dbgs() << " argument copy elision failed due to bad fixed stack " 11488 "object size\n"); 11489 return; 11490 } 11491 Align RequiredAlignment = AI->getAlign(); 11492 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 11493 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 11494 "greater than stack argument alignment (" 11495 << DebugStr(RequiredAlignment) << " vs " 11496 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 11497 return; 11498 } 11499 11500 // Perform the elision. Delete the old stack object and replace its only use 11501 // in the variable info map. Mark the stack object as mutable and aliased. 11502 LLVM_DEBUG({ 11503 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 11504 << " Replacing frame index " << OldIndex << " with " << FixedIndex 11505 << '\n'; 11506 }); 11507 MFI.RemoveStackObject(OldIndex); 11508 MFI.setIsImmutableObjectIndex(FixedIndex, false); 11509 MFI.setIsAliasedObjectIndex(FixedIndex, true); 11510 AllocaIndex = FixedIndex; 11511 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 11512 for (SDValue ArgVal : ArgVals) 11513 Chains.push_back(ArgVal.getValue(1)); 11514 11515 // Avoid emitting code for the store implementing the copy. 11516 const StoreInst *SI = ArgCopyIter->second.second; 11517 ElidedArgCopyInstrs.insert(SI); 11518 11519 // Check for uses of the argument again so that we can avoid exporting ArgVal 11520 // if it is't used by anything other than the store. 11521 for (const Value *U : Arg.users()) { 11522 if (U != SI) { 11523 ArgHasUses = true; 11524 break; 11525 } 11526 } 11527 } 11528 11529 void SelectionDAGISel::LowerArguments(const Function &F) { 11530 SelectionDAG &DAG = SDB->DAG; 11531 SDLoc dl = SDB->getCurSDLoc(); 11532 const DataLayout &DL = DAG.getDataLayout(); 11533 SmallVector<ISD::InputArg, 16> Ins; 11534 11535 // In Naked functions we aren't going to save any registers. 11536 if (F.hasFnAttribute(Attribute::Naked)) 11537 return; 11538 11539 if (!FuncInfo->CanLowerReturn) { 11540 // Put in an sret pointer parameter before all the other parameters. 11541 SmallVector<EVT, 1> ValueVTs; 11542 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11543 PointerType::get(F.getContext(), 11544 DAG.getDataLayout().getAllocaAddrSpace()), 11545 ValueVTs); 11546 11547 // NOTE: Assuming that a pointer will never break down to more than one VT 11548 // or one register. 11549 ISD::ArgFlagsTy Flags; 11550 Flags.setSRet(); 11551 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 11552 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 11553 ISD::InputArg::NoArgIndex, 0); 11554 Ins.push_back(RetArg); 11555 } 11556 11557 // Look for stores of arguments to static allocas. Mark such arguments with a 11558 // flag to ask the target to give us the memory location of that argument if 11559 // available. 11560 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11561 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11562 ArgCopyElisionCandidates); 11563 11564 // Set up the incoming argument description vector. 11565 for (const Argument &Arg : F.args()) { 11566 unsigned ArgNo = Arg.getArgNo(); 11567 SmallVector<EVT, 4> ValueVTs; 11568 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11569 bool isArgValueUsed = !Arg.use_empty(); 11570 unsigned PartBase = 0; 11571 Type *FinalType = Arg.getType(); 11572 if (Arg.hasAttribute(Attribute::ByVal)) 11573 FinalType = Arg.getParamByValType(); 11574 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11575 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11576 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11577 Value != NumValues; ++Value) { 11578 EVT VT = ValueVTs[Value]; 11579 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11580 ISD::ArgFlagsTy Flags; 11581 11582 11583 if (Arg.getType()->isPointerTy()) { 11584 Flags.setPointer(); 11585 Flags.setPointerAddrSpace( 11586 cast<PointerType>(Arg.getType())->getAddressSpace()); 11587 } 11588 if (Arg.hasAttribute(Attribute::ZExt)) 11589 Flags.setZExt(); 11590 if (Arg.hasAttribute(Attribute::SExt)) 11591 Flags.setSExt(); 11592 if (Arg.hasAttribute(Attribute::InReg)) { 11593 // If we are using vectorcall calling convention, a structure that is 11594 // passed InReg - is surely an HVA 11595 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11596 isa<StructType>(Arg.getType())) { 11597 // The first value of a structure is marked 11598 if (0 == Value) 11599 Flags.setHvaStart(); 11600 Flags.setHva(); 11601 } 11602 // Set InReg Flag 11603 Flags.setInReg(); 11604 } 11605 if (Arg.hasAttribute(Attribute::StructRet)) 11606 Flags.setSRet(); 11607 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11608 Flags.setSwiftSelf(); 11609 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11610 Flags.setSwiftAsync(); 11611 if (Arg.hasAttribute(Attribute::SwiftError)) 11612 Flags.setSwiftError(); 11613 if (Arg.hasAttribute(Attribute::ByVal)) 11614 Flags.setByVal(); 11615 if (Arg.hasAttribute(Attribute::ByRef)) 11616 Flags.setByRef(); 11617 if (Arg.hasAttribute(Attribute::InAlloca)) { 11618 Flags.setInAlloca(); 11619 // Set the byval flag for CCAssignFn callbacks that don't know about 11620 // inalloca. This way we can know how many bytes we should've allocated 11621 // and how many bytes a callee cleanup function will pop. If we port 11622 // inalloca to more targets, we'll have to add custom inalloca handling 11623 // in the various CC lowering callbacks. 11624 Flags.setByVal(); 11625 } 11626 if (Arg.hasAttribute(Attribute::Preallocated)) { 11627 Flags.setPreallocated(); 11628 // Set the byval flag for CCAssignFn callbacks that don't know about 11629 // preallocated. This way we can know how many bytes we should've 11630 // allocated and how many bytes a callee cleanup function will pop. If 11631 // we port preallocated to more targets, we'll have to add custom 11632 // preallocated handling in the various CC lowering callbacks. 11633 Flags.setByVal(); 11634 } 11635 11636 // Certain targets (such as MIPS), may have a different ABI alignment 11637 // for a type depending on the context. Give the target a chance to 11638 // specify the alignment it wants. 11639 const Align OriginalAlignment( 11640 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11641 Flags.setOrigAlign(OriginalAlignment); 11642 11643 Align MemAlign; 11644 Type *ArgMemTy = nullptr; 11645 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11646 Flags.isByRef()) { 11647 if (!ArgMemTy) 11648 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11649 11650 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11651 11652 // For in-memory arguments, size and alignment should be passed from FE. 11653 // BE will guess if this info is not there but there are cases it cannot 11654 // get right. 11655 if (auto ParamAlign = Arg.getParamStackAlign()) 11656 MemAlign = *ParamAlign; 11657 else if ((ParamAlign = Arg.getParamAlign())) 11658 MemAlign = *ParamAlign; 11659 else 11660 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11661 if (Flags.isByRef()) 11662 Flags.setByRefSize(MemSize); 11663 else 11664 Flags.setByValSize(MemSize); 11665 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11666 MemAlign = *ParamAlign; 11667 } else { 11668 MemAlign = OriginalAlignment; 11669 } 11670 Flags.setMemAlign(MemAlign); 11671 11672 if (Arg.hasAttribute(Attribute::Nest)) 11673 Flags.setNest(); 11674 if (NeedsRegBlock) 11675 Flags.setInConsecutiveRegs(); 11676 if (ArgCopyElisionCandidates.count(&Arg)) 11677 Flags.setCopyElisionCandidate(); 11678 if (Arg.hasAttribute(Attribute::Returned)) 11679 Flags.setReturned(); 11680 11681 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11682 *CurDAG->getContext(), F.getCallingConv(), VT); 11683 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11684 *CurDAG->getContext(), F.getCallingConv(), VT); 11685 for (unsigned i = 0; i != NumRegs; ++i) { 11686 // For scalable vectors, use the minimum size; individual targets 11687 // are responsible for handling scalable vector arguments and 11688 // return values. 11689 ISD::InputArg MyFlags( 11690 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11691 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11692 if (NumRegs > 1 && i == 0) 11693 MyFlags.Flags.setSplit(); 11694 // if it isn't first piece, alignment must be 1 11695 else if (i > 0) { 11696 MyFlags.Flags.setOrigAlign(Align(1)); 11697 if (i == NumRegs - 1) 11698 MyFlags.Flags.setSplitEnd(); 11699 } 11700 Ins.push_back(MyFlags); 11701 } 11702 if (NeedsRegBlock && Value == NumValues - 1) 11703 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11704 PartBase += VT.getStoreSize().getKnownMinValue(); 11705 } 11706 } 11707 11708 // Call the target to set up the argument values. 11709 SmallVector<SDValue, 8> InVals; 11710 SDValue NewRoot = TLI->LowerFormalArguments( 11711 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11712 11713 // Verify that the target's LowerFormalArguments behaved as expected. 11714 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11715 "LowerFormalArguments didn't return a valid chain!"); 11716 assert(InVals.size() == Ins.size() && 11717 "LowerFormalArguments didn't emit the correct number of values!"); 11718 LLVM_DEBUG({ 11719 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11720 assert(InVals[i].getNode() && 11721 "LowerFormalArguments emitted a null value!"); 11722 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11723 "LowerFormalArguments emitted a value with the wrong type!"); 11724 } 11725 }); 11726 11727 // Update the DAG with the new chain value resulting from argument lowering. 11728 DAG.setRoot(NewRoot); 11729 11730 // Set up the argument values. 11731 unsigned i = 0; 11732 if (!FuncInfo->CanLowerReturn) { 11733 // Create a virtual register for the sret pointer, and put in a copy 11734 // from the sret argument into it. 11735 SmallVector<EVT, 1> ValueVTs; 11736 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11737 PointerType::get(F.getContext(), 11738 DAG.getDataLayout().getAllocaAddrSpace()), 11739 ValueVTs); 11740 MVT VT = ValueVTs[0].getSimpleVT(); 11741 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11742 std::optional<ISD::NodeType> AssertOp; 11743 SDValue ArgValue = 11744 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11745 F.getCallingConv(), AssertOp); 11746 11747 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11748 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11749 Register SRetReg = 11750 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11751 FuncInfo->DemoteRegister = SRetReg; 11752 NewRoot = 11753 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11754 DAG.setRoot(NewRoot); 11755 11756 // i indexes lowered arguments. Bump it past the hidden sret argument. 11757 ++i; 11758 } 11759 11760 SmallVector<SDValue, 4> Chains; 11761 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11762 for (const Argument &Arg : F.args()) { 11763 SmallVector<SDValue, 4> ArgValues; 11764 SmallVector<EVT, 4> ValueVTs; 11765 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11766 unsigned NumValues = ValueVTs.size(); 11767 if (NumValues == 0) 11768 continue; 11769 11770 bool ArgHasUses = !Arg.use_empty(); 11771 11772 // Elide the copying store if the target loaded this argument from a 11773 // suitable fixed stack object. 11774 if (Ins[i].Flags.isCopyElisionCandidate()) { 11775 unsigned NumParts = 0; 11776 for (EVT VT : ValueVTs) 11777 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11778 F.getCallingConv(), VT); 11779 11780 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11781 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11782 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11783 } 11784 11785 // If this argument is unused then remember its value. It is used to generate 11786 // debugging information. 11787 bool isSwiftErrorArg = 11788 TLI->supportSwiftError() && 11789 Arg.hasAttribute(Attribute::SwiftError); 11790 if (!ArgHasUses && !isSwiftErrorArg) { 11791 SDB->setUnusedArgValue(&Arg, InVals[i]); 11792 11793 // Also remember any frame index for use in FastISel. 11794 if (FrameIndexSDNode *FI = 11795 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11796 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11797 } 11798 11799 for (unsigned Val = 0; Val != NumValues; ++Val) { 11800 EVT VT = ValueVTs[Val]; 11801 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11802 F.getCallingConv(), VT); 11803 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11804 *CurDAG->getContext(), F.getCallingConv(), VT); 11805 11806 // Even an apparent 'unused' swifterror argument needs to be returned. So 11807 // we do generate a copy for it that can be used on return from the 11808 // function. 11809 if (ArgHasUses || isSwiftErrorArg) { 11810 std::optional<ISD::NodeType> AssertOp; 11811 if (Arg.hasAttribute(Attribute::SExt)) 11812 AssertOp = ISD::AssertSext; 11813 else if (Arg.hasAttribute(Attribute::ZExt)) 11814 AssertOp = ISD::AssertZext; 11815 11816 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11817 PartVT, VT, nullptr, NewRoot, 11818 F.getCallingConv(), AssertOp)); 11819 } 11820 11821 i += NumParts; 11822 } 11823 11824 // We don't need to do anything else for unused arguments. 11825 if (ArgValues.empty()) 11826 continue; 11827 11828 // Note down frame index. 11829 if (FrameIndexSDNode *FI = 11830 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11831 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11832 11833 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11834 SDB->getCurSDLoc()); 11835 11836 SDB->setValue(&Arg, Res); 11837 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11838 // We want to associate the argument with the frame index, among 11839 // involved operands, that correspond to the lowest address. The 11840 // getCopyFromParts function, called earlier, is swapping the order of 11841 // the operands to BUILD_PAIR depending on endianness. The result of 11842 // that swapping is that the least significant bits of the argument will 11843 // be in the first operand of the BUILD_PAIR node, and the most 11844 // significant bits will be in the second operand. 11845 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11846 if (LoadSDNode *LNode = 11847 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11848 if (FrameIndexSDNode *FI = 11849 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11850 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11851 } 11852 11853 // Analyses past this point are naive and don't expect an assertion. 11854 if (Res.getOpcode() == ISD::AssertZext) 11855 Res = Res.getOperand(0); 11856 11857 // Update the SwiftErrorVRegDefMap. 11858 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11859 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11860 if (Reg.isVirtual()) 11861 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11862 Reg); 11863 } 11864 11865 // If this argument is live outside of the entry block, insert a copy from 11866 // wherever we got it to the vreg that other BB's will reference it as. 11867 if (Res.getOpcode() == ISD::CopyFromReg) { 11868 // If we can, though, try to skip creating an unnecessary vreg. 11869 // FIXME: This isn't very clean... it would be nice to make this more 11870 // general. 11871 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11872 if (Reg.isVirtual()) { 11873 FuncInfo->ValueMap[&Arg] = Reg; 11874 continue; 11875 } 11876 } 11877 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11878 FuncInfo->InitializeRegForValue(&Arg); 11879 SDB->CopyToExportRegsIfNeeded(&Arg); 11880 } 11881 } 11882 11883 if (!Chains.empty()) { 11884 Chains.push_back(NewRoot); 11885 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11886 } 11887 11888 DAG.setRoot(NewRoot); 11889 11890 assert(i == InVals.size() && "Argument register count mismatch!"); 11891 11892 // If any argument copy elisions occurred and we have debug info, update the 11893 // stale frame indices used in the dbg.declare variable info table. 11894 if (!ArgCopyElisionFrameIndexMap.empty()) { 11895 for (MachineFunction::VariableDbgInfo &VI : 11896 MF->getInStackSlotVariableDbgInfo()) { 11897 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11898 if (I != ArgCopyElisionFrameIndexMap.end()) 11899 VI.updateStackSlot(I->second); 11900 } 11901 } 11902 11903 // Finally, if the target has anything special to do, allow it to do so. 11904 emitFunctionEntryCode(); 11905 } 11906 11907 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11908 /// ensure constants are generated when needed. Remember the virtual registers 11909 /// that need to be added to the Machine PHI nodes as input. We cannot just 11910 /// directly add them, because expansion might result in multiple MBB's for one 11911 /// BB. As such, the start of the BB might correspond to a different MBB than 11912 /// the end. 11913 void 11914 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11915 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11916 11917 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11918 11919 // Check PHI nodes in successors that expect a value to be available from this 11920 // block. 11921 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11922 if (!isa<PHINode>(SuccBB->begin())) continue; 11923 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB); 11924 11925 // If this terminator has multiple identical successors (common for 11926 // switches), only handle each succ once. 11927 if (!SuccsHandled.insert(SuccMBB).second) 11928 continue; 11929 11930 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11931 11932 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11933 // nodes and Machine PHI nodes, but the incoming operands have not been 11934 // emitted yet. 11935 for (const PHINode &PN : SuccBB->phis()) { 11936 // Ignore dead phi's. 11937 if (PN.use_empty()) 11938 continue; 11939 11940 // Skip empty types 11941 if (PN.getType()->isEmptyTy()) 11942 continue; 11943 11944 unsigned Reg; 11945 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11946 11947 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11948 unsigned &RegOut = ConstantsOut[C]; 11949 if (RegOut == 0) { 11950 RegOut = FuncInfo.CreateRegs(C); 11951 // We need to zero/sign extend ConstantInt phi operands to match 11952 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11953 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11954 if (auto *CI = dyn_cast<ConstantInt>(C)) 11955 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11956 : ISD::ZERO_EXTEND; 11957 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11958 } 11959 Reg = RegOut; 11960 } else { 11961 DenseMap<const Value *, Register>::iterator I = 11962 FuncInfo.ValueMap.find(PHIOp); 11963 if (I != FuncInfo.ValueMap.end()) 11964 Reg = I->second; 11965 else { 11966 assert(isa<AllocaInst>(PHIOp) && 11967 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11968 "Didn't codegen value into a register!??"); 11969 Reg = FuncInfo.CreateRegs(PHIOp); 11970 CopyValueToVirtualRegister(PHIOp, Reg); 11971 } 11972 } 11973 11974 // Remember that this register needs to added to the machine PHI node as 11975 // the input for this MBB. 11976 SmallVector<EVT, 4> ValueVTs; 11977 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11978 for (EVT VT : ValueVTs) { 11979 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11980 for (unsigned i = 0; i != NumRegisters; ++i) 11981 FuncInfo.PHINodesToUpdate.push_back( 11982 std::make_pair(&*MBBI++, Reg + i)); 11983 Reg += NumRegisters; 11984 } 11985 } 11986 } 11987 11988 ConstantsOut.clear(); 11989 } 11990 11991 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11992 MachineFunction::iterator I(MBB); 11993 if (++I == FuncInfo.MF->end()) 11994 return nullptr; 11995 return &*I; 11996 } 11997 11998 /// During lowering new call nodes can be created (such as memset, etc.). 11999 /// Those will become new roots of the current DAG, but complications arise 12000 /// when they are tail calls. In such cases, the call lowering will update 12001 /// the root, but the builder still needs to know that a tail call has been 12002 /// lowered in order to avoid generating an additional return. 12003 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 12004 // If the node is null, we do have a tail call. 12005 if (MaybeTC.getNode() != nullptr) 12006 DAG.setRoot(MaybeTC); 12007 else 12008 HasTailCall = true; 12009 } 12010 12011 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 12012 MachineBasicBlock *SwitchMBB, 12013 MachineBasicBlock *DefaultMBB) { 12014 MachineFunction *CurMF = FuncInfo.MF; 12015 MachineBasicBlock *NextMBB = nullptr; 12016 MachineFunction::iterator BBI(W.MBB); 12017 if (++BBI != FuncInfo.MF->end()) 12018 NextMBB = &*BBI; 12019 12020 unsigned Size = W.LastCluster - W.FirstCluster + 1; 12021 12022 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12023 12024 if (Size == 2 && W.MBB == SwitchMBB) { 12025 // If any two of the cases has the same destination, and if one value 12026 // is the same as the other, but has one bit unset that the other has set, 12027 // use bit manipulation to do two compares at once. For example: 12028 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 12029 // TODO: This could be extended to merge any 2 cases in switches with 3 12030 // cases. 12031 // TODO: Handle cases where W.CaseBB != SwitchBB. 12032 CaseCluster &Small = *W.FirstCluster; 12033 CaseCluster &Big = *W.LastCluster; 12034 12035 if (Small.Low == Small.High && Big.Low == Big.High && 12036 Small.MBB == Big.MBB) { 12037 const APInt &SmallValue = Small.Low->getValue(); 12038 const APInt &BigValue = Big.Low->getValue(); 12039 12040 // Check that there is only one bit different. 12041 APInt CommonBit = BigValue ^ SmallValue; 12042 if (CommonBit.isPowerOf2()) { 12043 SDValue CondLHS = getValue(Cond); 12044 EVT VT = CondLHS.getValueType(); 12045 SDLoc DL = getCurSDLoc(); 12046 12047 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 12048 DAG.getConstant(CommonBit, DL, VT)); 12049 SDValue Cond = DAG.getSetCC( 12050 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 12051 ISD::SETEQ); 12052 12053 // Update successor info. 12054 // Both Small and Big will jump to Small.BB, so we sum up the 12055 // probabilities. 12056 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 12057 if (BPI) 12058 addSuccessorWithProb( 12059 SwitchMBB, DefaultMBB, 12060 // The default destination is the first successor in IR. 12061 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 12062 else 12063 addSuccessorWithProb(SwitchMBB, DefaultMBB); 12064 12065 // Insert the true branch. 12066 SDValue BrCond = 12067 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 12068 DAG.getBasicBlock(Small.MBB)); 12069 // Insert the false branch. 12070 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 12071 DAG.getBasicBlock(DefaultMBB)); 12072 12073 DAG.setRoot(BrCond); 12074 return; 12075 } 12076 } 12077 } 12078 12079 if (TM.getOptLevel() != CodeGenOptLevel::None) { 12080 // Here, we order cases by probability so the most likely case will be 12081 // checked first. However, two clusters can have the same probability in 12082 // which case their relative ordering is non-deterministic. So we use Low 12083 // as a tie-breaker as clusters are guaranteed to never overlap. 12084 llvm::sort(W.FirstCluster, W.LastCluster + 1, 12085 [](const CaseCluster &a, const CaseCluster &b) { 12086 return a.Prob != b.Prob ? 12087 a.Prob > b.Prob : 12088 a.Low->getValue().slt(b.Low->getValue()); 12089 }); 12090 12091 // Rearrange the case blocks so that the last one falls through if possible 12092 // without changing the order of probabilities. 12093 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 12094 --I; 12095 if (I->Prob > W.LastCluster->Prob) 12096 break; 12097 if (I->Kind == CC_Range && I->MBB == NextMBB) { 12098 std::swap(*I, *W.LastCluster); 12099 break; 12100 } 12101 } 12102 } 12103 12104 // Compute total probability. 12105 BranchProbability DefaultProb = W.DefaultProb; 12106 BranchProbability UnhandledProbs = DefaultProb; 12107 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 12108 UnhandledProbs += I->Prob; 12109 12110 MachineBasicBlock *CurMBB = W.MBB; 12111 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 12112 bool FallthroughUnreachable = false; 12113 MachineBasicBlock *Fallthrough; 12114 if (I == W.LastCluster) { 12115 // For the last cluster, fall through to the default destination. 12116 Fallthrough = DefaultMBB; 12117 FallthroughUnreachable = isa<UnreachableInst>( 12118 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 12119 } else { 12120 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 12121 CurMF->insert(BBI, Fallthrough); 12122 // Put Cond in a virtual register to make it available from the new blocks. 12123 ExportFromCurrentBlock(Cond); 12124 } 12125 UnhandledProbs -= I->Prob; 12126 12127 switch (I->Kind) { 12128 case CC_JumpTable: { 12129 // FIXME: Optimize away range check based on pivot comparisons. 12130 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 12131 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 12132 12133 // The jump block hasn't been inserted yet; insert it here. 12134 MachineBasicBlock *JumpMBB = JT->MBB; 12135 CurMF->insert(BBI, JumpMBB); 12136 12137 auto JumpProb = I->Prob; 12138 auto FallthroughProb = UnhandledProbs; 12139 12140 // If the default statement is a target of the jump table, we evenly 12141 // distribute the default probability to successors of CurMBB. Also 12142 // update the probability on the edge from JumpMBB to Fallthrough. 12143 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 12144 SE = JumpMBB->succ_end(); 12145 SI != SE; ++SI) { 12146 if (*SI == DefaultMBB) { 12147 JumpProb += DefaultProb / 2; 12148 FallthroughProb -= DefaultProb / 2; 12149 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 12150 JumpMBB->normalizeSuccProbs(); 12151 break; 12152 } 12153 } 12154 12155 // If the default clause is unreachable, propagate that knowledge into 12156 // JTH->FallthroughUnreachable which will use it to suppress the range 12157 // check. 12158 // 12159 // However, don't do this if we're doing branch target enforcement, 12160 // because a table branch _without_ a range check can be a tempting JOP 12161 // gadget - out-of-bounds inputs that are impossible in correct 12162 // execution become possible again if an attacker can influence the 12163 // control flow. So if an attacker doesn't already have a BTI bypass 12164 // available, we don't want them to be able to get one out of this 12165 // table branch. 12166 if (FallthroughUnreachable) { 12167 Function &CurFunc = CurMF->getFunction(); 12168 if (!CurFunc.hasFnAttribute("branch-target-enforcement")) 12169 JTH->FallthroughUnreachable = true; 12170 } 12171 12172 if (!JTH->FallthroughUnreachable) 12173 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 12174 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 12175 CurMBB->normalizeSuccProbs(); 12176 12177 // The jump table header will be inserted in our current block, do the 12178 // range check, and fall through to our fallthrough block. 12179 JTH->HeaderBB = CurMBB; 12180 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 12181 12182 // If we're in the right place, emit the jump table header right now. 12183 if (CurMBB == SwitchMBB) { 12184 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 12185 JTH->Emitted = true; 12186 } 12187 break; 12188 } 12189 case CC_BitTests: { 12190 // FIXME: Optimize away range check based on pivot comparisons. 12191 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 12192 12193 // The bit test blocks haven't been inserted yet; insert them here. 12194 for (BitTestCase &BTC : BTB->Cases) 12195 CurMF->insert(BBI, BTC.ThisBB); 12196 12197 // Fill in fields of the BitTestBlock. 12198 BTB->Parent = CurMBB; 12199 BTB->Default = Fallthrough; 12200 12201 BTB->DefaultProb = UnhandledProbs; 12202 // If the cases in bit test don't form a contiguous range, we evenly 12203 // distribute the probability on the edge to Fallthrough to two 12204 // successors of CurMBB. 12205 if (!BTB->ContiguousRange) { 12206 BTB->Prob += DefaultProb / 2; 12207 BTB->DefaultProb -= DefaultProb / 2; 12208 } 12209 12210 if (FallthroughUnreachable) 12211 BTB->FallthroughUnreachable = true; 12212 12213 // If we're in the right place, emit the bit test header right now. 12214 if (CurMBB == SwitchMBB) { 12215 visitBitTestHeader(*BTB, SwitchMBB); 12216 BTB->Emitted = true; 12217 } 12218 break; 12219 } 12220 case CC_Range: { 12221 const Value *RHS, *LHS, *MHS; 12222 ISD::CondCode CC; 12223 if (I->Low == I->High) { 12224 // Check Cond == I->Low. 12225 CC = ISD::SETEQ; 12226 LHS = Cond; 12227 RHS=I->Low; 12228 MHS = nullptr; 12229 } else { 12230 // Check I->Low <= Cond <= I->High. 12231 CC = ISD::SETLE; 12232 LHS = I->Low; 12233 MHS = Cond; 12234 RHS = I->High; 12235 } 12236 12237 // If Fallthrough is unreachable, fold away the comparison. 12238 if (FallthroughUnreachable) 12239 CC = ISD::SETTRUE; 12240 12241 // The false probability is the sum of all unhandled cases. 12242 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 12243 getCurSDLoc(), I->Prob, UnhandledProbs); 12244 12245 if (CurMBB == SwitchMBB) 12246 visitSwitchCase(CB, SwitchMBB); 12247 else 12248 SL->SwitchCases.push_back(CB); 12249 12250 break; 12251 } 12252 } 12253 CurMBB = Fallthrough; 12254 } 12255 } 12256 12257 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 12258 const SwitchWorkListItem &W, 12259 Value *Cond, 12260 MachineBasicBlock *SwitchMBB) { 12261 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 12262 "Clusters not sorted?"); 12263 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 12264 12265 auto [LastLeft, FirstRight, LeftProb, RightProb] = 12266 SL->computeSplitWorkItemInfo(W); 12267 12268 // Use the first element on the right as pivot since we will make less-than 12269 // comparisons against it. 12270 CaseClusterIt PivotCluster = FirstRight; 12271 assert(PivotCluster > W.FirstCluster); 12272 assert(PivotCluster <= W.LastCluster); 12273 12274 CaseClusterIt FirstLeft = W.FirstCluster; 12275 CaseClusterIt LastRight = W.LastCluster; 12276 12277 const ConstantInt *Pivot = PivotCluster->Low; 12278 12279 // New blocks will be inserted immediately after the current one. 12280 MachineFunction::iterator BBI(W.MBB); 12281 ++BBI; 12282 12283 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 12284 // we can branch to its destination directly if it's squeezed exactly in 12285 // between the known lower bound and Pivot - 1. 12286 MachineBasicBlock *LeftMBB; 12287 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 12288 FirstLeft->Low == W.GE && 12289 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 12290 LeftMBB = FirstLeft->MBB; 12291 } else { 12292 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12293 FuncInfo.MF->insert(BBI, LeftMBB); 12294 WorkList.push_back( 12295 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 12296 // Put Cond in a virtual register to make it available from the new blocks. 12297 ExportFromCurrentBlock(Cond); 12298 } 12299 12300 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 12301 // single cluster, RHS.Low == Pivot, and we can branch to its destination 12302 // directly if RHS.High equals the current upper bound. 12303 MachineBasicBlock *RightMBB; 12304 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 12305 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 12306 RightMBB = FirstRight->MBB; 12307 } else { 12308 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12309 FuncInfo.MF->insert(BBI, RightMBB); 12310 WorkList.push_back( 12311 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 12312 // Put Cond in a virtual register to make it available from the new blocks. 12313 ExportFromCurrentBlock(Cond); 12314 } 12315 12316 // Create the CaseBlock record that will be used to lower the branch. 12317 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 12318 getCurSDLoc(), LeftProb, RightProb); 12319 12320 if (W.MBB == SwitchMBB) 12321 visitSwitchCase(CB, SwitchMBB); 12322 else 12323 SL->SwitchCases.push_back(CB); 12324 } 12325 12326 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 12327 // from the swith statement. 12328 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 12329 BranchProbability PeeledCaseProb) { 12330 if (PeeledCaseProb == BranchProbability::getOne()) 12331 return BranchProbability::getZero(); 12332 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 12333 12334 uint32_t Numerator = CaseProb.getNumerator(); 12335 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 12336 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 12337 } 12338 12339 // Try to peel the top probability case if it exceeds the threshold. 12340 // Return current MachineBasicBlock for the switch statement if the peeling 12341 // does not occur. 12342 // If the peeling is performed, return the newly created MachineBasicBlock 12343 // for the peeled switch statement. Also update Clusters to remove the peeled 12344 // case. PeeledCaseProb is the BranchProbability for the peeled case. 12345 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 12346 const SwitchInst &SI, CaseClusterVector &Clusters, 12347 BranchProbability &PeeledCaseProb) { 12348 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12349 // Don't perform if there is only one cluster or optimizing for size. 12350 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 12351 TM.getOptLevel() == CodeGenOptLevel::None || 12352 SwitchMBB->getParent()->getFunction().hasMinSize()) 12353 return SwitchMBB; 12354 12355 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 12356 unsigned PeeledCaseIndex = 0; 12357 bool SwitchPeeled = false; 12358 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 12359 CaseCluster &CC = Clusters[Index]; 12360 if (CC.Prob < TopCaseProb) 12361 continue; 12362 TopCaseProb = CC.Prob; 12363 PeeledCaseIndex = Index; 12364 SwitchPeeled = true; 12365 } 12366 if (!SwitchPeeled) 12367 return SwitchMBB; 12368 12369 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 12370 << TopCaseProb << "\n"); 12371 12372 // Record the MBB for the peeled switch statement. 12373 MachineFunction::iterator BBI(SwitchMBB); 12374 ++BBI; 12375 MachineBasicBlock *PeeledSwitchMBB = 12376 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 12377 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 12378 12379 ExportFromCurrentBlock(SI.getCondition()); 12380 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 12381 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 12382 nullptr, nullptr, TopCaseProb.getCompl()}; 12383 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 12384 12385 Clusters.erase(PeeledCaseIt); 12386 for (CaseCluster &CC : Clusters) { 12387 LLVM_DEBUG( 12388 dbgs() << "Scale the probablity for one cluster, before scaling: " 12389 << CC.Prob << "\n"); 12390 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 12391 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 12392 } 12393 PeeledCaseProb = TopCaseProb; 12394 return PeeledSwitchMBB; 12395 } 12396 12397 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 12398 // Extract cases from the switch. 12399 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12400 CaseClusterVector Clusters; 12401 Clusters.reserve(SI.getNumCases()); 12402 for (auto I : SI.cases()) { 12403 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor()); 12404 const ConstantInt *CaseVal = I.getCaseValue(); 12405 BranchProbability Prob = 12406 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 12407 : BranchProbability(1, SI.getNumCases() + 1); 12408 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 12409 } 12410 12411 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest()); 12412 12413 // Cluster adjacent cases with the same destination. We do this at all 12414 // optimization levels because it's cheap to do and will make codegen faster 12415 // if there are many clusters. 12416 sortAndRangeify(Clusters); 12417 12418 // The branch probablity of the peeled case. 12419 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 12420 MachineBasicBlock *PeeledSwitchMBB = 12421 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 12422 12423 // If there is only the default destination, jump there directly. 12424 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12425 if (Clusters.empty()) { 12426 assert(PeeledSwitchMBB == SwitchMBB); 12427 SwitchMBB->addSuccessor(DefaultMBB); 12428 if (DefaultMBB != NextBlock(SwitchMBB)) { 12429 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 12430 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 12431 } 12432 return; 12433 } 12434 12435 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 12436 DAG.getBFI()); 12437 SL->findBitTestClusters(Clusters, &SI); 12438 12439 LLVM_DEBUG({ 12440 dbgs() << "Case clusters: "; 12441 for (const CaseCluster &C : Clusters) { 12442 if (C.Kind == CC_JumpTable) 12443 dbgs() << "JT:"; 12444 if (C.Kind == CC_BitTests) 12445 dbgs() << "BT:"; 12446 12447 C.Low->getValue().print(dbgs(), true); 12448 if (C.Low != C.High) { 12449 dbgs() << '-'; 12450 C.High->getValue().print(dbgs(), true); 12451 } 12452 dbgs() << ' '; 12453 } 12454 dbgs() << '\n'; 12455 }); 12456 12457 assert(!Clusters.empty()); 12458 SwitchWorkList WorkList; 12459 CaseClusterIt First = Clusters.begin(); 12460 CaseClusterIt Last = Clusters.end() - 1; 12461 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 12462 // Scale the branchprobability for DefaultMBB if the peel occurs and 12463 // DefaultMBB is not replaced. 12464 if (PeeledCaseProb != BranchProbability::getZero() && 12465 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest())) 12466 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 12467 WorkList.push_back( 12468 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 12469 12470 while (!WorkList.empty()) { 12471 SwitchWorkListItem W = WorkList.pop_back_val(); 12472 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 12473 12474 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 12475 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 12476 // For optimized builds, lower large range as a balanced binary tree. 12477 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 12478 continue; 12479 } 12480 12481 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 12482 } 12483 } 12484 12485 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 12486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12487 auto DL = getCurSDLoc(); 12488 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12489 setValue(&I, DAG.getStepVector(DL, ResultVT)); 12490 } 12491 12492 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 12493 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12494 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12495 12496 SDLoc DL = getCurSDLoc(); 12497 SDValue V = getValue(I.getOperand(0)); 12498 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 12499 12500 if (VT.isScalableVector()) { 12501 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 12502 return; 12503 } 12504 12505 // Use VECTOR_SHUFFLE for the fixed-length vector 12506 // to maintain existing behavior. 12507 SmallVector<int, 8> Mask; 12508 unsigned NumElts = VT.getVectorMinNumElements(); 12509 for (unsigned i = 0; i != NumElts; ++i) 12510 Mask.push_back(NumElts - 1 - i); 12511 12512 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 12513 } 12514 12515 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 12516 auto DL = getCurSDLoc(); 12517 SDValue InVec = getValue(I.getOperand(0)); 12518 EVT OutVT = 12519 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 12520 12521 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 12522 12523 // ISD Node needs the input vectors split into two equal parts 12524 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12525 DAG.getVectorIdxConstant(0, DL)); 12526 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12527 DAG.getVectorIdxConstant(OutNumElts, DL)); 12528 12529 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12530 // legalisation and combines. 12531 if (OutVT.isFixedLengthVector()) { 12532 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12533 createStrideMask(0, 2, OutNumElts)); 12534 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12535 createStrideMask(1, 2, OutNumElts)); 12536 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 12537 setValue(&I, Res); 12538 return; 12539 } 12540 12541 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12542 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12543 setValue(&I, Res); 12544 } 12545 12546 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12547 auto DL = getCurSDLoc(); 12548 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12549 SDValue InVec0 = getValue(I.getOperand(0)); 12550 SDValue InVec1 = getValue(I.getOperand(1)); 12551 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12552 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12553 12554 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12555 // legalisation and combines. 12556 if (OutVT.isFixedLengthVector()) { 12557 unsigned NumElts = InVT.getVectorMinNumElements(); 12558 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12559 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12560 createInterleaveMask(NumElts, 2))); 12561 return; 12562 } 12563 12564 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12565 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12566 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12567 Res.getValue(1)); 12568 setValue(&I, Res); 12569 } 12570 12571 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12572 SmallVector<EVT, 4> ValueVTs; 12573 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12574 ValueVTs); 12575 unsigned NumValues = ValueVTs.size(); 12576 if (NumValues == 0) return; 12577 12578 SmallVector<SDValue, 4> Values(NumValues); 12579 SDValue Op = getValue(I.getOperand(0)); 12580 12581 for (unsigned i = 0; i != NumValues; ++i) 12582 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12583 SDValue(Op.getNode(), Op.getResNo() + i)); 12584 12585 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12586 DAG.getVTList(ValueVTs), Values)); 12587 } 12588 12589 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12590 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12591 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12592 12593 SDLoc DL = getCurSDLoc(); 12594 SDValue V1 = getValue(I.getOperand(0)); 12595 SDValue V2 = getValue(I.getOperand(1)); 12596 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12597 12598 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12599 if (VT.isScalableVector()) { 12600 setValue( 12601 &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12602 DAG.getSignedConstant( 12603 Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout())))); 12604 return; 12605 } 12606 12607 unsigned NumElts = VT.getVectorNumElements(); 12608 12609 uint64_t Idx = (NumElts + Imm) % NumElts; 12610 12611 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12612 SmallVector<int, 8> Mask; 12613 for (unsigned i = 0; i < NumElts; ++i) 12614 Mask.push_back(Idx + i); 12615 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12616 } 12617 12618 // Consider the following MIR after SelectionDAG, which produces output in 12619 // phyregs in the first case or virtregs in the second case. 12620 // 12621 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12622 // %5:gr32 = COPY $ebx 12623 // %6:gr32 = COPY $edx 12624 // %1:gr32 = COPY %6:gr32 12625 // %0:gr32 = COPY %5:gr32 12626 // 12627 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12628 // %1:gr32 = COPY %6:gr32 12629 // %0:gr32 = COPY %5:gr32 12630 // 12631 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12632 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12633 // 12634 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12635 // to a single virtreg (such as %0). The remaining outputs monotonically 12636 // increase in virtreg number from there. If a callbr has no outputs, then it 12637 // should not have a corresponding callbr landingpad; in fact, the callbr 12638 // landingpad would not even be able to refer to such a callbr. 12639 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12640 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12641 // There is definitely at least one copy. 12642 assert(MI->getOpcode() == TargetOpcode::COPY && 12643 "start of copy chain MUST be COPY"); 12644 Reg = MI->getOperand(1).getReg(); 12645 MI = MRI.def_begin(Reg)->getParent(); 12646 // There may be an optional second copy. 12647 if (MI->getOpcode() == TargetOpcode::COPY) { 12648 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12649 Reg = MI->getOperand(1).getReg(); 12650 assert(Reg.isPhysical() && "expected COPY of physical register"); 12651 MI = MRI.def_begin(Reg)->getParent(); 12652 } 12653 // The start of the chain must be an INLINEASM_BR. 12654 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12655 "end of copy chain MUST be INLINEASM_BR"); 12656 return Reg; 12657 } 12658 12659 // We must do this walk rather than the simpler 12660 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12661 // otherwise we will end up with copies of virtregs only valid along direct 12662 // edges. 12663 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12664 SmallVector<EVT, 8> ResultVTs; 12665 SmallVector<SDValue, 8> ResultValues; 12666 const auto *CBR = 12667 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12668 12669 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12670 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12671 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12672 12673 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12674 SDValue Chain = DAG.getRoot(); 12675 12676 // Re-parse the asm constraints string. 12677 TargetLowering::AsmOperandInfoVector TargetConstraints = 12678 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12679 for (auto &T : TargetConstraints) { 12680 SDISelAsmOperandInfo OpInfo(T); 12681 if (OpInfo.Type != InlineAsm::isOutput) 12682 continue; 12683 12684 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12685 // individual constraint. 12686 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12687 12688 switch (OpInfo.ConstraintType) { 12689 case TargetLowering::C_Register: 12690 case TargetLowering::C_RegisterClass: { 12691 // Fill in OpInfo.AssignedRegs.Regs. 12692 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12693 12694 // getRegistersForValue may produce 1 to many registers based on whether 12695 // the OpInfo.ConstraintVT is legal on the target or not. 12696 for (Register &Reg : OpInfo.AssignedRegs.Regs) { 12697 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12698 if (Register::isPhysicalRegister(OriginalDef)) 12699 FuncInfo.MBB->addLiveIn(OriginalDef); 12700 // Update the assigned registers to use the original defs. 12701 Reg = OriginalDef; 12702 } 12703 12704 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12705 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12706 ResultValues.push_back(V); 12707 ResultVTs.push_back(OpInfo.ConstraintVT); 12708 break; 12709 } 12710 case TargetLowering::C_Other: { 12711 SDValue Flag; 12712 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12713 OpInfo, DAG); 12714 ++InitialDef; 12715 ResultValues.push_back(V); 12716 ResultVTs.push_back(OpInfo.ConstraintVT); 12717 break; 12718 } 12719 default: 12720 break; 12721 } 12722 } 12723 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12724 DAG.getVTList(ResultVTs), ResultValues); 12725 setValue(&I, V); 12726 } 12727