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 } 1227 1228 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1229 // Add SDDbgValue nodes for any var locs here. Do so before updating 1230 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1231 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1232 // Add SDDbgValue nodes for any var locs here. Do so before updating 1233 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1234 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1235 It != End; ++It) { 1236 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1237 dropDanglingDebugInfo(Var, It->Expr); 1238 if (It->Values.isKillLocation(It->Expr)) { 1239 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1240 continue; 1241 } 1242 SmallVector<Value *> Values(It->Values.location_ops()); 1243 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1244 It->Values.hasArgList())) { 1245 SmallVector<Value *, 4> Vals(It->Values.location_ops()); 1246 addDanglingDebugInfo(Vals, 1247 FnVarLocs->getDILocalVariable(It->VariableID), 1248 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1249 } 1250 } 1251 } 1252 1253 // We must skip DbgVariableRecords if they've already been processed above as 1254 // we have just emitted the debug values resulting from assignment tracking 1255 // analysis, making any existing DbgVariableRecords redundant (and probably 1256 // less correct). We still need to process DbgLabelRecords. This does sink 1257 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't 1258 // be important as it does so deterministcally and ordering between 1259 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR 1260 // printing). 1261 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs(); 1262 // Is there is any debug-info attached to this instruction, in the form of 1263 // DbgRecord non-instruction debug-info records. 1264 for (DbgRecord &DR : I.getDbgRecordRange()) { 1265 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 1266 assert(DLR->getLabel() && "Missing label"); 1267 SDDbgLabel *SDV = 1268 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder); 1269 DAG.AddDbgLabel(SDV); 1270 continue; 1271 } 1272 1273 if (SkipDbgVariableRecords) 1274 continue; 1275 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 1276 DILocalVariable *Variable = DVR.getVariable(); 1277 DIExpression *Expression = DVR.getExpression(); 1278 dropDanglingDebugInfo(Variable, Expression); 1279 1280 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) { 1281 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR)) 1282 continue; 1283 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR 1284 << "\n"); 1285 handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression, 1286 DVR.getDebugLoc()); 1287 continue; 1288 } 1289 1290 // A DbgVariableRecord with no locations is a kill location. 1291 SmallVector<Value *, 4> Values(DVR.location_ops()); 1292 if (Values.empty()) { 1293 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1294 SDNodeOrder); 1295 continue; 1296 } 1297 1298 // A DbgVariableRecord with an undef or absent location is also a kill 1299 // location. 1300 if (llvm::any_of(Values, 1301 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1302 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1303 SDNodeOrder); 1304 continue; 1305 } 1306 1307 bool IsVariadic = DVR.hasArgList(); 1308 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(), 1309 SDNodeOrder, IsVariadic)) { 1310 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1311 DVR.getDebugLoc(), SDNodeOrder); 1312 } 1313 } 1314 } 1315 1316 void SelectionDAGBuilder::visit(const Instruction &I) { 1317 visitDbgInfo(I); 1318 1319 // Set up outgoing PHI node register values before emitting the terminator. 1320 if (I.isTerminator()) { 1321 HandlePHINodesInSuccessorBlocks(I.getParent()); 1322 } 1323 1324 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1325 if (!isa<DbgInfoIntrinsic>(I)) 1326 ++SDNodeOrder; 1327 1328 CurInst = &I; 1329 1330 // Set inserted listener only if required. 1331 bool NodeInserted = false; 1332 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1333 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1334 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra); 1335 if (PCSectionsMD || MMRA) { 1336 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1337 DAG, [&](SDNode *) { NodeInserted = true; }); 1338 } 1339 1340 visit(I.getOpcode(), I); 1341 1342 if (!I.isTerminator() && !HasTailCall && 1343 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1344 CopyToExportRegsIfNeeded(&I); 1345 1346 // Handle metadata. 1347 if (PCSectionsMD || MMRA) { 1348 auto It = NodeMap.find(&I); 1349 if (It != NodeMap.end()) { 1350 if (PCSectionsMD) 1351 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1352 if (MMRA) 1353 DAG.addMMRAMetadata(It->second.getNode(), MMRA); 1354 } else if (NodeInserted) { 1355 // This should not happen; if it does, don't let it go unnoticed so we can 1356 // fix it. Relevant visit*() function is probably missing a setValue(). 1357 errs() << "warning: loosing !pcsections and/or !mmra metadata [" 1358 << I.getModule()->getName() << "]\n"; 1359 LLVM_DEBUG(I.dump()); 1360 assert(false); 1361 } 1362 } 1363 1364 CurInst = nullptr; 1365 } 1366 1367 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1368 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1369 } 1370 1371 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1372 // Note: this doesn't use InstVisitor, because it has to work with 1373 // ConstantExpr's in addition to instructions. 1374 switch (Opcode) { 1375 default: llvm_unreachable("Unknown instruction type encountered!"); 1376 // Build the switch statement using the Instruction.def file. 1377 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1378 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1379 #include "llvm/IR/Instruction.def" 1380 } 1381 } 1382 1383 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1384 DILocalVariable *Variable, 1385 DebugLoc DL, unsigned Order, 1386 SmallVectorImpl<Value *> &Values, 1387 DIExpression *Expression) { 1388 // For variadic dbg_values we will now insert an undef. 1389 // FIXME: We can potentially recover these! 1390 SmallVector<SDDbgOperand, 2> Locs; 1391 for (const Value *V : Values) { 1392 auto *Undef = UndefValue::get(V->getType()); 1393 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1394 } 1395 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1396 /*IsIndirect=*/false, DL, Order, 1397 /*IsVariadic=*/true); 1398 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1399 return true; 1400 } 1401 1402 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1403 DILocalVariable *Var, 1404 DIExpression *Expr, 1405 bool IsVariadic, DebugLoc DL, 1406 unsigned Order) { 1407 if (IsVariadic) { 1408 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1409 return; 1410 } 1411 // TODO: Dangling debug info will eventually either be resolved or produce 1412 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1413 // between the original dbg.value location and its resolved DBG_VALUE, 1414 // which we should ideally fill with an extra Undef DBG_VALUE. 1415 assert(Values.size() == 1); 1416 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1417 } 1418 1419 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1420 const DIExpression *Expr) { 1421 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1422 DIVariable *DanglingVariable = DDI.getVariable(); 1423 DIExpression *DanglingExpr = DDI.getExpression(); 1424 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1425 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1426 << printDDI(nullptr, DDI) << "\n"); 1427 return true; 1428 } 1429 return false; 1430 }; 1431 1432 for (auto &DDIMI : DanglingDebugInfoMap) { 1433 DanglingDebugInfoVector &DDIV = DDIMI.second; 1434 1435 // If debug info is to be dropped, run it through final checks to see 1436 // whether it can be salvaged. 1437 for (auto &DDI : DDIV) 1438 if (isMatchingDbgValue(DDI)) 1439 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1440 1441 erase_if(DDIV, isMatchingDbgValue); 1442 } 1443 } 1444 1445 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1446 // generate the debug data structures now that we've seen its definition. 1447 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1448 SDValue Val) { 1449 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1450 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1451 return; 1452 1453 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1454 for (auto &DDI : DDIV) { 1455 DebugLoc DL = DDI.getDebugLoc(); 1456 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1457 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1458 DILocalVariable *Variable = DDI.getVariable(); 1459 DIExpression *Expr = DDI.getExpression(); 1460 assert(Variable->isValidLocationForIntrinsic(DL) && 1461 "Expected inlined-at fields to agree"); 1462 SDDbgValue *SDV; 1463 if (Val.getNode()) { 1464 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1465 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1466 // we couldn't resolve it directly when examining the DbgValue intrinsic 1467 // in the first place we should not be more successful here). Unless we 1468 // have some test case that prove this to be correct we should avoid 1469 // calling EmitFuncArgumentDbgValue here. 1470 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1471 FuncArgumentDbgValueKind::Value, Val)) { 1472 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1473 << printDDI(V, DDI) << "\n"); 1474 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1475 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1476 // inserted after the definition of Val when emitting the instructions 1477 // after ISel. An alternative could be to teach 1478 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1479 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1480 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1481 << ValSDNodeOrder << "\n"); 1482 SDV = getDbgValue(Val, Variable, Expr, DL, 1483 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1484 DAG.AddDbgValue(SDV, false); 1485 } else 1486 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1487 << printDDI(V, DDI) 1488 << " in EmitFuncArgumentDbgValue\n"); 1489 } else { 1490 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1491 << "\n"); 1492 auto Undef = UndefValue::get(V->getType()); 1493 auto SDV = 1494 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1495 DAG.AddDbgValue(SDV, false); 1496 } 1497 } 1498 DDIV.clear(); 1499 } 1500 1501 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1502 DanglingDebugInfo &DDI) { 1503 // TODO: For the variadic implementation, instead of only checking the fail 1504 // state of `handleDebugValue`, we need know specifically which values were 1505 // invalid, so that we attempt to salvage only those values when processing 1506 // a DIArgList. 1507 const Value *OrigV = V; 1508 DILocalVariable *Var = DDI.getVariable(); 1509 DIExpression *Expr = DDI.getExpression(); 1510 DebugLoc DL = DDI.getDebugLoc(); 1511 unsigned SDOrder = DDI.getSDNodeOrder(); 1512 1513 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1514 // that DW_OP_stack_value is desired. 1515 bool StackValue = true; 1516 1517 // Can this Value can be encoded without any further work? 1518 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1519 return; 1520 1521 // Attempt to salvage back through as many instructions as possible. Bail if 1522 // a non-instruction is seen, such as a constant expression or global 1523 // variable. FIXME: Further work could recover those too. 1524 while (isa<Instruction>(V)) { 1525 const Instruction &VAsInst = *cast<const Instruction>(V); 1526 // Temporary "0", awaiting real implementation. 1527 SmallVector<uint64_t, 16> Ops; 1528 SmallVector<Value *, 4> AdditionalValues; 1529 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1530 Expr->getNumLocationOperands(), Ops, 1531 AdditionalValues); 1532 // If we cannot salvage any further, and haven't yet found a suitable debug 1533 // expression, bail out. 1534 if (!V) 1535 break; 1536 1537 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1538 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1539 // here for variadic dbg_values, remove that condition. 1540 if (!AdditionalValues.empty()) 1541 break; 1542 1543 // New value and expr now represent this debuginfo. 1544 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1545 1546 // Some kind of simplification occurred: check whether the operand of the 1547 // salvaged debug expression can be encoded in this DAG. 1548 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1549 LLVM_DEBUG( 1550 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1551 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1552 return; 1553 } 1554 } 1555 1556 // This was the final opportunity to salvage this debug information, and it 1557 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1558 // any earlier variable location. 1559 assert(OrigV && "V shouldn't be null"); 1560 auto *Undef = UndefValue::get(OrigV->getType()); 1561 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1562 DAG.AddDbgValue(SDV, false); 1563 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1564 << printDDI(OrigV, DDI) << "\n"); 1565 } 1566 1567 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1568 DIExpression *Expr, 1569 DebugLoc DbgLoc, 1570 unsigned Order) { 1571 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1572 DIExpression *NewExpr = 1573 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1574 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1575 /*IsVariadic*/ false); 1576 } 1577 1578 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1579 DILocalVariable *Var, 1580 DIExpression *Expr, DebugLoc DbgLoc, 1581 unsigned Order, bool IsVariadic) { 1582 if (Values.empty()) 1583 return true; 1584 1585 // Filter EntryValue locations out early. 1586 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1587 return true; 1588 1589 SmallVector<SDDbgOperand> LocationOps; 1590 SmallVector<SDNode *> Dependencies; 1591 for (const Value *V : Values) { 1592 // Constant value. 1593 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1594 isa<ConstantPointerNull>(V)) { 1595 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1596 continue; 1597 } 1598 1599 // Look through IntToPtr constants. 1600 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1601 if (CE->getOpcode() == Instruction::IntToPtr) { 1602 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1603 continue; 1604 } 1605 1606 // If the Value is a frame index, we can create a FrameIndex debug value 1607 // without relying on the DAG at all. 1608 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1609 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1610 if (SI != FuncInfo.StaticAllocaMap.end()) { 1611 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1612 continue; 1613 } 1614 } 1615 1616 // Do not use getValue() in here; we don't want to generate code at 1617 // this point if it hasn't been done yet. 1618 SDValue N = NodeMap[V]; 1619 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1620 N = UnusedArgNodeMap[V]; 1621 1622 if (N.getNode()) { 1623 // Only emit func arg dbg value for non-variadic dbg.values for now. 1624 if (!IsVariadic && 1625 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1626 FuncArgumentDbgValueKind::Value, N)) 1627 return true; 1628 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1629 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1630 // describe stack slot locations. 1631 // 1632 // Consider "int x = 0; int *px = &x;". There are two kinds of 1633 // interesting debug values here after optimization: 1634 // 1635 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1636 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1637 // 1638 // Both describe the direct values of their associated variables. 1639 Dependencies.push_back(N.getNode()); 1640 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1641 continue; 1642 } 1643 LocationOps.emplace_back( 1644 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1645 continue; 1646 } 1647 1648 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1649 // Special rules apply for the first dbg.values of parameter variables in a 1650 // function. Identify them by the fact they reference Argument Values, that 1651 // they're parameters, and they are parameters of the current function. We 1652 // need to let them dangle until they get an SDNode. 1653 bool IsParamOfFunc = 1654 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1655 if (IsParamOfFunc) 1656 return false; 1657 1658 // The value is not used in this block yet (or it would have an SDNode). 1659 // We still want the value to appear for the user if possible -- if it has 1660 // an associated VReg, we can refer to that instead. 1661 auto VMI = FuncInfo.ValueMap.find(V); 1662 if (VMI != FuncInfo.ValueMap.end()) { 1663 unsigned Reg = VMI->second; 1664 // If this is a PHI node, it may be split up into several MI PHI nodes 1665 // (in FunctionLoweringInfo::set). 1666 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1667 V->getType(), std::nullopt); 1668 if (RFV.occupiesMultipleRegs()) { 1669 // FIXME: We could potentially support variadic dbg_values here. 1670 if (IsVariadic) 1671 return false; 1672 unsigned Offset = 0; 1673 unsigned BitsToDescribe = 0; 1674 if (auto VarSize = Var->getSizeInBits()) 1675 BitsToDescribe = *VarSize; 1676 if (auto Fragment = Expr->getFragmentInfo()) 1677 BitsToDescribe = Fragment->SizeInBits; 1678 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1679 // Bail out if all bits are described already. 1680 if (Offset >= BitsToDescribe) 1681 break; 1682 // TODO: handle scalable vectors. 1683 unsigned RegisterSize = RegAndSize.second; 1684 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1685 ? BitsToDescribe - Offset 1686 : RegisterSize; 1687 auto FragmentExpr = DIExpression::createFragmentExpression( 1688 Expr, Offset, FragmentSize); 1689 if (!FragmentExpr) 1690 continue; 1691 SDDbgValue *SDV = DAG.getVRegDbgValue( 1692 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order); 1693 DAG.AddDbgValue(SDV, false); 1694 Offset += RegisterSize; 1695 } 1696 return true; 1697 } 1698 // We can use simple vreg locations for variadic dbg_values as well. 1699 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1700 continue; 1701 } 1702 // We failed to create a SDDbgOperand for V. 1703 return false; 1704 } 1705 1706 // We have created a SDDbgOperand for each Value in Values. 1707 assert(!LocationOps.empty()); 1708 SDDbgValue *SDV = 1709 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1710 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic); 1711 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1712 return true; 1713 } 1714 1715 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1716 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1717 for (auto &Pair : DanglingDebugInfoMap) 1718 for (auto &DDI : Pair.second) 1719 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1720 clearDanglingDebugInfo(); 1721 } 1722 1723 /// getCopyFromRegs - If there was virtual register allocated for the value V 1724 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1725 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1726 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1727 SDValue Result; 1728 1729 if (It != FuncInfo.ValueMap.end()) { 1730 Register InReg = It->second; 1731 1732 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1733 DAG.getDataLayout(), InReg, Ty, 1734 std::nullopt); // This is not an ABI copy. 1735 SDValue Chain = DAG.getEntryNode(); 1736 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1737 V); 1738 resolveDanglingDebugInfo(V, Result); 1739 } 1740 1741 return Result; 1742 } 1743 1744 /// getValue - Return an SDValue for the given Value. 1745 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1746 // If we already have an SDValue for this value, use it. It's important 1747 // to do this first, so that we don't create a CopyFromReg if we already 1748 // have a regular SDValue. 1749 SDValue &N = NodeMap[V]; 1750 if (N.getNode()) return N; 1751 1752 // If there's a virtual register allocated and initialized for this 1753 // value, use it. 1754 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1755 return copyFromReg; 1756 1757 // Otherwise create a new SDValue and remember it. 1758 SDValue Val = getValueImpl(V); 1759 NodeMap[V] = Val; 1760 resolveDanglingDebugInfo(V, Val); 1761 return Val; 1762 } 1763 1764 /// getNonRegisterValue - Return an SDValue for the given Value, but 1765 /// don't look in FuncInfo.ValueMap for a virtual register. 1766 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1767 // If we already have an SDValue for this value, use it. 1768 SDValue &N = NodeMap[V]; 1769 if (N.getNode()) { 1770 if (isIntOrFPConstant(N)) { 1771 // Remove the debug location from the node as the node is about to be used 1772 // in a location which may differ from the original debug location. This 1773 // is relevant to Constant and ConstantFP nodes because they can appear 1774 // as constant expressions inside PHI nodes. 1775 N->setDebugLoc(DebugLoc()); 1776 } 1777 return N; 1778 } 1779 1780 // Otherwise create a new SDValue and remember it. 1781 SDValue Val = getValueImpl(V); 1782 NodeMap[V] = Val; 1783 resolveDanglingDebugInfo(V, Val); 1784 return Val; 1785 } 1786 1787 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1788 /// Create an SDValue for the given value. 1789 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1790 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1791 1792 if (const Constant *C = dyn_cast<Constant>(V)) { 1793 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1794 1795 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1796 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1797 1798 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1799 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1800 1801 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) { 1802 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT, 1803 getValue(CPA->getPointer()), getValue(CPA->getKey()), 1804 getValue(CPA->getAddrDiscriminator()), 1805 getValue(CPA->getDiscriminator())); 1806 } 1807 1808 if (isa<ConstantPointerNull>(C)) { 1809 unsigned AS = V->getType()->getPointerAddressSpace(); 1810 return DAG.getConstant(0, getCurSDLoc(), 1811 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1812 } 1813 1814 if (match(C, m_VScale())) 1815 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1816 1817 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1818 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1819 1820 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1821 return DAG.getUNDEF(VT); 1822 1823 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1824 visit(CE->getOpcode(), *CE); 1825 SDValue N1 = NodeMap[V]; 1826 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1827 return N1; 1828 } 1829 1830 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1831 SmallVector<SDValue, 4> Constants; 1832 for (const Use &U : C->operands()) { 1833 SDNode *Val = getValue(U).getNode(); 1834 // If the operand is an empty aggregate, there are no values. 1835 if (!Val) continue; 1836 // Add each leaf value from the operand to the Constants list 1837 // to form a flattened list of all the values. 1838 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1839 Constants.push_back(SDValue(Val, i)); 1840 } 1841 1842 return DAG.getMergeValues(Constants, getCurSDLoc()); 1843 } 1844 1845 if (const ConstantDataSequential *CDS = 1846 dyn_cast<ConstantDataSequential>(C)) { 1847 SmallVector<SDValue, 4> Ops; 1848 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1849 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1850 // Add each leaf value from the operand to the Constants list 1851 // to form a flattened list of all the values. 1852 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1853 Ops.push_back(SDValue(Val, i)); 1854 } 1855 1856 if (isa<ArrayType>(CDS->getType())) 1857 return DAG.getMergeValues(Ops, getCurSDLoc()); 1858 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1859 } 1860 1861 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1862 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1863 "Unknown struct or array constant!"); 1864 1865 SmallVector<EVT, 4> ValueVTs; 1866 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1867 unsigned NumElts = ValueVTs.size(); 1868 if (NumElts == 0) 1869 return SDValue(); // empty struct 1870 SmallVector<SDValue, 4> Constants(NumElts); 1871 for (unsigned i = 0; i != NumElts; ++i) { 1872 EVT EltVT = ValueVTs[i]; 1873 if (isa<UndefValue>(C)) 1874 Constants[i] = DAG.getUNDEF(EltVT); 1875 else if (EltVT.isFloatingPoint()) 1876 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1877 else 1878 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1879 } 1880 1881 return DAG.getMergeValues(Constants, getCurSDLoc()); 1882 } 1883 1884 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1885 return DAG.getBlockAddress(BA, VT); 1886 1887 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1888 return getValue(Equiv->getGlobalValue()); 1889 1890 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1891 return getValue(NC->getGlobalValue()); 1892 1893 if (VT == MVT::aarch64svcount) { 1894 assert(C->isNullValue() && "Can only zero this target type!"); 1895 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1896 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1897 } 1898 1899 VectorType *VecTy = cast<VectorType>(V->getType()); 1900 1901 // Now that we know the number and type of the elements, get that number of 1902 // elements into the Ops array based on what kind of constant it is. 1903 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1904 SmallVector<SDValue, 16> Ops; 1905 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1906 for (unsigned i = 0; i != NumElements; ++i) 1907 Ops.push_back(getValue(CV->getOperand(i))); 1908 1909 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1910 } 1911 1912 if (isa<ConstantAggregateZero>(C)) { 1913 EVT EltVT = 1914 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1915 1916 SDValue Op; 1917 if (EltVT.isFloatingPoint()) 1918 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1919 else 1920 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1921 1922 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1923 } 1924 1925 llvm_unreachable("Unknown vector constant"); 1926 } 1927 1928 // If this is a static alloca, generate it as the frameindex instead of 1929 // computation. 1930 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1931 DenseMap<const AllocaInst*, int>::iterator SI = 1932 FuncInfo.StaticAllocaMap.find(AI); 1933 if (SI != FuncInfo.StaticAllocaMap.end()) 1934 return DAG.getFrameIndex( 1935 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1936 } 1937 1938 // If this is an instruction which fast-isel has deferred, select it now. 1939 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1940 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1941 1942 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1943 Inst->getType(), std::nullopt); 1944 SDValue Chain = DAG.getEntryNode(); 1945 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1946 } 1947 1948 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1949 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1950 1951 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1952 return DAG.getBasicBlock(FuncInfo.getMBB(BB)); 1953 1954 llvm_unreachable("Can't get register for value!"); 1955 } 1956 1957 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1958 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1959 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1960 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1961 bool IsSEH = isAsynchronousEHPersonality(Pers); 1962 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1963 if (!IsSEH) 1964 CatchPadMBB->setIsEHScopeEntry(); 1965 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1966 if (IsMSVCCXX || IsCoreCLR) 1967 CatchPadMBB->setIsEHFuncletEntry(); 1968 } 1969 1970 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1971 // Update machine-CFG edge. 1972 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor()); 1973 FuncInfo.MBB->addSuccessor(TargetMBB); 1974 TargetMBB->setIsEHCatchretTarget(true); 1975 DAG.getMachineFunction().setHasEHCatchret(true); 1976 1977 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1978 bool IsSEH = isAsynchronousEHPersonality(Pers); 1979 if (IsSEH) { 1980 // If this is not a fall-through branch or optimizations are switched off, 1981 // emit the branch. 1982 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1983 TM.getOptLevel() == CodeGenOptLevel::None) 1984 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1985 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1986 return; 1987 } 1988 1989 // Figure out the funclet membership for the catchret's successor. 1990 // This will be used by the FuncletLayout pass to determine how to order the 1991 // BB's. 1992 // A 'catchret' returns to the outer scope's color. 1993 Value *ParentPad = I.getCatchSwitchParentPad(); 1994 const BasicBlock *SuccessorColor; 1995 if (isa<ConstantTokenNone>(ParentPad)) 1996 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1997 else 1998 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1999 assert(SuccessorColor && "No parent funclet for catchret!"); 2000 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor); 2001 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 2002 2003 // Create the terminator node. 2004 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 2005 getControlRoot(), DAG.getBasicBlock(TargetMBB), 2006 DAG.getBasicBlock(SuccessorColorMBB)); 2007 DAG.setRoot(Ret); 2008 } 2009 2010 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 2011 // Don't emit any special code for the cleanuppad instruction. It just marks 2012 // the start of an EH scope/funclet. 2013 FuncInfo.MBB->setIsEHScopeEntry(); 2014 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2015 if (Pers != EHPersonality::Wasm_CXX) { 2016 FuncInfo.MBB->setIsEHFuncletEntry(); 2017 FuncInfo.MBB->setIsCleanupFuncletEntry(); 2018 } 2019 } 2020 2021 // In wasm EH, even though a catchpad may not catch an exception if a tag does 2022 // not match, it is OK to add only the first unwind destination catchpad to the 2023 // successors, because there will be at least one invoke instruction within the 2024 // catch scope that points to the next unwind destination, if one exists, so 2025 // CFGSort cannot mess up with BB sorting order. 2026 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 2027 // call within them, and catchpads only consisting of 'catch (...)' have a 2028 // '__cxa_end_catch' call within them, both of which generate invokes in case 2029 // the next unwind destination exists, i.e., the next unwind destination is not 2030 // the caller.) 2031 // 2032 // Having at most one EH pad successor is also simpler and helps later 2033 // transformations. 2034 // 2035 // For example, 2036 // current: 2037 // invoke void @foo to ... unwind label %catch.dispatch 2038 // catch.dispatch: 2039 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2040 // catch.start: 2041 // ... 2042 // ... in this BB or some other child BB dominated by this BB there will be an 2043 // invoke that points to 'next' BB as an unwind destination 2044 // 2045 // next: ; We don't need to add this to 'current' BB's successor 2046 // ... 2047 static void findWasmUnwindDestinations( 2048 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2049 BranchProbability Prob, 2050 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2051 &UnwindDests) { 2052 while (EHPadBB) { 2053 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2054 if (isa<CleanupPadInst>(Pad)) { 2055 // Stop on cleanup pads. 2056 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2057 UnwindDests.back().first->setIsEHScopeEntry(); 2058 break; 2059 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2060 // Add the catchpad handlers to the possible destinations. We don't 2061 // continue to the unwind destination of the catchswitch for wasm. 2062 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2063 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob); 2064 UnwindDests.back().first->setIsEHScopeEntry(); 2065 } 2066 break; 2067 } else { 2068 continue; 2069 } 2070 } 2071 } 2072 2073 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2074 /// many places it could ultimately go. In the IR, we have a single unwind 2075 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2076 /// This function skips over imaginary basic blocks that hold catchswitch 2077 /// instructions, and finds all the "real" machine 2078 /// basic block destinations. As those destinations may not be successors of 2079 /// EHPadBB, here we also calculate the edge probability to those destinations. 2080 /// The passed-in Prob is the edge probability to EHPadBB. 2081 static void findUnwindDestinations( 2082 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2083 BranchProbability Prob, 2084 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2085 &UnwindDests) { 2086 EHPersonality Personality = 2087 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2088 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2089 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2090 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2091 bool IsSEH = isAsynchronousEHPersonality(Personality); 2092 2093 if (IsWasmCXX) { 2094 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2095 assert(UnwindDests.size() <= 1 && 2096 "There should be at most one unwind destination for wasm"); 2097 return; 2098 } 2099 2100 while (EHPadBB) { 2101 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2102 BasicBlock *NewEHPadBB = nullptr; 2103 if (isa<LandingPadInst>(Pad)) { 2104 // Stop on landingpads. They are not funclets. 2105 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2106 break; 2107 } else if (isa<CleanupPadInst>(Pad)) { 2108 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2109 // personalities. 2110 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2111 UnwindDests.back().first->setIsEHScopeEntry(); 2112 UnwindDests.back().first->setIsEHFuncletEntry(); 2113 break; 2114 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2115 // Add the catchpad handlers to the possible destinations. 2116 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2117 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob); 2118 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2119 if (IsMSVCCXX || IsCoreCLR) 2120 UnwindDests.back().first->setIsEHFuncletEntry(); 2121 if (!IsSEH) 2122 UnwindDests.back().first->setIsEHScopeEntry(); 2123 } 2124 NewEHPadBB = CatchSwitch->getUnwindDest(); 2125 } else { 2126 continue; 2127 } 2128 2129 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2130 if (BPI && NewEHPadBB) 2131 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2132 EHPadBB = NewEHPadBB; 2133 } 2134 } 2135 2136 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2137 // Update successor info. 2138 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2139 auto UnwindDest = I.getUnwindDest(); 2140 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2141 BranchProbability UnwindDestProb = 2142 (BPI && UnwindDest) 2143 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2144 : BranchProbability::getZero(); 2145 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2146 for (auto &UnwindDest : UnwindDests) { 2147 UnwindDest.first->setIsEHPad(); 2148 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2149 } 2150 FuncInfo.MBB->normalizeSuccProbs(); 2151 2152 // Create the terminator node. 2153 MachineBasicBlock *CleanupPadMBB = 2154 FuncInfo.getMBB(I.getCleanupPad()->getParent()); 2155 SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, 2156 getControlRoot(), DAG.getBasicBlock(CleanupPadMBB)); 2157 DAG.setRoot(Ret); 2158 } 2159 2160 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2161 report_fatal_error("visitCatchSwitch not yet implemented!"); 2162 } 2163 2164 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2165 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2166 auto &DL = DAG.getDataLayout(); 2167 SDValue Chain = getControlRoot(); 2168 SmallVector<ISD::OutputArg, 8> Outs; 2169 SmallVector<SDValue, 8> OutVals; 2170 2171 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2172 // lower 2173 // 2174 // %val = call <ty> @llvm.experimental.deoptimize() 2175 // ret <ty> %val 2176 // 2177 // differently. 2178 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2179 LowerDeoptimizingReturn(); 2180 return; 2181 } 2182 2183 if (!FuncInfo.CanLowerReturn) { 2184 Register DemoteReg = FuncInfo.DemoteRegister; 2185 const Function *F = I.getParent()->getParent(); 2186 2187 // Emit a store of the return value through the virtual register. 2188 // Leave Outs empty so that LowerReturn won't try to load return 2189 // registers the usual way. 2190 SmallVector<EVT, 1> PtrValueVTs; 2191 ComputeValueVTs(TLI, DL, 2192 PointerType::get(F->getContext(), 2193 DAG.getDataLayout().getAllocaAddrSpace()), 2194 PtrValueVTs); 2195 2196 SDValue RetPtr = 2197 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2198 SDValue RetOp = getValue(I.getOperand(0)); 2199 2200 SmallVector<EVT, 4> ValueVTs, MemVTs; 2201 SmallVector<uint64_t, 4> Offsets; 2202 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2203 &Offsets, 0); 2204 unsigned NumValues = ValueVTs.size(); 2205 2206 SmallVector<SDValue, 4> Chains(NumValues); 2207 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2208 for (unsigned i = 0; i != NumValues; ++i) { 2209 // An aggregate return value cannot wrap around the address space, so 2210 // offsets to its parts don't wrap either. 2211 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2212 TypeSize::getFixed(Offsets[i])); 2213 2214 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2215 if (MemVTs[i] != ValueVTs[i]) 2216 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2217 Chains[i] = DAG.getStore( 2218 Chain, getCurSDLoc(), Val, 2219 // FIXME: better loc info would be nice. 2220 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2221 commonAlignment(BaseAlign, Offsets[i])); 2222 } 2223 2224 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2225 MVT::Other, Chains); 2226 } else if (I.getNumOperands() != 0) { 2227 SmallVector<EVT, 4> ValueVTs; 2228 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2229 unsigned NumValues = ValueVTs.size(); 2230 if (NumValues) { 2231 SDValue RetOp = getValue(I.getOperand(0)); 2232 2233 const Function *F = I.getParent()->getParent(); 2234 2235 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2236 I.getOperand(0)->getType(), F->getCallingConv(), 2237 /*IsVarArg*/ false, DL); 2238 2239 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2240 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2241 ExtendKind = ISD::SIGN_EXTEND; 2242 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2243 ExtendKind = ISD::ZERO_EXTEND; 2244 2245 LLVMContext &Context = F->getContext(); 2246 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2247 2248 for (unsigned j = 0; j != NumValues; ++j) { 2249 EVT VT = ValueVTs[j]; 2250 2251 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2252 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2253 2254 CallingConv::ID CC = F->getCallingConv(); 2255 2256 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2257 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2258 SmallVector<SDValue, 4> Parts(NumParts); 2259 getCopyToParts(DAG, getCurSDLoc(), 2260 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2261 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2262 2263 // 'inreg' on function refers to return value 2264 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2265 if (RetInReg) 2266 Flags.setInReg(); 2267 2268 if (I.getOperand(0)->getType()->isPointerTy()) { 2269 Flags.setPointer(); 2270 Flags.setPointerAddrSpace( 2271 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2272 } 2273 2274 if (NeedsRegBlock) { 2275 Flags.setInConsecutiveRegs(); 2276 if (j == NumValues - 1) 2277 Flags.setInConsecutiveRegsLast(); 2278 } 2279 2280 // Propagate extension type if any 2281 if (ExtendKind == ISD::SIGN_EXTEND) 2282 Flags.setSExt(); 2283 else if (ExtendKind == ISD::ZERO_EXTEND) 2284 Flags.setZExt(); 2285 else if (F->getAttributes().hasRetAttr(Attribute::NoExt)) 2286 Flags.setNoExt(); 2287 2288 for (unsigned i = 0; i < NumParts; ++i) { 2289 Outs.push_back(ISD::OutputArg(Flags, 2290 Parts[i].getValueType().getSimpleVT(), 2291 VT, /*isfixed=*/true, 0, 0)); 2292 OutVals.push_back(Parts[i]); 2293 } 2294 } 2295 } 2296 } 2297 2298 // Push in swifterror virtual register as the last element of Outs. This makes 2299 // sure swifterror virtual register will be returned in the swifterror 2300 // physical register. 2301 const Function *F = I.getParent()->getParent(); 2302 if (TLI.supportSwiftError() && 2303 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2304 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2305 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2306 Flags.setSwiftError(); 2307 Outs.push_back(ISD::OutputArg( 2308 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2309 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2310 // Create SDNode for the swifterror virtual register. 2311 OutVals.push_back( 2312 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2313 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2314 EVT(TLI.getPointerTy(DL)))); 2315 } 2316 2317 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2318 CallingConv::ID CallConv = 2319 DAG.getMachineFunction().getFunction().getCallingConv(); 2320 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2321 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2322 2323 // Verify that the target's LowerReturn behaved as expected. 2324 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2325 "LowerReturn didn't return a valid chain!"); 2326 2327 // Update the DAG with the new chain value resulting from return lowering. 2328 DAG.setRoot(Chain); 2329 } 2330 2331 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2332 /// created for it, emit nodes to copy the value into the virtual 2333 /// registers. 2334 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2335 // Skip empty types 2336 if (V->getType()->isEmptyTy()) 2337 return; 2338 2339 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2340 if (VMI != FuncInfo.ValueMap.end()) { 2341 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2342 "Unused value assigned virtual registers!"); 2343 CopyValueToVirtualRegister(V, VMI->second); 2344 } 2345 } 2346 2347 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2348 /// the current basic block, add it to ValueMap now so that we'll get a 2349 /// CopyTo/FromReg. 2350 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2351 // No need to export constants. 2352 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2353 2354 // Already exported? 2355 if (FuncInfo.isExportedInst(V)) return; 2356 2357 Register Reg = FuncInfo.InitializeRegForValue(V); 2358 CopyValueToVirtualRegister(V, Reg); 2359 } 2360 2361 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2362 const BasicBlock *FromBB) { 2363 // The operands of the setcc have to be in this block. We don't know 2364 // how to export them from some other block. 2365 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2366 // Can export from current BB. 2367 if (VI->getParent() == FromBB) 2368 return true; 2369 2370 // Is already exported, noop. 2371 return FuncInfo.isExportedInst(V); 2372 } 2373 2374 // If this is an argument, we can export it if the BB is the entry block or 2375 // if it is already exported. 2376 if (isa<Argument>(V)) { 2377 if (FromBB->isEntryBlock()) 2378 return true; 2379 2380 // Otherwise, can only export this if it is already exported. 2381 return FuncInfo.isExportedInst(V); 2382 } 2383 2384 // Otherwise, constants can always be exported. 2385 return true; 2386 } 2387 2388 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2389 BranchProbability 2390 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2391 const MachineBasicBlock *Dst) const { 2392 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2393 const BasicBlock *SrcBB = Src->getBasicBlock(); 2394 const BasicBlock *DstBB = Dst->getBasicBlock(); 2395 if (!BPI) { 2396 // If BPI is not available, set the default probability as 1 / N, where N is 2397 // the number of successors. 2398 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2399 return BranchProbability(1, SuccSize); 2400 } 2401 return BPI->getEdgeProbability(SrcBB, DstBB); 2402 } 2403 2404 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2405 MachineBasicBlock *Dst, 2406 BranchProbability Prob) { 2407 if (!FuncInfo.BPI) 2408 Src->addSuccessorWithoutProb(Dst); 2409 else { 2410 if (Prob.isUnknown()) 2411 Prob = getEdgeProbability(Src, Dst); 2412 Src->addSuccessor(Dst, Prob); 2413 } 2414 } 2415 2416 static bool InBlock(const Value *V, const BasicBlock *BB) { 2417 if (const Instruction *I = dyn_cast<Instruction>(V)) 2418 return I->getParent() == BB; 2419 return true; 2420 } 2421 2422 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2423 /// This function emits a branch and is used at the leaves of an OR or an 2424 /// AND operator tree. 2425 void 2426 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2427 MachineBasicBlock *TBB, 2428 MachineBasicBlock *FBB, 2429 MachineBasicBlock *CurBB, 2430 MachineBasicBlock *SwitchBB, 2431 BranchProbability TProb, 2432 BranchProbability FProb, 2433 bool InvertCond) { 2434 const BasicBlock *BB = CurBB->getBasicBlock(); 2435 2436 // If the leaf of the tree is a comparison, merge the condition into 2437 // the caseblock. 2438 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2439 // The operands of the cmp have to be in this block. We don't know 2440 // how to export them from some other block. If this is the first block 2441 // of the sequence, no exporting is needed. 2442 if (CurBB == SwitchBB || 2443 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2444 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2445 ISD::CondCode Condition; 2446 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2447 ICmpInst::Predicate Pred = 2448 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2449 Condition = getICmpCondCode(Pred); 2450 } else { 2451 const FCmpInst *FC = cast<FCmpInst>(Cond); 2452 FCmpInst::Predicate Pred = 2453 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2454 Condition = getFCmpCondCode(Pred); 2455 if (TM.Options.NoNaNsFPMath) 2456 Condition = getFCmpCodeWithoutNaN(Condition); 2457 } 2458 2459 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2460 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2461 SL->SwitchCases.push_back(CB); 2462 return; 2463 } 2464 } 2465 2466 // Create a CaseBlock record representing this branch. 2467 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2468 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2469 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2470 SL->SwitchCases.push_back(CB); 2471 } 2472 2473 // Collect dependencies on V recursively. This is used for the cost analysis in 2474 // `shouldKeepJumpConditionsTogether`. 2475 static bool collectInstructionDeps( 2476 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V, 2477 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr, 2478 unsigned Depth = 0) { 2479 // Return false if we have an incomplete count. 2480 if (Depth >= SelectionDAG::MaxRecursionDepth) 2481 return false; 2482 2483 auto *I = dyn_cast<Instruction>(V); 2484 if (I == nullptr) 2485 return true; 2486 2487 if (Necessary != nullptr) { 2488 // This instruction is necessary for the other side of the condition so 2489 // don't count it. 2490 if (Necessary->contains(I)) 2491 return true; 2492 } 2493 2494 // Already added this dep. 2495 if (!Deps->try_emplace(I, false).second) 2496 return true; 2497 2498 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx) 2499 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary, 2500 Depth + 1)) 2501 return false; 2502 return true; 2503 } 2504 2505 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether( 2506 const FunctionLoweringInfo &FuncInfo, const BranchInst &I, 2507 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, 2508 TargetLoweringBase::CondMergingParams Params) const { 2509 if (I.getNumSuccessors() != 2) 2510 return false; 2511 2512 if (!I.isConditional()) 2513 return false; 2514 2515 if (Params.BaseCost < 0) 2516 return false; 2517 2518 // Baseline cost. 2519 InstructionCost CostThresh = Params.BaseCost; 2520 2521 BranchProbabilityInfo *BPI = nullptr; 2522 if (Params.LikelyBias || Params.UnlikelyBias) 2523 BPI = FuncInfo.BPI; 2524 if (BPI != nullptr) { 2525 // See if we are either likely to get an early out or compute both lhs/rhs 2526 // of the condition. 2527 BasicBlock *IfFalse = I.getSuccessor(0); 2528 BasicBlock *IfTrue = I.getSuccessor(1); 2529 2530 std::optional<bool> Likely; 2531 if (BPI->isEdgeHot(I.getParent(), IfTrue)) 2532 Likely = true; 2533 else if (BPI->isEdgeHot(I.getParent(), IfFalse)) 2534 Likely = false; 2535 2536 if (Likely) { 2537 if (Opc == (*Likely ? Instruction::And : Instruction::Or)) 2538 // Its likely we will have to compute both lhs and rhs of condition 2539 CostThresh += Params.LikelyBias; 2540 else { 2541 if (Params.UnlikelyBias < 0) 2542 return false; 2543 // Its likely we will get an early out. 2544 CostThresh -= Params.UnlikelyBias; 2545 } 2546 } 2547 } 2548 2549 if (CostThresh <= 0) 2550 return false; 2551 2552 // Collect "all" instructions that lhs condition is dependent on. 2553 // Use map for stable iteration (to avoid non-determanism of iteration of 2554 // SmallPtrSet). The `bool` value is just a dummy. 2555 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps; 2556 collectInstructionDeps(&LhsDeps, Lhs); 2557 // Collect "all" instructions that rhs condition is dependent on AND are 2558 // dependencies of lhs. This gives us an estimate on which instructions we 2559 // stand to save by splitting the condition. 2560 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps)) 2561 return false; 2562 // Add the compare instruction itself unless its a dependency on the LHS. 2563 if (const auto *RhsI = dyn_cast<Instruction>(Rhs)) 2564 if (!LhsDeps.contains(RhsI)) 2565 RhsDeps.try_emplace(RhsI, false); 2566 2567 const auto &TLI = DAG.getTargetLoweringInfo(); 2568 const auto &TTI = 2569 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 2570 2571 InstructionCost CostOfIncluding = 0; 2572 // See if this instruction will need to computed independently of whether RHS 2573 // is. 2574 Value *BrCond = I.getCondition(); 2575 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) { 2576 for (const auto *U : Ins->users()) { 2577 // If user is independent of RHS calculation we don't need to count it. 2578 if (auto *UIns = dyn_cast<Instruction>(U)) 2579 if (UIns != BrCond && !RhsDeps.contains(UIns)) 2580 return false; 2581 } 2582 return true; 2583 }; 2584 2585 // Prune instructions from RHS Deps that are dependencies of unrelated 2586 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly 2587 // arbitrary and just meant to cap the how much time we spend in the pruning 2588 // loop. Its highly unlikely to come into affect. 2589 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth; 2590 // Stop after a certain point. No incorrectness from including too many 2591 // instructions. 2592 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) { 2593 const Instruction *ToDrop = nullptr; 2594 for (const auto &InsPair : RhsDeps) { 2595 if (!ShouldCountInsn(InsPair.first)) { 2596 ToDrop = InsPair.first; 2597 break; 2598 } 2599 } 2600 if (ToDrop == nullptr) 2601 break; 2602 RhsDeps.erase(ToDrop); 2603 } 2604 2605 for (const auto &InsPair : RhsDeps) { 2606 // Finally accumulate latency that we can only attribute to computing the 2607 // RHS condition. Use latency because we are essentially trying to calculate 2608 // the cost of the dependency chain. 2609 // Possible TODO: We could try to estimate ILP and make this more precise. 2610 CostOfIncluding += 2611 TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency); 2612 2613 if (CostOfIncluding > CostThresh) 2614 return false; 2615 } 2616 return true; 2617 } 2618 2619 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2620 MachineBasicBlock *TBB, 2621 MachineBasicBlock *FBB, 2622 MachineBasicBlock *CurBB, 2623 MachineBasicBlock *SwitchBB, 2624 Instruction::BinaryOps Opc, 2625 BranchProbability TProb, 2626 BranchProbability FProb, 2627 bool InvertCond) { 2628 // Skip over not part of the tree and remember to invert op and operands at 2629 // next level. 2630 Value *NotCond; 2631 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2632 InBlock(NotCond, CurBB->getBasicBlock())) { 2633 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2634 !InvertCond); 2635 return; 2636 } 2637 2638 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2639 const Value *BOpOp0, *BOpOp1; 2640 // Compute the effective opcode for Cond, taking into account whether it needs 2641 // to be inverted, e.g. 2642 // and (not (or A, B)), C 2643 // gets lowered as 2644 // and (and (not A, not B), C) 2645 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2646 if (BOp) { 2647 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2648 ? Instruction::And 2649 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2650 ? Instruction::Or 2651 : (Instruction::BinaryOps)0); 2652 if (InvertCond) { 2653 if (BOpc == Instruction::And) 2654 BOpc = Instruction::Or; 2655 else if (BOpc == Instruction::Or) 2656 BOpc = Instruction::And; 2657 } 2658 } 2659 2660 // If this node is not part of the or/and tree, emit it as a branch. 2661 // Note that all nodes in the tree should have same opcode. 2662 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2663 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2664 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2665 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2666 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2667 TProb, FProb, InvertCond); 2668 return; 2669 } 2670 2671 // Create TmpBB after CurBB. 2672 MachineFunction::iterator BBI(CurBB); 2673 MachineFunction &MF = DAG.getMachineFunction(); 2674 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2675 CurBB->getParent()->insert(++BBI, TmpBB); 2676 2677 if (Opc == Instruction::Or) { 2678 // Codegen X | Y as: 2679 // BB1: 2680 // jmp_if_X TBB 2681 // jmp TmpBB 2682 // TmpBB: 2683 // jmp_if_Y TBB 2684 // jmp FBB 2685 // 2686 2687 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2688 // The requirement is that 2689 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2690 // = TrueProb for original BB. 2691 // Assuming the original probabilities are A and B, one choice is to set 2692 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2693 // A/(1+B) and 2B/(1+B). This choice assumes that 2694 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2695 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2696 // TmpBB, but the math is more complicated. 2697 2698 auto NewTrueProb = TProb / 2; 2699 auto NewFalseProb = TProb / 2 + FProb; 2700 // Emit the LHS condition. 2701 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2702 NewFalseProb, InvertCond); 2703 2704 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2705 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2706 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2707 // Emit the RHS condition into TmpBB. 2708 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2709 Probs[1], InvertCond); 2710 } else { 2711 assert(Opc == Instruction::And && "Unknown merge op!"); 2712 // Codegen X & Y as: 2713 // BB1: 2714 // jmp_if_X TmpBB 2715 // jmp FBB 2716 // TmpBB: 2717 // jmp_if_Y TBB 2718 // jmp FBB 2719 // 2720 // This requires creation of TmpBB after CurBB. 2721 2722 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2723 // The requirement is that 2724 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2725 // = FalseProb for original BB. 2726 // Assuming the original probabilities are A and B, one choice is to set 2727 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2728 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2729 // TrueProb for BB1 * FalseProb for TmpBB. 2730 2731 auto NewTrueProb = TProb + FProb / 2; 2732 auto NewFalseProb = FProb / 2; 2733 // Emit the LHS condition. 2734 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2735 NewFalseProb, InvertCond); 2736 2737 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2738 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2739 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2740 // Emit the RHS condition into TmpBB. 2741 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2742 Probs[1], InvertCond); 2743 } 2744 } 2745 2746 /// If the set of cases should be emitted as a series of branches, return true. 2747 /// If we should emit this as a bunch of and/or'd together conditions, return 2748 /// false. 2749 bool 2750 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2751 if (Cases.size() != 2) return true; 2752 2753 // If this is two comparisons of the same values or'd or and'd together, they 2754 // will get folded into a single comparison, so don't emit two blocks. 2755 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2756 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2757 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2758 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2759 return false; 2760 } 2761 2762 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2763 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2764 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2765 Cases[0].CC == Cases[1].CC && 2766 isa<Constant>(Cases[0].CmpRHS) && 2767 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2768 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2769 return false; 2770 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2771 return false; 2772 } 2773 2774 return true; 2775 } 2776 2777 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2778 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2779 2780 // Update machine-CFG edges. 2781 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0)); 2782 2783 if (I.isUnconditional()) { 2784 // Update machine-CFG edges. 2785 BrMBB->addSuccessor(Succ0MBB); 2786 2787 // If this is not a fall-through branch or optimizations are switched off, 2788 // emit the branch. 2789 if (Succ0MBB != NextBlock(BrMBB) || 2790 TM.getOptLevel() == CodeGenOptLevel::None) { 2791 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2792 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2793 setValue(&I, Br); 2794 DAG.setRoot(Br); 2795 } 2796 2797 return; 2798 } 2799 2800 // If this condition is one of the special cases we handle, do special stuff 2801 // now. 2802 const Value *CondVal = I.getCondition(); 2803 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1)); 2804 2805 // If this is a series of conditions that are or'd or and'd together, emit 2806 // this as a sequence of branches instead of setcc's with and/or operations. 2807 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2808 // unpredictable branches, and vector extracts because those jumps are likely 2809 // expensive for any target), this should improve performance. 2810 // For example, instead of something like: 2811 // cmp A, B 2812 // C = seteq 2813 // cmp D, E 2814 // F = setle 2815 // or C, F 2816 // jnz foo 2817 // Emit: 2818 // cmp A, B 2819 // je foo 2820 // cmp D, E 2821 // jle foo 2822 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable); 2823 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2824 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2825 BOp->hasOneUse() && !IsUnpredictable) { 2826 Value *Vec; 2827 const Value *BOp0, *BOp1; 2828 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2829 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2830 Opcode = Instruction::And; 2831 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2832 Opcode = Instruction::Or; 2833 2834 if (Opcode && 2835 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2836 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) && 2837 !shouldKeepJumpConditionsTogether( 2838 FuncInfo, I, Opcode, BOp0, BOp1, 2839 DAG.getTargetLoweringInfo().getJumpConditionMergingParams( 2840 Opcode, BOp0, BOp1))) { 2841 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2842 getEdgeProbability(BrMBB, Succ0MBB), 2843 getEdgeProbability(BrMBB, Succ1MBB), 2844 /*InvertCond=*/false); 2845 // If the compares in later blocks need to use values not currently 2846 // exported from this block, export them now. This block should always 2847 // be the first entry. 2848 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2849 2850 // Allow some cases to be rejected. 2851 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2852 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2853 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2854 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2855 } 2856 2857 // Emit the branch for this block. 2858 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2859 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2860 return; 2861 } 2862 2863 // Okay, we decided not to do this, remove any inserted MBB's and clear 2864 // SwitchCases. 2865 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2866 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2867 2868 SL->SwitchCases.clear(); 2869 } 2870 } 2871 2872 // Create a CaseBlock record representing this branch. 2873 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2874 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(), 2875 BranchProbability::getUnknown(), BranchProbability::getUnknown(), 2876 IsUnpredictable); 2877 2878 // Use visitSwitchCase to actually insert the fast branch sequence for this 2879 // cond branch. 2880 visitSwitchCase(CB, BrMBB); 2881 } 2882 2883 /// visitSwitchCase - Emits the necessary code to represent a single node in 2884 /// the binary search tree resulting from lowering a switch instruction. 2885 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2886 MachineBasicBlock *SwitchBB) { 2887 SDValue Cond; 2888 SDValue CondLHS = getValue(CB.CmpLHS); 2889 SDLoc dl = CB.DL; 2890 2891 if (CB.CC == ISD::SETTRUE) { 2892 // Branch or fall through to TrueBB. 2893 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2894 SwitchBB->normalizeSuccProbs(); 2895 if (CB.TrueBB != NextBlock(SwitchBB)) { 2896 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2897 DAG.getBasicBlock(CB.TrueBB))); 2898 } 2899 return; 2900 } 2901 2902 auto &TLI = DAG.getTargetLoweringInfo(); 2903 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2904 2905 // Build the setcc now. 2906 if (!CB.CmpMHS) { 2907 // Fold "(X == true)" to X and "(X == false)" to !X to 2908 // handle common cases produced by branch lowering. 2909 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2910 CB.CC == ISD::SETEQ) 2911 Cond = CondLHS; 2912 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2913 CB.CC == ISD::SETEQ) { 2914 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2915 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2916 } else { 2917 SDValue CondRHS = getValue(CB.CmpRHS); 2918 2919 // If a pointer's DAG type is larger than its memory type then the DAG 2920 // values are zero-extended. This breaks signed comparisons so truncate 2921 // back to the underlying type before doing the compare. 2922 if (CondLHS.getValueType() != MemVT) { 2923 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2924 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2925 } 2926 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2927 } 2928 } else { 2929 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2930 2931 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2932 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2933 2934 SDValue CmpOp = getValue(CB.CmpMHS); 2935 EVT VT = CmpOp.getValueType(); 2936 2937 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2938 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2939 ISD::SETLE); 2940 } else { 2941 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2942 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2943 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2944 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2945 } 2946 } 2947 2948 // Update successor info 2949 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2950 // TrueBB and FalseBB are always different unless the incoming IR is 2951 // degenerate. This only happens when running llc on weird IR. 2952 if (CB.TrueBB != CB.FalseBB) 2953 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2954 SwitchBB->normalizeSuccProbs(); 2955 2956 // If the lhs block is the next block, invert the condition so that we can 2957 // fall through to the lhs instead of the rhs block. 2958 if (CB.TrueBB == NextBlock(SwitchBB)) { 2959 std::swap(CB.TrueBB, CB.FalseBB); 2960 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2961 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2962 } 2963 2964 SDNodeFlags Flags; 2965 Flags.setUnpredictable(CB.IsUnpredictable); 2966 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(), 2967 Cond, DAG.getBasicBlock(CB.TrueBB), Flags); 2968 2969 setValue(CurInst, BrCond); 2970 2971 // Insert the false branch. Do this even if it's a fall through branch, 2972 // this makes it easier to do DAG optimizations which require inverting 2973 // the branch condition. 2974 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2975 DAG.getBasicBlock(CB.FalseBB)); 2976 2977 DAG.setRoot(BrCond); 2978 } 2979 2980 /// visitJumpTable - Emit JumpTable node in the current MBB 2981 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2982 // Emit the code for the jump table 2983 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2984 assert(JT.Reg && "Should lower JT Header first!"); 2985 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout()); 2986 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2987 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2988 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2989 Index.getValue(1), Table, Index); 2990 DAG.setRoot(BrJumpTable); 2991 } 2992 2993 /// visitJumpTableHeader - This function emits necessary code to produce index 2994 /// in the JumpTable from switch case. 2995 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2996 JumpTableHeader &JTH, 2997 MachineBasicBlock *SwitchBB) { 2998 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2999 const SDLoc &dl = *JT.SL; 3000 3001 // Subtract the lowest switch case value from the value being switched on. 3002 SDValue SwitchOp = getValue(JTH.SValue); 3003 EVT VT = SwitchOp.getValueType(); 3004 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 3005 DAG.getConstant(JTH.First, dl, VT)); 3006 3007 // The SDNode we just created, which holds the value being switched on minus 3008 // the smallest case value, needs to be copied to a virtual register so it 3009 // can be used as an index into the jump table in a subsequent basic block. 3010 // This value may be smaller or larger than the target's pointer type, and 3011 // therefore require extension or truncating. 3012 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3013 SwitchOp = 3014 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout())); 3015 3016 Register JumpTableReg = 3017 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout())); 3018 SDValue CopyTo = 3019 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp); 3020 JT.Reg = JumpTableReg; 3021 3022 if (!JTH.FallthroughUnreachable) { 3023 // Emit the range check for the jump table, and branch to the default block 3024 // for the switch statement if the value being switched on exceeds the 3025 // largest case in the switch. 3026 SDValue CMP = DAG.getSetCC( 3027 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3028 Sub.getValueType()), 3029 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 3030 3031 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3032 MVT::Other, CopyTo, CMP, 3033 DAG.getBasicBlock(JT.Default)); 3034 3035 // Avoid emitting unnecessary branches to the next block. 3036 if (JT.MBB != NextBlock(SwitchBB)) 3037 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 3038 DAG.getBasicBlock(JT.MBB)); 3039 3040 DAG.setRoot(BrCond); 3041 } else { 3042 // Avoid emitting unnecessary branches to the next block. 3043 if (JT.MBB != NextBlock(SwitchBB)) 3044 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 3045 DAG.getBasicBlock(JT.MBB))); 3046 else 3047 DAG.setRoot(CopyTo); 3048 } 3049 } 3050 3051 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 3052 /// variable if there exists one. 3053 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 3054 SDValue &Chain) { 3055 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3056 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3057 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3058 MachineFunction &MF = DAG.getMachineFunction(); 3059 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 3060 MachineSDNode *Node = 3061 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 3062 if (Global) { 3063 MachinePointerInfo MPInfo(Global); 3064 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 3065 MachineMemOperand::MODereferenceable; 3066 MachineMemOperand *MemRef = MF.getMachineMemOperand( 3067 MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8), 3068 DAG.getEVTAlign(PtrTy)); 3069 DAG.setNodeMemRefs(Node, {MemRef}); 3070 } 3071 if (PtrTy != PtrMemTy) 3072 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 3073 return SDValue(Node, 0); 3074 } 3075 3076 /// Codegen a new tail for a stack protector check ParentMBB which has had its 3077 /// tail spliced into a stack protector check success bb. 3078 /// 3079 /// For a high level explanation of how this fits into the stack protector 3080 /// generation see the comment on the declaration of class 3081 /// StackProtectorDescriptor. 3082 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 3083 MachineBasicBlock *ParentBB) { 3084 3085 // First create the loads to the guard/stack slot for the comparison. 3086 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3087 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3088 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3089 3090 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 3091 int FI = MFI.getStackProtectorIndex(); 3092 3093 SDValue Guard; 3094 SDLoc dl = getCurSDLoc(); 3095 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 3096 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 3097 Align Align = 3098 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 3099 3100 // Generate code to load the content of the guard slot. 3101 SDValue GuardVal = DAG.getLoad( 3102 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 3103 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 3104 MachineMemOperand::MOVolatile); 3105 3106 if (TLI.useStackGuardXorFP()) 3107 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 3108 3109 // Retrieve guard check function, nullptr if instrumentation is inlined. 3110 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 3111 // The target provides a guard check function to validate the guard value. 3112 // Generate a call to that function with the content of the guard slot as 3113 // argument. 3114 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 3115 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 3116 3117 TargetLowering::ArgListTy Args; 3118 TargetLowering::ArgListEntry Entry; 3119 Entry.Node = GuardVal; 3120 Entry.Ty = FnTy->getParamType(0); 3121 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 3122 Entry.IsInReg = true; 3123 Args.push_back(Entry); 3124 3125 TargetLowering::CallLoweringInfo CLI(DAG); 3126 CLI.setDebugLoc(getCurSDLoc()) 3127 .setChain(DAG.getEntryNode()) 3128 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 3129 getValue(GuardCheckFn), std::move(Args)); 3130 3131 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 3132 DAG.setRoot(Result.second); 3133 return; 3134 } 3135 3136 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 3137 // Otherwise, emit a volatile load to retrieve the stack guard value. 3138 SDValue Chain = DAG.getEntryNode(); 3139 if (TLI.useLoadStackGuardNode(M)) { 3140 Guard = getLoadStackGuard(DAG, dl, Chain); 3141 } else { 3142 const Value *IRGuard = TLI.getSDagStackGuard(M); 3143 SDValue GuardPtr = getValue(IRGuard); 3144 3145 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 3146 MachinePointerInfo(IRGuard, 0), Align, 3147 MachineMemOperand::MOVolatile); 3148 } 3149 3150 // Perform the comparison via a getsetcc. 3151 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 3152 *DAG.getContext(), 3153 Guard.getValueType()), 3154 Guard, GuardVal, ISD::SETNE); 3155 3156 // If the guard/stackslot do not equal, branch to failure MBB. 3157 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3158 MVT::Other, GuardVal.getOperand(0), 3159 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 3160 // Otherwise branch to success MBB. 3161 SDValue Br = DAG.getNode(ISD::BR, dl, 3162 MVT::Other, BrCond, 3163 DAG.getBasicBlock(SPD.getSuccessMBB())); 3164 3165 DAG.setRoot(Br); 3166 } 3167 3168 /// Codegen the failure basic block for a stack protector check. 3169 /// 3170 /// A failure stack protector machine basic block consists simply of a call to 3171 /// __stack_chk_fail(). 3172 /// 3173 /// For a high level explanation of how this fits into the stack protector 3174 /// generation see the comment on the declaration of class 3175 /// StackProtectorDescriptor. 3176 void 3177 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 3178 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3179 TargetLowering::MakeLibCallOptions CallOptions; 3180 CallOptions.setDiscardResult(true); 3181 SDValue Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, 3182 MVT::isVoid, {}, CallOptions, getCurSDLoc()) 3183 .second; 3184 3185 // Emit a trap instruction if we are required to do so. 3186 const TargetOptions &TargetOpts = DAG.getTarget().Options; 3187 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn) 3188 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3189 3190 DAG.setRoot(Chain); 3191 } 3192 3193 /// visitBitTestHeader - This function emits necessary code to produce value 3194 /// suitable for "bit tests" 3195 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3196 MachineBasicBlock *SwitchBB) { 3197 SDLoc dl = getCurSDLoc(); 3198 3199 // Subtract the minimum value. 3200 SDValue SwitchOp = getValue(B.SValue); 3201 EVT VT = SwitchOp.getValueType(); 3202 SDValue RangeSub = 3203 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3204 3205 // Determine the type of the test operands. 3206 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3207 bool UsePtrType = false; 3208 if (!TLI.isTypeLegal(VT)) { 3209 UsePtrType = true; 3210 } else { 3211 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3212 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3213 // Switch table case range are encoded into series of masks. 3214 // Just use pointer type, it's guaranteed to fit. 3215 UsePtrType = true; 3216 break; 3217 } 3218 } 3219 SDValue Sub = RangeSub; 3220 if (UsePtrType) { 3221 VT = TLI.getPointerTy(DAG.getDataLayout()); 3222 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3223 } 3224 3225 B.RegVT = VT.getSimpleVT(); 3226 B.Reg = FuncInfo.CreateReg(B.RegVT); 3227 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3228 3229 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3230 3231 if (!B.FallthroughUnreachable) 3232 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3233 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3234 SwitchBB->normalizeSuccProbs(); 3235 3236 SDValue Root = CopyTo; 3237 if (!B.FallthroughUnreachable) { 3238 // Conditional branch to the default block. 3239 SDValue RangeCmp = DAG.getSetCC(dl, 3240 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3241 RangeSub.getValueType()), 3242 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3243 ISD::SETUGT); 3244 3245 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3246 DAG.getBasicBlock(B.Default)); 3247 } 3248 3249 // Avoid emitting unnecessary branches to the next block. 3250 if (MBB != NextBlock(SwitchBB)) 3251 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3252 3253 DAG.setRoot(Root); 3254 } 3255 3256 /// visitBitTestCase - this function produces one "bit test" 3257 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3258 MachineBasicBlock *NextMBB, 3259 BranchProbability BranchProbToNext, 3260 Register Reg, BitTestCase &B, 3261 MachineBasicBlock *SwitchBB) { 3262 SDLoc dl = getCurSDLoc(); 3263 MVT VT = BB.RegVT; 3264 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3265 SDValue Cmp; 3266 unsigned PopCount = llvm::popcount(B.Mask); 3267 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3268 if (PopCount == 1) { 3269 // Testing for a single bit; just compare the shift count with what it 3270 // would need to be to shift a 1 bit in that position. 3271 Cmp = DAG.getSetCC( 3272 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3273 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3274 ISD::SETEQ); 3275 } else if (PopCount == BB.Range) { 3276 // There is only one zero bit in the range, test for it directly. 3277 Cmp = DAG.getSetCC( 3278 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3279 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3280 } else { 3281 // Make desired shift 3282 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3283 DAG.getConstant(1, dl, VT), ShiftOp); 3284 3285 // Emit bit tests and jumps 3286 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3287 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3288 Cmp = DAG.getSetCC( 3289 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3290 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3291 } 3292 3293 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3294 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3295 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3296 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3297 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3298 // one as they are relative probabilities (and thus work more like weights), 3299 // and hence we need to normalize them to let the sum of them become one. 3300 SwitchBB->normalizeSuccProbs(); 3301 3302 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3303 MVT::Other, getControlRoot(), 3304 Cmp, DAG.getBasicBlock(B.TargetBB)); 3305 3306 // Avoid emitting unnecessary branches to the next block. 3307 if (NextMBB != NextBlock(SwitchBB)) 3308 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3309 DAG.getBasicBlock(NextMBB)); 3310 3311 DAG.setRoot(BrAnd); 3312 } 3313 3314 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3315 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3316 3317 // Retrieve successors. Look through artificial IR level blocks like 3318 // catchswitch for successors. 3319 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0)); 3320 const BasicBlock *EHPadBB = I.getSuccessor(1); 3321 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB); 3322 3323 // Deopt and ptrauth bundles are lowered in helper functions, and we don't 3324 // have to do anything here to lower funclet bundles. 3325 assert(!I.hasOperandBundlesOtherThan( 3326 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3327 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3328 LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth, 3329 LLVMContext::OB_clang_arc_attachedcall}) && 3330 "Cannot lower invokes with arbitrary operand bundles yet!"); 3331 3332 const Value *Callee(I.getCalledOperand()); 3333 const Function *Fn = dyn_cast<Function>(Callee); 3334 if (isa<InlineAsm>(Callee)) 3335 visitInlineAsm(I, EHPadBB); 3336 else if (Fn && Fn->isIntrinsic()) { 3337 switch (Fn->getIntrinsicID()) { 3338 default: 3339 llvm_unreachable("Cannot invoke this intrinsic"); 3340 case Intrinsic::donothing: 3341 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3342 case Intrinsic::seh_try_begin: 3343 case Intrinsic::seh_scope_begin: 3344 case Intrinsic::seh_try_end: 3345 case Intrinsic::seh_scope_end: 3346 if (EHPadMBB) 3347 // a block referenced by EH table 3348 // so dtor-funclet not removed by opts 3349 EHPadMBB->setMachineBlockAddressTaken(); 3350 break; 3351 case Intrinsic::experimental_patchpoint_void: 3352 case Intrinsic::experimental_patchpoint: 3353 visitPatchpoint(I, EHPadBB); 3354 break; 3355 case Intrinsic::experimental_gc_statepoint: 3356 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3357 break; 3358 case Intrinsic::wasm_rethrow: { 3359 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3360 // special because it can be invoked, so we manually lower it to a DAG 3361 // node here. 3362 SmallVector<SDValue, 8> Ops; 3363 Ops.push_back(getControlRoot()); // inchain for the terminator node 3364 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3365 Ops.push_back( 3366 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3367 TLI.getPointerTy(DAG.getDataLayout()))); 3368 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3369 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3370 break; 3371 } 3372 } 3373 } else if (I.hasDeoptState()) { 3374 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3375 // Eventually we will support lowering the @llvm.experimental.deoptimize 3376 // intrinsic, and right now there are no plans to support other intrinsics 3377 // with deopt state. 3378 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3379 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 3380 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB); 3381 } else { 3382 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3383 } 3384 3385 // If the value of the invoke is used outside of its defining block, make it 3386 // available as a virtual register. 3387 // We already took care of the exported value for the statepoint instruction 3388 // during call to the LowerStatepoint. 3389 if (!isa<GCStatepointInst>(I)) { 3390 CopyToExportRegsIfNeeded(&I); 3391 } 3392 3393 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3394 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3395 BranchProbability EHPadBBProb = 3396 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3397 : BranchProbability::getZero(); 3398 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3399 3400 // Update successor info. 3401 addSuccessorWithProb(InvokeMBB, Return); 3402 for (auto &UnwindDest : UnwindDests) { 3403 UnwindDest.first->setIsEHPad(); 3404 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3405 } 3406 InvokeMBB->normalizeSuccProbs(); 3407 3408 // Drop into normal successor. 3409 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3410 DAG.getBasicBlock(Return))); 3411 } 3412 3413 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3414 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3415 3416 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3417 // have to do anything here to lower funclet bundles. 3418 assert(!I.hasOperandBundlesOtherThan( 3419 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3420 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3421 3422 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3423 visitInlineAsm(I); 3424 CopyToExportRegsIfNeeded(&I); 3425 3426 // Retrieve successors. 3427 SmallPtrSet<BasicBlock *, 8> Dests; 3428 Dests.insert(I.getDefaultDest()); 3429 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest()); 3430 3431 // Update successor info. 3432 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3433 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3434 BasicBlock *Dest = I.getIndirectDest(i); 3435 MachineBasicBlock *Target = FuncInfo.getMBB(Dest); 3436 Target->setIsInlineAsmBrIndirectTarget(); 3437 Target->setMachineBlockAddressTaken(); 3438 Target->setLabelMustBeEmitted(); 3439 // Don't add duplicate machine successors. 3440 if (Dests.insert(Dest).second) 3441 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3442 } 3443 CallBrMBB->normalizeSuccProbs(); 3444 3445 // Drop into default successor. 3446 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3447 MVT::Other, getControlRoot(), 3448 DAG.getBasicBlock(Return))); 3449 } 3450 3451 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3452 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3453 } 3454 3455 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3456 assert(FuncInfo.MBB->isEHPad() && 3457 "Call to landingpad not in landing pad!"); 3458 3459 // If there aren't registers to copy the values into (e.g., during SjLj 3460 // exceptions), then don't bother to create these DAG nodes. 3461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3462 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3463 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3464 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3465 return; 3466 3467 // If landingpad's return type is token type, we don't create DAG nodes 3468 // for its exception pointer and selector value. The extraction of exception 3469 // pointer or selector value from token type landingpads is not currently 3470 // supported. 3471 if (LP.getType()->isTokenTy()) 3472 return; 3473 3474 SmallVector<EVT, 2> ValueVTs; 3475 SDLoc dl = getCurSDLoc(); 3476 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3477 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3478 3479 // Get the two live-in registers as SDValues. The physregs have already been 3480 // copied into virtual registers. 3481 SDValue Ops[2]; 3482 if (FuncInfo.ExceptionPointerVirtReg) { 3483 Ops[0] = DAG.getZExtOrTrunc( 3484 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3485 FuncInfo.ExceptionPointerVirtReg, 3486 TLI.getPointerTy(DAG.getDataLayout())), 3487 dl, ValueVTs[0]); 3488 } else { 3489 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3490 } 3491 Ops[1] = DAG.getZExtOrTrunc( 3492 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3493 FuncInfo.ExceptionSelectorVirtReg, 3494 TLI.getPointerTy(DAG.getDataLayout())), 3495 dl, ValueVTs[1]); 3496 3497 // Merge into one. 3498 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3499 DAG.getVTList(ValueVTs), Ops); 3500 setValue(&LP, Res); 3501 } 3502 3503 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3504 MachineBasicBlock *Last) { 3505 // Update JTCases. 3506 for (JumpTableBlock &JTB : SL->JTCases) 3507 if (JTB.first.HeaderBB == First) 3508 JTB.first.HeaderBB = Last; 3509 3510 // Update BitTestCases. 3511 for (BitTestBlock &BTB : SL->BitTestCases) 3512 if (BTB.Parent == First) 3513 BTB.Parent = Last; 3514 } 3515 3516 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3517 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3518 3519 // Update machine-CFG edges with unique successors. 3520 SmallSet<BasicBlock*, 32> Done; 3521 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3522 BasicBlock *BB = I.getSuccessor(i); 3523 bool Inserted = Done.insert(BB).second; 3524 if (!Inserted) 3525 continue; 3526 3527 MachineBasicBlock *Succ = FuncInfo.getMBB(BB); 3528 addSuccessorWithProb(IndirectBrMBB, Succ); 3529 } 3530 IndirectBrMBB->normalizeSuccProbs(); 3531 3532 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3533 MVT::Other, getControlRoot(), 3534 getValue(I.getAddress()))); 3535 } 3536 3537 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3538 if (!DAG.getTarget().Options.TrapUnreachable) 3539 return; 3540 3541 // We may be able to ignore unreachable behind a noreturn call. 3542 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode()); 3543 Call && Call->doesNotReturn()) { 3544 if (DAG.getTarget().Options.NoTrapAfterNoreturn) 3545 return; 3546 // Do not emit an additional trap instruction. 3547 if (Call->isNonContinuableTrap()) 3548 return; 3549 } 3550 3551 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3552 } 3553 3554 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3555 SDNodeFlags Flags; 3556 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3557 Flags.copyFMF(*FPOp); 3558 3559 SDValue Op = getValue(I.getOperand(0)); 3560 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3561 Op, Flags); 3562 setValue(&I, UnNodeValue); 3563 } 3564 3565 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3566 SDNodeFlags Flags; 3567 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3568 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3569 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3570 } 3571 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3572 Flags.setExact(ExactOp->isExact()); 3573 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3574 Flags.setDisjoint(DisjointOp->isDisjoint()); 3575 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3576 Flags.copyFMF(*FPOp); 3577 3578 SDValue Op1 = getValue(I.getOperand(0)); 3579 SDValue Op2 = getValue(I.getOperand(1)); 3580 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3581 Op1, Op2, Flags); 3582 setValue(&I, BinNodeValue); 3583 } 3584 3585 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3586 SDValue Op1 = getValue(I.getOperand(0)); 3587 SDValue Op2 = getValue(I.getOperand(1)); 3588 3589 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3590 Op1.getValueType(), DAG.getDataLayout()); 3591 3592 // Coerce the shift amount to the right type if we can. This exposes the 3593 // truncate or zext to optimization early. 3594 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3595 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3596 "Unexpected shift type"); 3597 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3598 } 3599 3600 bool nuw = false; 3601 bool nsw = false; 3602 bool exact = false; 3603 3604 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3605 3606 if (const OverflowingBinaryOperator *OFBinOp = 3607 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3608 nuw = OFBinOp->hasNoUnsignedWrap(); 3609 nsw = OFBinOp->hasNoSignedWrap(); 3610 } 3611 if (const PossiblyExactOperator *ExactOp = 3612 dyn_cast<const PossiblyExactOperator>(&I)) 3613 exact = ExactOp->isExact(); 3614 } 3615 SDNodeFlags Flags; 3616 Flags.setExact(exact); 3617 Flags.setNoSignedWrap(nsw); 3618 Flags.setNoUnsignedWrap(nuw); 3619 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3620 Flags); 3621 setValue(&I, Res); 3622 } 3623 3624 void SelectionDAGBuilder::visitSDiv(const User &I) { 3625 SDValue Op1 = getValue(I.getOperand(0)); 3626 SDValue Op2 = getValue(I.getOperand(1)); 3627 3628 SDNodeFlags Flags; 3629 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3630 cast<PossiblyExactOperator>(&I)->isExact()); 3631 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3632 Op2, Flags)); 3633 } 3634 3635 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) { 3636 ICmpInst::Predicate predicate = I.getPredicate(); 3637 SDValue Op1 = getValue(I.getOperand(0)); 3638 SDValue Op2 = getValue(I.getOperand(1)); 3639 ISD::CondCode Opcode = getICmpCondCode(predicate); 3640 3641 auto &TLI = DAG.getTargetLoweringInfo(); 3642 EVT MemVT = 3643 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3644 3645 // If a pointer's DAG type is larger than its memory type then the DAG values 3646 // are zero-extended. This breaks signed comparisons so truncate back to the 3647 // underlying type before doing the compare. 3648 if (Op1.getValueType() != MemVT) { 3649 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3650 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3651 } 3652 3653 SDNodeFlags Flags; 3654 Flags.setSameSign(I.hasSameSign()); 3655 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3656 3657 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3658 I.getType()); 3659 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3660 } 3661 3662 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) { 3663 FCmpInst::Predicate predicate = I.getPredicate(); 3664 SDValue Op1 = getValue(I.getOperand(0)); 3665 SDValue Op2 = getValue(I.getOperand(1)); 3666 3667 ISD::CondCode Condition = getFCmpCondCode(predicate); 3668 auto *FPMO = cast<FPMathOperator>(&I); 3669 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3670 Condition = getFCmpCodeWithoutNaN(Condition); 3671 3672 SDNodeFlags Flags; 3673 Flags.copyFMF(*FPMO); 3674 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3675 3676 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3677 I.getType()); 3678 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3679 } 3680 3681 // Check if the condition of the select has one use or two users that are both 3682 // selects with the same condition. 3683 static bool hasOnlySelectUsers(const Value *Cond) { 3684 return llvm::all_of(Cond->users(), [](const Value *V) { 3685 return isa<SelectInst>(V); 3686 }); 3687 } 3688 3689 void SelectionDAGBuilder::visitSelect(const User &I) { 3690 SmallVector<EVT, 4> ValueVTs; 3691 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3692 ValueVTs); 3693 unsigned NumValues = ValueVTs.size(); 3694 if (NumValues == 0) return; 3695 3696 SmallVector<SDValue, 4> Values(NumValues); 3697 SDValue Cond = getValue(I.getOperand(0)); 3698 SDValue LHSVal = getValue(I.getOperand(1)); 3699 SDValue RHSVal = getValue(I.getOperand(2)); 3700 SmallVector<SDValue, 1> BaseOps(1, Cond); 3701 ISD::NodeType OpCode = 3702 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3703 3704 bool IsUnaryAbs = false; 3705 bool Negate = false; 3706 3707 SDNodeFlags Flags; 3708 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3709 Flags.copyFMF(*FPOp); 3710 3711 Flags.setUnpredictable( 3712 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3713 3714 // Min/max matching is only viable if all output VTs are the same. 3715 if (all_equal(ValueVTs)) { 3716 EVT VT = ValueVTs[0]; 3717 LLVMContext &Ctx = *DAG.getContext(); 3718 auto &TLI = DAG.getTargetLoweringInfo(); 3719 3720 // We care about the legality of the operation after it has been type 3721 // legalized. 3722 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3723 VT = TLI.getTypeToTransformTo(Ctx, VT); 3724 3725 // If the vselect is legal, assume we want to leave this as a vector setcc + 3726 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3727 // min/max is legal on the scalar type. 3728 bool UseScalarMinMax = VT.isVector() && 3729 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3730 3731 // ValueTracking's select pattern matching does not account for -0.0, 3732 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3733 // -0.0 is less than +0.0. 3734 const Value *LHS, *RHS; 3735 auto SPR = matchSelectPattern(&I, LHS, RHS); 3736 ISD::NodeType Opc = ISD::DELETED_NODE; 3737 switch (SPR.Flavor) { 3738 case SPF_UMAX: Opc = ISD::UMAX; break; 3739 case SPF_UMIN: Opc = ISD::UMIN; break; 3740 case SPF_SMAX: Opc = ISD::SMAX; break; 3741 case SPF_SMIN: Opc = ISD::SMIN; break; 3742 case SPF_FMINNUM: 3743 switch (SPR.NaNBehavior) { 3744 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3745 case SPNB_RETURNS_NAN: break; 3746 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3747 case SPNB_RETURNS_ANY: 3748 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3749 (UseScalarMinMax && 3750 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3751 Opc = ISD::FMINNUM; 3752 break; 3753 } 3754 break; 3755 case SPF_FMAXNUM: 3756 switch (SPR.NaNBehavior) { 3757 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3758 case SPNB_RETURNS_NAN: break; 3759 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3760 case SPNB_RETURNS_ANY: 3761 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3762 (UseScalarMinMax && 3763 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3764 Opc = ISD::FMAXNUM; 3765 break; 3766 } 3767 break; 3768 case SPF_NABS: 3769 Negate = true; 3770 [[fallthrough]]; 3771 case SPF_ABS: 3772 IsUnaryAbs = true; 3773 Opc = ISD::ABS; 3774 break; 3775 default: break; 3776 } 3777 3778 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3779 (TLI.isOperationLegalOrCustom(Opc, VT) || 3780 (UseScalarMinMax && 3781 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3782 // If the underlying comparison instruction is used by any other 3783 // instruction, the consumed instructions won't be destroyed, so it is 3784 // not profitable to convert to a min/max. 3785 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3786 OpCode = Opc; 3787 LHSVal = getValue(LHS); 3788 RHSVal = getValue(RHS); 3789 BaseOps.clear(); 3790 } 3791 3792 if (IsUnaryAbs) { 3793 OpCode = Opc; 3794 LHSVal = getValue(LHS); 3795 BaseOps.clear(); 3796 } 3797 } 3798 3799 if (IsUnaryAbs) { 3800 for (unsigned i = 0; i != NumValues; ++i) { 3801 SDLoc dl = getCurSDLoc(); 3802 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3803 Values[i] = 3804 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3805 if (Negate) 3806 Values[i] = DAG.getNegative(Values[i], dl, VT); 3807 } 3808 } else { 3809 for (unsigned i = 0; i != NumValues; ++i) { 3810 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3811 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3812 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3813 Values[i] = DAG.getNode( 3814 OpCode, getCurSDLoc(), 3815 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3816 } 3817 } 3818 3819 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3820 DAG.getVTList(ValueVTs), Values)); 3821 } 3822 3823 void SelectionDAGBuilder::visitTrunc(const User &I) { 3824 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3825 SDValue N = getValue(I.getOperand(0)); 3826 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3827 I.getType()); 3828 SDNodeFlags Flags; 3829 if (auto *Trunc = dyn_cast<TruncInst>(&I)) { 3830 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap()); 3831 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap()); 3832 } 3833 3834 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags)); 3835 } 3836 3837 void SelectionDAGBuilder::visitZExt(const User &I) { 3838 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3839 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3840 SDValue N = getValue(I.getOperand(0)); 3841 auto &TLI = DAG.getTargetLoweringInfo(); 3842 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3843 3844 SDNodeFlags Flags; 3845 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3846 Flags.setNonNeg(PNI->hasNonNeg()); 3847 3848 // Eagerly use nonneg information to canonicalize towards sign_extend if 3849 // that is the target's preference. 3850 // TODO: Let the target do this later. 3851 if (Flags.hasNonNeg() && 3852 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3853 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3854 return; 3855 } 3856 3857 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3858 } 3859 3860 void SelectionDAGBuilder::visitSExt(const User &I) { 3861 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3862 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3863 SDValue N = getValue(I.getOperand(0)); 3864 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3865 I.getType()); 3866 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3867 } 3868 3869 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3870 // FPTrunc is never a no-op cast, no need to check 3871 SDValue N = getValue(I.getOperand(0)); 3872 SDLoc dl = getCurSDLoc(); 3873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3874 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3875 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3876 DAG.getTargetConstant( 3877 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3878 } 3879 3880 void SelectionDAGBuilder::visitFPExt(const User &I) { 3881 // FPExt is never a no-op cast, no need to check 3882 SDValue N = getValue(I.getOperand(0)); 3883 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3884 I.getType()); 3885 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3886 } 3887 3888 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3889 // FPToUI is never a no-op cast, no need to check 3890 SDValue N = getValue(I.getOperand(0)); 3891 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3892 I.getType()); 3893 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3894 } 3895 3896 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3897 // FPToSI is never a no-op cast, no need to check 3898 SDValue N = getValue(I.getOperand(0)); 3899 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3900 I.getType()); 3901 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3902 } 3903 3904 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3905 // UIToFP is never a no-op cast, no need to check 3906 SDValue N = getValue(I.getOperand(0)); 3907 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3908 I.getType()); 3909 SDNodeFlags Flags; 3910 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3911 Flags.setNonNeg(PNI->hasNonNeg()); 3912 3913 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags)); 3914 } 3915 3916 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3917 // SIToFP is never a no-op cast, no need to check 3918 SDValue N = getValue(I.getOperand(0)); 3919 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3920 I.getType()); 3921 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3922 } 3923 3924 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3925 // What to do depends on the size of the integer and the size of the pointer. 3926 // We can either truncate, zero extend, or no-op, accordingly. 3927 SDValue N = getValue(I.getOperand(0)); 3928 auto &TLI = DAG.getTargetLoweringInfo(); 3929 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3930 I.getType()); 3931 EVT PtrMemVT = 3932 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3933 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3934 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3935 setValue(&I, N); 3936 } 3937 3938 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3939 // What to do depends on the size of the integer and the size of the pointer. 3940 // We can either truncate, zero extend, or no-op, accordingly. 3941 SDValue N = getValue(I.getOperand(0)); 3942 auto &TLI = DAG.getTargetLoweringInfo(); 3943 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3944 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3945 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3946 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3947 setValue(&I, N); 3948 } 3949 3950 void SelectionDAGBuilder::visitBitCast(const User &I) { 3951 SDValue N = getValue(I.getOperand(0)); 3952 SDLoc dl = getCurSDLoc(); 3953 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3954 I.getType()); 3955 3956 // BitCast assures us that source and destination are the same size so this is 3957 // either a BITCAST or a no-op. 3958 if (DestVT != N.getValueType()) 3959 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3960 DestVT, N)); // convert types. 3961 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3962 // might fold any kind of constant expression to an integer constant and that 3963 // is not what we are looking for. Only recognize a bitcast of a genuine 3964 // constant integer as an opaque constant. 3965 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3966 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3967 /*isOpaque*/true)); 3968 else 3969 setValue(&I, N); // noop cast. 3970 } 3971 3972 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3973 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3974 const Value *SV = I.getOperand(0); 3975 SDValue N = getValue(SV); 3976 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3977 3978 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3979 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3980 3981 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3982 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3983 3984 setValue(&I, N); 3985 } 3986 3987 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3988 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3989 SDValue InVec = getValue(I.getOperand(0)); 3990 SDValue InVal = getValue(I.getOperand(1)); 3991 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3992 TLI.getVectorIdxTy(DAG.getDataLayout())); 3993 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3994 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3995 InVec, InVal, InIdx)); 3996 } 3997 3998 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3999 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4000 SDValue InVec = getValue(I.getOperand(0)); 4001 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 4002 TLI.getVectorIdxTy(DAG.getDataLayout())); 4003 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 4004 TLI.getValueType(DAG.getDataLayout(), I.getType()), 4005 InVec, InIdx)); 4006 } 4007 4008 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 4009 SDValue Src1 = getValue(I.getOperand(0)); 4010 SDValue Src2 = getValue(I.getOperand(1)); 4011 ArrayRef<int> Mask; 4012 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 4013 Mask = SVI->getShuffleMask(); 4014 else 4015 Mask = cast<ConstantExpr>(I).getShuffleMask(); 4016 SDLoc DL = getCurSDLoc(); 4017 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4018 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4019 EVT SrcVT = Src1.getValueType(); 4020 4021 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 4022 VT.isScalableVector()) { 4023 // Canonical splat form of first element of first input vector. 4024 SDValue FirstElt = 4025 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 4026 DAG.getVectorIdxConstant(0, DL)); 4027 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 4028 return; 4029 } 4030 4031 // For now, we only handle splats for scalable vectors. 4032 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 4033 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 4034 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 4035 4036 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 4037 unsigned MaskNumElts = Mask.size(); 4038 4039 if (SrcNumElts == MaskNumElts) { 4040 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 4041 return; 4042 } 4043 4044 // Normalize the shuffle vector since mask and vector length don't match. 4045 if (SrcNumElts < MaskNumElts) { 4046 // Mask is longer than the source vectors. We can use concatenate vector to 4047 // make the mask and vectors lengths match. 4048 4049 if (MaskNumElts % SrcNumElts == 0) { 4050 // Mask length is a multiple of the source vector length. 4051 // Check if the shuffle is some kind of concatenation of the input 4052 // vectors. 4053 unsigned NumConcat = MaskNumElts / SrcNumElts; 4054 bool IsConcat = true; 4055 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 4056 for (unsigned i = 0; i != MaskNumElts; ++i) { 4057 int Idx = Mask[i]; 4058 if (Idx < 0) 4059 continue; 4060 // Ensure the indices in each SrcVT sized piece are sequential and that 4061 // the same source is used for the whole piece. 4062 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 4063 (ConcatSrcs[i / SrcNumElts] >= 0 && 4064 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 4065 IsConcat = false; 4066 break; 4067 } 4068 // Remember which source this index came from. 4069 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 4070 } 4071 4072 // The shuffle is concatenating multiple vectors together. Just emit 4073 // a CONCAT_VECTORS operation. 4074 if (IsConcat) { 4075 SmallVector<SDValue, 8> ConcatOps; 4076 for (auto Src : ConcatSrcs) { 4077 if (Src < 0) 4078 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 4079 else if (Src == 0) 4080 ConcatOps.push_back(Src1); 4081 else 4082 ConcatOps.push_back(Src2); 4083 } 4084 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 4085 return; 4086 } 4087 } 4088 4089 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 4090 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 4091 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 4092 PaddedMaskNumElts); 4093 4094 // Pad both vectors with undefs to make them the same length as the mask. 4095 SDValue UndefVal = DAG.getUNDEF(SrcVT); 4096 4097 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 4098 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 4099 MOps1[0] = Src1; 4100 MOps2[0] = Src2; 4101 4102 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 4103 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 4104 4105 // Readjust mask for new input vector length. 4106 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 4107 for (unsigned i = 0; i != MaskNumElts; ++i) { 4108 int Idx = Mask[i]; 4109 if (Idx >= (int)SrcNumElts) 4110 Idx -= SrcNumElts - PaddedMaskNumElts; 4111 MappedOps[i] = Idx; 4112 } 4113 4114 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 4115 4116 // If the concatenated vector was padded, extract a subvector with the 4117 // correct number of elements. 4118 if (MaskNumElts != PaddedMaskNumElts) 4119 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 4120 DAG.getVectorIdxConstant(0, DL)); 4121 4122 setValue(&I, Result); 4123 return; 4124 } 4125 4126 assert(SrcNumElts > MaskNumElts); 4127 4128 // Analyze the access pattern of the vector to see if we can extract 4129 // two subvectors and do the shuffle. 4130 int StartIdx[2] = {-1, -1}; // StartIdx to extract from 4131 bool CanExtract = true; 4132 for (int Idx : Mask) { 4133 unsigned Input = 0; 4134 if (Idx < 0) 4135 continue; 4136 4137 if (Idx >= (int)SrcNumElts) { 4138 Input = 1; 4139 Idx -= SrcNumElts; 4140 } 4141 4142 // If all the indices come from the same MaskNumElts sized portion of 4143 // the sources we can use extract. Also make sure the extract wouldn't 4144 // extract past the end of the source. 4145 int NewStartIdx = alignDown(Idx, MaskNumElts); 4146 if (NewStartIdx + MaskNumElts > SrcNumElts || 4147 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 4148 CanExtract = false; 4149 // Make sure we always update StartIdx as we use it to track if all 4150 // elements are undef. 4151 StartIdx[Input] = NewStartIdx; 4152 } 4153 4154 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 4155 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 4156 return; 4157 } 4158 if (CanExtract) { 4159 // Extract appropriate subvector and generate a vector shuffle 4160 for (unsigned Input = 0; Input < 2; ++Input) { 4161 SDValue &Src = Input == 0 ? Src1 : Src2; 4162 if (StartIdx[Input] < 0) 4163 Src = DAG.getUNDEF(VT); 4164 else { 4165 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 4166 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 4167 } 4168 } 4169 4170 // Calculate new mask. 4171 SmallVector<int, 8> MappedOps(Mask); 4172 for (int &Idx : MappedOps) { 4173 if (Idx >= (int)SrcNumElts) 4174 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 4175 else if (Idx >= 0) 4176 Idx -= StartIdx[0]; 4177 } 4178 4179 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 4180 return; 4181 } 4182 4183 // We can't use either concat vectors or extract subvectors so fall back to 4184 // replacing the shuffle with extract and build vector. 4185 // to insert and build vector. 4186 EVT EltVT = VT.getVectorElementType(); 4187 SmallVector<SDValue,8> Ops; 4188 for (int Idx : Mask) { 4189 SDValue Res; 4190 4191 if (Idx < 0) { 4192 Res = DAG.getUNDEF(EltVT); 4193 } else { 4194 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 4195 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 4196 4197 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4198 DAG.getVectorIdxConstant(Idx, DL)); 4199 } 4200 4201 Ops.push_back(Res); 4202 } 4203 4204 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4205 } 4206 4207 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4208 ArrayRef<unsigned> Indices = I.getIndices(); 4209 const Value *Op0 = I.getOperand(0); 4210 const Value *Op1 = I.getOperand(1); 4211 Type *AggTy = I.getType(); 4212 Type *ValTy = Op1->getType(); 4213 bool IntoUndef = isa<UndefValue>(Op0); 4214 bool FromUndef = isa<UndefValue>(Op1); 4215 4216 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4217 4218 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4219 SmallVector<EVT, 4> AggValueVTs; 4220 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4221 SmallVector<EVT, 4> ValValueVTs; 4222 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4223 4224 unsigned NumAggValues = AggValueVTs.size(); 4225 unsigned NumValValues = ValValueVTs.size(); 4226 SmallVector<SDValue, 4> Values(NumAggValues); 4227 4228 // Ignore an insertvalue that produces an empty object 4229 if (!NumAggValues) { 4230 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4231 return; 4232 } 4233 4234 SDValue Agg = getValue(Op0); 4235 unsigned i = 0; 4236 // Copy the beginning value(s) from the original aggregate. 4237 for (; i != LinearIndex; ++i) 4238 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4239 SDValue(Agg.getNode(), Agg.getResNo() + i); 4240 // Copy values from the inserted value(s). 4241 if (NumValValues) { 4242 SDValue Val = getValue(Op1); 4243 for (; i != LinearIndex + NumValValues; ++i) 4244 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4245 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4246 } 4247 // Copy remaining value(s) from the original aggregate. 4248 for (; i != NumAggValues; ++i) 4249 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4250 SDValue(Agg.getNode(), Agg.getResNo() + i); 4251 4252 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4253 DAG.getVTList(AggValueVTs), Values)); 4254 } 4255 4256 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4257 ArrayRef<unsigned> Indices = I.getIndices(); 4258 const Value *Op0 = I.getOperand(0); 4259 Type *AggTy = Op0->getType(); 4260 Type *ValTy = I.getType(); 4261 bool OutOfUndef = isa<UndefValue>(Op0); 4262 4263 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4264 4265 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4266 SmallVector<EVT, 4> ValValueVTs; 4267 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4268 4269 unsigned NumValValues = ValValueVTs.size(); 4270 4271 // Ignore a extractvalue that produces an empty object 4272 if (!NumValValues) { 4273 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4274 return; 4275 } 4276 4277 SmallVector<SDValue, 4> Values(NumValValues); 4278 4279 SDValue Agg = getValue(Op0); 4280 // Copy out the selected value(s). 4281 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4282 Values[i - LinearIndex] = 4283 OutOfUndef ? 4284 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4285 SDValue(Agg.getNode(), Agg.getResNo() + i); 4286 4287 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4288 DAG.getVTList(ValValueVTs), Values)); 4289 } 4290 4291 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4292 Value *Op0 = I.getOperand(0); 4293 // Note that the pointer operand may be a vector of pointers. Take the scalar 4294 // element which holds a pointer. 4295 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4296 SDValue N = getValue(Op0); 4297 SDLoc dl = getCurSDLoc(); 4298 auto &TLI = DAG.getTargetLoweringInfo(); 4299 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags(); 4300 4301 // Normalize Vector GEP - all scalar operands should be converted to the 4302 // splat vector. 4303 bool IsVectorGEP = I.getType()->isVectorTy(); 4304 ElementCount VectorElementCount = 4305 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4306 : ElementCount::getFixed(0); 4307 4308 if (IsVectorGEP && !N.getValueType().isVector()) { 4309 LLVMContext &Context = *DAG.getContext(); 4310 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4311 N = DAG.getSplat(VT, dl, N); 4312 } 4313 4314 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4315 GTI != E; ++GTI) { 4316 const Value *Idx = GTI.getOperand(); 4317 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4318 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4319 if (Field) { 4320 // N = N + Offset 4321 uint64_t Offset = 4322 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4323 4324 // In an inbounds GEP with an offset that is nonnegative even when 4325 // interpreted as signed, assume there is no unsigned overflow. 4326 SDNodeFlags Flags; 4327 if (NW.hasNoUnsignedWrap() || 4328 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap())) 4329 Flags |= SDNodeFlags::NoUnsignedWrap; 4330 4331 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4332 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4333 } 4334 } else { 4335 // IdxSize is the width of the arithmetic according to IR semantics. 4336 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4337 // (and fix up the result later). 4338 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4339 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4340 TypeSize ElementSize = 4341 GTI.getSequentialElementStride(DAG.getDataLayout()); 4342 // We intentionally mask away the high bits here; ElementSize may not 4343 // fit in IdxTy. 4344 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(), 4345 /*isSigned=*/false, /*implicitTrunc=*/true); 4346 bool ElementScalable = ElementSize.isScalable(); 4347 4348 // If this is a scalar constant or a splat vector of constants, 4349 // handle it quickly. 4350 const auto *C = dyn_cast<Constant>(Idx); 4351 if (C && isa<VectorType>(C->getType())) 4352 C = C->getSplatValue(); 4353 4354 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4355 if (CI && CI->isZero()) 4356 continue; 4357 if (CI && !ElementScalable) { 4358 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4359 LLVMContext &Context = *DAG.getContext(); 4360 SDValue OffsVal; 4361 if (IsVectorGEP) 4362 OffsVal = DAG.getConstant( 4363 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4364 else 4365 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4366 4367 // In an inbounds GEP with an offset that is nonnegative even when 4368 // interpreted as signed, assume there is no unsigned overflow. 4369 SDNodeFlags Flags; 4370 if (NW.hasNoUnsignedWrap() || 4371 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap())) 4372 Flags.setNoUnsignedWrap(true); 4373 4374 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4375 4376 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4377 continue; 4378 } 4379 4380 // N = N + Idx * ElementMul; 4381 SDValue IdxN = getValue(Idx); 4382 4383 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4384 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4385 VectorElementCount); 4386 IdxN = DAG.getSplat(VT, dl, IdxN); 4387 } 4388 4389 // If the index is smaller or larger than intptr_t, truncate or extend 4390 // it. 4391 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4392 4393 SDNodeFlags ScaleFlags; 4394 // The multiplication of an index by the type size does not wrap the 4395 // pointer index type in a signed sense (mul nsw). 4396 ScaleFlags.setNoSignedWrap(NW.hasNoUnsignedSignedWrap()); 4397 4398 // The multiplication of an index by the type size does not wrap the 4399 // pointer index type in an unsigned sense (mul nuw). 4400 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap()); 4401 4402 if (ElementScalable) { 4403 EVT VScaleTy = N.getValueType().getScalarType(); 4404 SDValue VScale = DAG.getNode( 4405 ISD::VSCALE, dl, VScaleTy, 4406 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4407 if (IsVectorGEP) 4408 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4409 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale, 4410 ScaleFlags); 4411 } else { 4412 // If this is a multiply by a power of two, turn it into a shl 4413 // immediately. This is a very common case. 4414 if (ElementMul != 1) { 4415 if (ElementMul.isPowerOf2()) { 4416 unsigned Amt = ElementMul.logBase2(); 4417 IdxN = DAG.getNode(ISD::SHL, dl, N.getValueType(), IdxN, 4418 DAG.getConstant(Amt, dl, IdxN.getValueType()), 4419 ScaleFlags); 4420 } else { 4421 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4422 IdxN.getValueType()); 4423 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale, 4424 ScaleFlags); 4425 } 4426 } 4427 } 4428 4429 // The successive addition of the current address, truncated to the 4430 // pointer index type and interpreted as an unsigned number, and each 4431 // offset, also interpreted as an unsigned number, does not wrap the 4432 // pointer index type (add nuw). 4433 SDNodeFlags AddFlags; 4434 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap()); 4435 4436 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, IdxN, AddFlags); 4437 } 4438 } 4439 4440 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4441 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4442 if (IsVectorGEP) { 4443 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4444 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4445 } 4446 4447 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4448 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4449 4450 setValue(&I, N); 4451 } 4452 4453 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4454 // If this is a fixed sized alloca in the entry block of the function, 4455 // allocate it statically on the stack. 4456 if (FuncInfo.StaticAllocaMap.count(&I)) 4457 return; // getValue will auto-populate this. 4458 4459 SDLoc dl = getCurSDLoc(); 4460 Type *Ty = I.getAllocatedType(); 4461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4462 auto &DL = DAG.getDataLayout(); 4463 TypeSize TySize = DL.getTypeAllocSize(Ty); 4464 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4465 4466 SDValue AllocSize = getValue(I.getArraySize()); 4467 4468 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4469 if (AllocSize.getValueType() != IntPtr) 4470 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4471 4472 if (TySize.isScalable()) 4473 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4474 DAG.getVScale(dl, IntPtr, 4475 APInt(IntPtr.getScalarSizeInBits(), 4476 TySize.getKnownMinValue()))); 4477 else { 4478 SDValue TySizeValue = 4479 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4480 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4481 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4482 } 4483 4484 // Handle alignment. If the requested alignment is less than or equal to 4485 // the stack alignment, ignore it. If the size is greater than or equal to 4486 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4487 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4488 if (*Alignment <= StackAlign) 4489 Alignment = std::nullopt; 4490 4491 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4492 // Round the size of the allocation up to the stack alignment size 4493 // by add SA-1 to the size. This doesn't overflow because we're computing 4494 // an address inside an alloca. 4495 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4496 DAG.getConstant(StackAlignMask, dl, IntPtr), 4497 SDNodeFlags::NoUnsignedWrap); 4498 4499 // Mask out the low bits for alignment purposes. 4500 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4501 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr)); 4502 4503 SDValue Ops[] = { 4504 getRoot(), AllocSize, 4505 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4506 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4507 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4508 setValue(&I, DSA); 4509 DAG.setRoot(DSA.getValue(1)); 4510 4511 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4512 } 4513 4514 static const MDNode *getRangeMetadata(const Instruction &I) { 4515 // If !noundef is not present, then !range violation results in a poison 4516 // value rather than immediate undefined behavior. In theory, transferring 4517 // these annotations to SDAG is fine, but in practice there are key SDAG 4518 // transforms that are known not to be poison-safe, such as folding logical 4519 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4520 // also present. 4521 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4522 return nullptr; 4523 return I.getMetadata(LLVMContext::MD_range); 4524 } 4525 4526 static std::optional<ConstantRange> getRange(const Instruction &I) { 4527 if (const auto *CB = dyn_cast<CallBase>(&I)) { 4528 // see comment in getRangeMetadata about this check 4529 if (CB->hasRetAttr(Attribute::NoUndef)) 4530 return CB->getRange(); 4531 } 4532 if (const MDNode *Range = getRangeMetadata(I)) 4533 return getConstantRangeFromMetadata(*Range); 4534 return std::nullopt; 4535 } 4536 4537 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4538 if (I.isAtomic()) 4539 return visitAtomicLoad(I); 4540 4541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4542 const Value *SV = I.getOperand(0); 4543 if (TLI.supportSwiftError()) { 4544 // Swifterror values can come from either a function parameter with 4545 // swifterror attribute or an alloca with swifterror attribute. 4546 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4547 if (Arg->hasSwiftErrorAttr()) 4548 return visitLoadFromSwiftError(I); 4549 } 4550 4551 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4552 if (Alloca->isSwiftError()) 4553 return visitLoadFromSwiftError(I); 4554 } 4555 } 4556 4557 SDValue Ptr = getValue(SV); 4558 4559 Type *Ty = I.getType(); 4560 SmallVector<EVT, 4> ValueVTs, MemVTs; 4561 SmallVector<TypeSize, 4> Offsets; 4562 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4563 unsigned NumValues = ValueVTs.size(); 4564 if (NumValues == 0) 4565 return; 4566 4567 Align Alignment = I.getAlign(); 4568 AAMDNodes AAInfo = I.getAAMetadata(); 4569 const MDNode *Ranges = getRangeMetadata(I); 4570 bool isVolatile = I.isVolatile(); 4571 MachineMemOperand::Flags MMOFlags = 4572 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4573 4574 SDValue Root; 4575 bool ConstantMemory = false; 4576 if (isVolatile) 4577 // Serialize volatile loads with other side effects. 4578 Root = getRoot(); 4579 else if (NumValues > MaxParallelChains) 4580 Root = getMemoryRoot(); 4581 else if (AA && 4582 AA->pointsToConstantMemory(MemoryLocation( 4583 SV, 4584 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4585 AAInfo))) { 4586 // Do not serialize (non-volatile) loads of constant memory with anything. 4587 Root = DAG.getEntryNode(); 4588 ConstantMemory = true; 4589 MMOFlags |= MachineMemOperand::MOInvariant; 4590 } else { 4591 // Do not serialize non-volatile loads against each other. 4592 Root = DAG.getRoot(); 4593 } 4594 4595 SDLoc dl = getCurSDLoc(); 4596 4597 if (isVolatile) 4598 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4599 4600 SmallVector<SDValue, 4> Values(NumValues); 4601 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4602 4603 unsigned ChainI = 0; 4604 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4605 // Serializing loads here may result in excessive register pressure, and 4606 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4607 // could recover a bit by hoisting nodes upward in the chain by recognizing 4608 // they are side-effect free or do not alias. The optimizer should really 4609 // avoid this case by converting large object/array copies to llvm.memcpy 4610 // (MaxParallelChains should always remain as failsafe). 4611 if (ChainI == MaxParallelChains) { 4612 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4613 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4614 ArrayRef(Chains.data(), ChainI)); 4615 Root = Chain; 4616 ChainI = 0; 4617 } 4618 4619 // TODO: MachinePointerInfo only supports a fixed length offset. 4620 MachinePointerInfo PtrInfo = 4621 !Offsets[i].isScalable() || Offsets[i].isZero() 4622 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4623 : MachinePointerInfo(); 4624 4625 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4626 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4627 MMOFlags, AAInfo, Ranges); 4628 Chains[ChainI] = L.getValue(1); 4629 4630 if (MemVTs[i] != ValueVTs[i]) 4631 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4632 4633 Values[i] = L; 4634 } 4635 4636 if (!ConstantMemory) { 4637 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4638 ArrayRef(Chains.data(), ChainI)); 4639 if (isVolatile) 4640 DAG.setRoot(Chain); 4641 else 4642 PendingLoads.push_back(Chain); 4643 } 4644 4645 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4646 DAG.getVTList(ValueVTs), Values)); 4647 } 4648 4649 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4650 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4651 "call visitStoreToSwiftError when backend supports swifterror"); 4652 4653 SmallVector<EVT, 4> ValueVTs; 4654 SmallVector<uint64_t, 4> Offsets; 4655 const Value *SrcV = I.getOperand(0); 4656 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4657 SrcV->getType(), ValueVTs, &Offsets, 0); 4658 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4659 "expect a single EVT for swifterror"); 4660 4661 SDValue Src = getValue(SrcV); 4662 // Create a virtual register, then update the virtual register. 4663 Register VReg = 4664 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4665 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4666 // Chain can be getRoot or getControlRoot. 4667 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4668 SDValue(Src.getNode(), Src.getResNo())); 4669 DAG.setRoot(CopyNode); 4670 } 4671 4672 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4673 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4674 "call visitLoadFromSwiftError when backend supports swifterror"); 4675 4676 assert(!I.isVolatile() && 4677 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4678 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4679 "Support volatile, non temporal, invariant for load_from_swift_error"); 4680 4681 const Value *SV = I.getOperand(0); 4682 Type *Ty = I.getType(); 4683 assert( 4684 (!AA || 4685 !AA->pointsToConstantMemory(MemoryLocation( 4686 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4687 I.getAAMetadata()))) && 4688 "load_from_swift_error should not be constant memory"); 4689 4690 SmallVector<EVT, 4> ValueVTs; 4691 SmallVector<uint64_t, 4> Offsets; 4692 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4693 ValueVTs, &Offsets, 0); 4694 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4695 "expect a single EVT for swifterror"); 4696 4697 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4698 SDValue L = DAG.getCopyFromReg( 4699 getRoot(), getCurSDLoc(), 4700 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4701 4702 setValue(&I, L); 4703 } 4704 4705 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4706 if (I.isAtomic()) 4707 return visitAtomicStore(I); 4708 4709 const Value *SrcV = I.getOperand(0); 4710 const Value *PtrV = I.getOperand(1); 4711 4712 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4713 if (TLI.supportSwiftError()) { 4714 // Swifterror values can come from either a function parameter with 4715 // swifterror attribute or an alloca with swifterror attribute. 4716 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4717 if (Arg->hasSwiftErrorAttr()) 4718 return visitStoreToSwiftError(I); 4719 } 4720 4721 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4722 if (Alloca->isSwiftError()) 4723 return visitStoreToSwiftError(I); 4724 } 4725 } 4726 4727 SmallVector<EVT, 4> ValueVTs, MemVTs; 4728 SmallVector<TypeSize, 4> Offsets; 4729 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4730 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4731 unsigned NumValues = ValueVTs.size(); 4732 if (NumValues == 0) 4733 return; 4734 4735 // Get the lowered operands. Note that we do this after 4736 // checking if NumResults is zero, because with zero results 4737 // the operands won't have values in the map. 4738 SDValue Src = getValue(SrcV); 4739 SDValue Ptr = getValue(PtrV); 4740 4741 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4742 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4743 SDLoc dl = getCurSDLoc(); 4744 Align Alignment = I.getAlign(); 4745 AAMDNodes AAInfo = I.getAAMetadata(); 4746 4747 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4748 4749 unsigned ChainI = 0; 4750 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4751 // See visitLoad comments. 4752 if (ChainI == MaxParallelChains) { 4753 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4754 ArrayRef(Chains.data(), ChainI)); 4755 Root = Chain; 4756 ChainI = 0; 4757 } 4758 4759 // TODO: MachinePointerInfo only supports a fixed length offset. 4760 MachinePointerInfo PtrInfo = 4761 !Offsets[i].isScalable() || Offsets[i].isZero() 4762 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4763 : MachinePointerInfo(); 4764 4765 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4766 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4767 if (MemVTs[i] != ValueVTs[i]) 4768 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4769 SDValue St = 4770 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4771 Chains[ChainI] = St; 4772 } 4773 4774 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4775 ArrayRef(Chains.data(), ChainI)); 4776 setValue(&I, StoreNode); 4777 DAG.setRoot(StoreNode); 4778 } 4779 4780 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4781 bool IsCompressing) { 4782 SDLoc sdl = getCurSDLoc(); 4783 4784 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4785 Align &Alignment) { 4786 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4787 Src0 = I.getArgOperand(0); 4788 Ptr = I.getArgOperand(1); 4789 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue(); 4790 Mask = I.getArgOperand(3); 4791 }; 4792 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4793 Align &Alignment) { 4794 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4795 Src0 = I.getArgOperand(0); 4796 Ptr = I.getArgOperand(1); 4797 Mask = I.getArgOperand(2); 4798 Alignment = I.getParamAlign(1).valueOrOne(); 4799 }; 4800 4801 Value *PtrOperand, *MaskOperand, *Src0Operand; 4802 Align Alignment; 4803 if (IsCompressing) 4804 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4805 else 4806 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4807 4808 SDValue Ptr = getValue(PtrOperand); 4809 SDValue Src0 = getValue(Src0Operand); 4810 SDValue Mask = getValue(MaskOperand); 4811 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4812 4813 EVT VT = Src0.getValueType(); 4814 4815 auto MMOFlags = MachineMemOperand::MOStore; 4816 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4817 MMOFlags |= MachineMemOperand::MONonTemporal; 4818 4819 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4820 MachinePointerInfo(PtrOperand), MMOFlags, 4821 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4822 4823 const auto &TLI = DAG.getTargetLoweringInfo(); 4824 const auto &TTI = 4825 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 4826 SDValue StoreNode = 4827 !IsCompressing && 4828 TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType()) 4829 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0, 4830 Mask) 4831 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, 4832 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false, 4833 IsCompressing); 4834 DAG.setRoot(StoreNode); 4835 setValue(&I, StoreNode); 4836 } 4837 4838 // Get a uniform base for the Gather/Scatter intrinsic. 4839 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4840 // We try to represent it as a base pointer + vector of indices. 4841 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4842 // The first operand of the GEP may be a single pointer or a vector of pointers 4843 // Example: 4844 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4845 // or 4846 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4847 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4848 // 4849 // When the first GEP operand is a single pointer - it is the uniform base we 4850 // are looking for. If first operand of the GEP is a splat vector - we 4851 // extract the splat value and use it as a uniform base. 4852 // In all other cases the function returns 'false'. 4853 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4854 ISD::MemIndexType &IndexType, SDValue &Scale, 4855 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4856 uint64_t ElemSize) { 4857 SelectionDAG& DAG = SDB->DAG; 4858 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4859 const DataLayout &DL = DAG.getDataLayout(); 4860 4861 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4862 4863 // Handle splat constant pointer. 4864 if (auto *C = dyn_cast<Constant>(Ptr)) { 4865 C = C->getSplatValue(); 4866 if (!C) 4867 return false; 4868 4869 Base = SDB->getValue(C); 4870 4871 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4872 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4873 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4874 IndexType = ISD::SIGNED_SCALED; 4875 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4876 return true; 4877 } 4878 4879 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4880 if (!GEP || GEP->getParent() != CurBB) 4881 return false; 4882 4883 if (GEP->getNumOperands() != 2) 4884 return false; 4885 4886 const Value *BasePtr = GEP->getPointerOperand(); 4887 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4888 4889 // Make sure the base is scalar and the index is a vector. 4890 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4891 return false; 4892 4893 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4894 if (ScaleVal.isScalable()) 4895 return false; 4896 4897 // Target may not support the required addressing mode. 4898 if (ScaleVal != 1 && 4899 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4900 return false; 4901 4902 Base = SDB->getValue(BasePtr); 4903 Index = SDB->getValue(IndexVal); 4904 IndexType = ISD::SIGNED_SCALED; 4905 4906 Scale = 4907 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4908 return true; 4909 } 4910 4911 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4912 SDLoc sdl = getCurSDLoc(); 4913 4914 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4915 const Value *Ptr = I.getArgOperand(1); 4916 SDValue Src0 = getValue(I.getArgOperand(0)); 4917 SDValue Mask = getValue(I.getArgOperand(3)); 4918 EVT VT = Src0.getValueType(); 4919 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4920 ->getMaybeAlignValue() 4921 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4922 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4923 4924 SDValue Base; 4925 SDValue Index; 4926 ISD::MemIndexType IndexType; 4927 SDValue Scale; 4928 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4929 I.getParent(), VT.getScalarStoreSize()); 4930 4931 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4932 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4933 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4934 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4935 if (!UniformBase) { 4936 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4937 Index = getValue(Ptr); 4938 IndexType = ISD::SIGNED_SCALED; 4939 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4940 } 4941 4942 EVT IdxVT = Index.getValueType(); 4943 EVT EltTy = IdxVT.getVectorElementType(); 4944 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4945 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4946 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4947 } 4948 4949 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4950 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4951 Ops, MMO, IndexType, false); 4952 DAG.setRoot(Scatter); 4953 setValue(&I, Scatter); 4954 } 4955 4956 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4957 SDLoc sdl = getCurSDLoc(); 4958 4959 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4960 Align &Alignment) { 4961 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4962 Ptr = I.getArgOperand(0); 4963 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue(); 4964 Mask = I.getArgOperand(2); 4965 Src0 = I.getArgOperand(3); 4966 }; 4967 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4968 Align &Alignment) { 4969 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4970 Ptr = I.getArgOperand(0); 4971 Alignment = I.getParamAlign(0).valueOrOne(); 4972 Mask = I.getArgOperand(1); 4973 Src0 = I.getArgOperand(2); 4974 }; 4975 4976 Value *PtrOperand, *MaskOperand, *Src0Operand; 4977 Align Alignment; 4978 if (IsExpanding) 4979 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4980 else 4981 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4982 4983 SDValue Ptr = getValue(PtrOperand); 4984 SDValue Src0 = getValue(Src0Operand); 4985 SDValue Mask = getValue(MaskOperand); 4986 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4987 4988 EVT VT = Src0.getValueType(); 4989 AAMDNodes AAInfo = I.getAAMetadata(); 4990 const MDNode *Ranges = getRangeMetadata(I); 4991 4992 // Do not serialize masked loads of constant memory with anything. 4993 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4994 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4995 4996 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4997 4998 auto MMOFlags = MachineMemOperand::MOLoad; 4999 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 5000 MMOFlags |= MachineMemOperand::MONonTemporal; 5001 5002 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5003 MachinePointerInfo(PtrOperand), MMOFlags, 5004 LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges); 5005 5006 const auto &TLI = DAG.getTargetLoweringInfo(); 5007 const auto &TTI = 5008 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 5009 // The Load/Res may point to different values and both of them are output 5010 // variables. 5011 SDValue Load; 5012 SDValue Res; 5013 if (!IsExpanding && 5014 TTI.hasConditionalLoadStoreForType(Src0Operand->getType())) 5015 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask); 5016 else 5017 Res = Load = 5018 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 5019 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 5020 if (AddToChain) 5021 PendingLoads.push_back(Load.getValue(1)); 5022 setValue(&I, Res); 5023 } 5024 5025 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 5026 SDLoc sdl = getCurSDLoc(); 5027 5028 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 5029 const Value *Ptr = I.getArgOperand(0); 5030 SDValue Src0 = getValue(I.getArgOperand(3)); 5031 SDValue Mask = getValue(I.getArgOperand(2)); 5032 5033 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5034 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5035 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 5036 ->getMaybeAlignValue() 5037 .value_or(DAG.getEVTAlign(VT.getScalarType())); 5038 5039 const MDNode *Ranges = getRangeMetadata(I); 5040 5041 SDValue Root = DAG.getRoot(); 5042 SDValue Base; 5043 SDValue Index; 5044 ISD::MemIndexType IndexType; 5045 SDValue Scale; 5046 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 5047 I.getParent(), VT.getScalarStoreSize()); 5048 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 5049 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5050 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 5051 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(), 5052 Ranges); 5053 5054 if (!UniformBase) { 5055 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 5056 Index = getValue(Ptr); 5057 IndexType = ISD::SIGNED_SCALED; 5058 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 5059 } 5060 5061 EVT IdxVT = Index.getValueType(); 5062 EVT EltTy = IdxVT.getVectorElementType(); 5063 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 5064 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 5065 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 5066 } 5067 5068 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 5069 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 5070 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 5071 5072 PendingLoads.push_back(Gather.getValue(1)); 5073 setValue(&I, Gather); 5074 } 5075 5076 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 5077 SDLoc dl = getCurSDLoc(); 5078 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 5079 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 5080 SyncScope::ID SSID = I.getSyncScopeID(); 5081 5082 SDValue InChain = getRoot(); 5083 5084 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 5085 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 5086 5087 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5088 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5089 5090 MachineFunction &MF = DAG.getMachineFunction(); 5091 MachineMemOperand *MMO = MF.getMachineMemOperand( 5092 MachinePointerInfo(I.getPointerOperand()), Flags, 5093 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5094 AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering); 5095 5096 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 5097 dl, MemVT, VTs, InChain, 5098 getValue(I.getPointerOperand()), 5099 getValue(I.getCompareOperand()), 5100 getValue(I.getNewValOperand()), MMO); 5101 5102 SDValue OutChain = L.getValue(2); 5103 5104 setValue(&I, L); 5105 DAG.setRoot(OutChain); 5106 } 5107 5108 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 5109 SDLoc dl = getCurSDLoc(); 5110 ISD::NodeType NT; 5111 switch (I.getOperation()) { 5112 default: llvm_unreachable("Unknown atomicrmw operation"); 5113 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 5114 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 5115 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 5116 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 5117 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 5118 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 5119 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 5120 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 5121 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 5122 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 5123 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 5124 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 5125 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 5126 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 5127 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 5128 case AtomicRMWInst::UIncWrap: 5129 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 5130 break; 5131 case AtomicRMWInst::UDecWrap: 5132 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 5133 break; 5134 case AtomicRMWInst::USubCond: 5135 NT = ISD::ATOMIC_LOAD_USUB_COND; 5136 break; 5137 case AtomicRMWInst::USubSat: 5138 NT = ISD::ATOMIC_LOAD_USUB_SAT; 5139 break; 5140 } 5141 AtomicOrdering Ordering = I.getOrdering(); 5142 SyncScope::ID SSID = I.getSyncScopeID(); 5143 5144 SDValue InChain = getRoot(); 5145 5146 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 5147 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5148 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5149 5150 MachineFunction &MF = DAG.getMachineFunction(); 5151 MachineMemOperand *MMO = MF.getMachineMemOperand( 5152 MachinePointerInfo(I.getPointerOperand()), Flags, 5153 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5154 AAMDNodes(), nullptr, SSID, Ordering); 5155 5156 SDValue L = 5157 DAG.getAtomic(NT, dl, MemVT, InChain, 5158 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 5159 MMO); 5160 5161 SDValue OutChain = L.getValue(1); 5162 5163 setValue(&I, L); 5164 DAG.setRoot(OutChain); 5165 } 5166 5167 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 5168 SDLoc dl = getCurSDLoc(); 5169 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5170 SDValue Ops[3]; 5171 Ops[0] = getRoot(); 5172 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 5173 TLI.getFenceOperandTy(DAG.getDataLayout())); 5174 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 5175 TLI.getFenceOperandTy(DAG.getDataLayout())); 5176 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 5177 setValue(&I, N); 5178 DAG.setRoot(N); 5179 } 5180 5181 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 5182 SDLoc dl = getCurSDLoc(); 5183 AtomicOrdering Order = I.getOrdering(); 5184 SyncScope::ID SSID = I.getSyncScopeID(); 5185 5186 SDValue InChain = getRoot(); 5187 5188 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5189 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5190 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 5191 5192 if (!TLI.supportsUnalignedAtomics() && 5193 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5194 report_fatal_error("Cannot generate unaligned atomic load"); 5195 5196 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 5197 5198 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5199 MachinePointerInfo(I.getPointerOperand()), Flags, 5200 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5201 nullptr, SSID, Order); 5202 5203 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 5204 5205 SDValue Ptr = getValue(I.getPointerOperand()); 5206 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 5207 Ptr, MMO); 5208 5209 SDValue OutChain = L.getValue(1); 5210 if (MemVT != VT) 5211 L = DAG.getPtrExtOrTrunc(L, dl, VT); 5212 5213 setValue(&I, L); 5214 DAG.setRoot(OutChain); 5215 } 5216 5217 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 5218 SDLoc dl = getCurSDLoc(); 5219 5220 AtomicOrdering Ordering = I.getOrdering(); 5221 SyncScope::ID SSID = I.getSyncScopeID(); 5222 5223 SDValue InChain = getRoot(); 5224 5225 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5226 EVT MemVT = 5227 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 5228 5229 if (!TLI.supportsUnalignedAtomics() && 5230 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5231 report_fatal_error("Cannot generate unaligned atomic store"); 5232 5233 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 5234 5235 MachineFunction &MF = DAG.getMachineFunction(); 5236 MachineMemOperand *MMO = MF.getMachineMemOperand( 5237 MachinePointerInfo(I.getPointerOperand()), Flags, 5238 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5239 nullptr, SSID, Ordering); 5240 5241 SDValue Val = getValue(I.getValueOperand()); 5242 if (Val.getValueType() != MemVT) 5243 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 5244 SDValue Ptr = getValue(I.getPointerOperand()); 5245 5246 SDValue OutChain = 5247 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 5248 5249 setValue(&I, OutChain); 5250 DAG.setRoot(OutChain); 5251 } 5252 5253 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 5254 /// node. 5255 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5256 unsigned Intrinsic) { 5257 // Ignore the callsite's attributes. A specific call site may be marked with 5258 // readnone, but the lowering code will expect the chain based on the 5259 // definition. 5260 const Function *F = I.getCalledFunction(); 5261 bool HasChain = !F->doesNotAccessMemory(); 5262 bool OnlyLoad = 5263 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow(); 5264 5265 // Build the operand list. 5266 SmallVector<SDValue, 8> Ops; 5267 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5268 if (OnlyLoad) { 5269 // We don't need to serialize loads against other loads. 5270 Ops.push_back(DAG.getRoot()); 5271 } else { 5272 Ops.push_back(getRoot()); 5273 } 5274 } 5275 5276 // Info is set by getTgtMemIntrinsic 5277 TargetLowering::IntrinsicInfo Info; 5278 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5279 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5280 DAG.getMachineFunction(), 5281 Intrinsic); 5282 5283 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5284 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5285 Info.opc == ISD::INTRINSIC_W_CHAIN) 5286 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5287 TLI.getPointerTy(DAG.getDataLayout()))); 5288 5289 // Add all operands of the call to the operand list. 5290 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5291 const Value *Arg = I.getArgOperand(i); 5292 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5293 Ops.push_back(getValue(Arg)); 5294 continue; 5295 } 5296 5297 // Use TargetConstant instead of a regular constant for immarg. 5298 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5299 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5300 assert(CI->getBitWidth() <= 64 && 5301 "large intrinsic immediates not handled"); 5302 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5303 } else { 5304 Ops.push_back( 5305 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5306 } 5307 } 5308 5309 SmallVector<EVT, 4> ValueVTs; 5310 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5311 5312 if (HasChain) 5313 ValueVTs.push_back(MVT::Other); 5314 5315 SDVTList VTs = DAG.getVTList(ValueVTs); 5316 5317 // Propagate fast-math-flags from IR to node(s). 5318 SDNodeFlags Flags; 5319 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5320 Flags.copyFMF(*FPMO); 5321 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5322 5323 // Create the node. 5324 SDValue Result; 5325 5326 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) { 5327 auto *Token = Bundle->Inputs[0].get(); 5328 SDValue ConvControlToken = getValue(Token); 5329 assert(Ops.back().getValueType() != MVT::Glue && 5330 "Did not expected another glue node here."); 5331 ConvControlToken = 5332 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken); 5333 Ops.push_back(ConvControlToken); 5334 } 5335 5336 // In some cases, custom collection of operands from CallInst I may be needed. 5337 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5338 if (IsTgtIntrinsic) { 5339 // This is target intrinsic that touches memory 5340 // 5341 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5342 // didn't yield anything useful. 5343 MachinePointerInfo MPI; 5344 if (Info.ptrVal) 5345 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5346 else if (Info.fallbackAddressSpace) 5347 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5348 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5349 Info.memVT, MPI, Info.align, Info.flags, 5350 Info.size, I.getAAMetadata()); 5351 } else if (!HasChain) { 5352 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5353 } else if (!I.getType()->isVoidTy()) { 5354 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5355 } else { 5356 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5357 } 5358 5359 if (HasChain) { 5360 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5361 if (OnlyLoad) 5362 PendingLoads.push_back(Chain); 5363 else 5364 DAG.setRoot(Chain); 5365 } 5366 5367 if (!I.getType()->isVoidTy()) { 5368 if (!isa<VectorType>(I.getType())) 5369 Result = lowerRangeToAssertZExt(DAG, I, Result); 5370 5371 MaybeAlign Alignment = I.getRetAlign(); 5372 5373 // Insert `assertalign` node if there's an alignment. 5374 if (InsertAssertAlign && Alignment) { 5375 Result = 5376 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5377 } 5378 } 5379 5380 setValue(&I, Result); 5381 } 5382 5383 /// GetSignificand - Get the significand and build it into a floating-point 5384 /// number with exponent of 1: 5385 /// 5386 /// Op = (Op & 0x007fffff) | 0x3f800000; 5387 /// 5388 /// where Op is the hexadecimal representation of floating point value. 5389 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5390 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5391 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5392 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5393 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5394 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5395 } 5396 5397 /// GetExponent - Get the exponent: 5398 /// 5399 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5400 /// 5401 /// where Op is the hexadecimal representation of floating point value. 5402 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5403 const TargetLowering &TLI, const SDLoc &dl) { 5404 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5405 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5406 SDValue t1 = DAG.getNode( 5407 ISD::SRL, dl, MVT::i32, t0, 5408 DAG.getConstant(23, dl, 5409 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5410 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5411 DAG.getConstant(127, dl, MVT::i32)); 5412 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5413 } 5414 5415 /// getF32Constant - Get 32-bit floating point constant. 5416 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5417 const SDLoc &dl) { 5418 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5419 MVT::f32); 5420 } 5421 5422 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5423 SelectionDAG &DAG) { 5424 // TODO: What fast-math-flags should be set on the floating-point nodes? 5425 5426 // IntegerPartOfX = ((int32_t)(t0); 5427 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5428 5429 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5430 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5431 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5432 5433 // IntegerPartOfX <<= 23; 5434 IntegerPartOfX = 5435 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5436 DAG.getConstant(23, dl, 5437 DAG.getTargetLoweringInfo().getShiftAmountTy( 5438 MVT::i32, DAG.getDataLayout()))); 5439 5440 SDValue TwoToFractionalPartOfX; 5441 if (LimitFloatPrecision <= 6) { 5442 // For floating-point precision of 6: 5443 // 5444 // TwoToFractionalPartOfX = 5445 // 0.997535578f + 5446 // (0.735607626f + 0.252464424f * x) * x; 5447 // 5448 // error 0.0144103317, which is 6 bits 5449 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5450 getF32Constant(DAG, 0x3e814304, dl)); 5451 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5452 getF32Constant(DAG, 0x3f3c50c8, dl)); 5453 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5454 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5455 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5456 } else if (LimitFloatPrecision <= 12) { 5457 // For floating-point precision of 12: 5458 // 5459 // TwoToFractionalPartOfX = 5460 // 0.999892986f + 5461 // (0.696457318f + 5462 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5463 // 5464 // error 0.000107046256, which is 13 to 14 bits 5465 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5466 getF32Constant(DAG, 0x3da235e3, dl)); 5467 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5468 getF32Constant(DAG, 0x3e65b8f3, dl)); 5469 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5470 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5471 getF32Constant(DAG, 0x3f324b07, dl)); 5472 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5473 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5474 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5475 } else { // LimitFloatPrecision <= 18 5476 // For floating-point precision of 18: 5477 // 5478 // TwoToFractionalPartOfX = 5479 // 0.999999982f + 5480 // (0.693148872f + 5481 // (0.240227044f + 5482 // (0.554906021e-1f + 5483 // (0.961591928e-2f + 5484 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5485 // error 2.47208000*10^(-7), which is better than 18 bits 5486 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5487 getF32Constant(DAG, 0x3924b03e, dl)); 5488 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5489 getF32Constant(DAG, 0x3ab24b87, dl)); 5490 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5491 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5492 getF32Constant(DAG, 0x3c1d8c17, dl)); 5493 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5494 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5495 getF32Constant(DAG, 0x3d634a1d, dl)); 5496 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5497 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5498 getF32Constant(DAG, 0x3e75fe14, dl)); 5499 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5500 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5501 getF32Constant(DAG, 0x3f317234, dl)); 5502 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5503 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5504 getF32Constant(DAG, 0x3f800000, dl)); 5505 } 5506 5507 // Add the exponent into the result in integer domain. 5508 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5509 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5510 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5511 } 5512 5513 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5514 /// limited-precision mode. 5515 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5516 const TargetLowering &TLI, SDNodeFlags Flags) { 5517 if (Op.getValueType() == MVT::f32 && 5518 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5519 5520 // Put the exponent in the right bit position for later addition to the 5521 // final result: 5522 // 5523 // t0 = Op * log2(e) 5524 5525 // TODO: What fast-math-flags should be set here? 5526 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5527 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5528 return getLimitedPrecisionExp2(t0, dl, DAG); 5529 } 5530 5531 // No special expansion. 5532 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5533 } 5534 5535 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5536 /// limited-precision mode. 5537 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5538 const TargetLowering &TLI, SDNodeFlags Flags) { 5539 // TODO: What fast-math-flags should be set on the floating-point nodes? 5540 5541 if (Op.getValueType() == MVT::f32 && 5542 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5543 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5544 5545 // Scale the exponent by log(2). 5546 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5547 SDValue LogOfExponent = 5548 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5549 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5550 5551 // Get the significand and build it into a floating-point number with 5552 // exponent of 1. 5553 SDValue X = GetSignificand(DAG, Op1, dl); 5554 5555 SDValue LogOfMantissa; 5556 if (LimitFloatPrecision <= 6) { 5557 // For floating-point precision of 6: 5558 // 5559 // LogofMantissa = 5560 // -1.1609546f + 5561 // (1.4034025f - 0.23903021f * x) * x; 5562 // 5563 // error 0.0034276066, which is better than 8 bits 5564 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5565 getF32Constant(DAG, 0xbe74c456, dl)); 5566 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5567 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5568 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5569 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5570 getF32Constant(DAG, 0x3f949a29, dl)); 5571 } else if (LimitFloatPrecision <= 12) { 5572 // For floating-point precision of 12: 5573 // 5574 // LogOfMantissa = 5575 // -1.7417939f + 5576 // (2.8212026f + 5577 // (-1.4699568f + 5578 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5579 // 5580 // error 0.000061011436, which is 14 bits 5581 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5582 getF32Constant(DAG, 0xbd67b6d6, dl)); 5583 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5584 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5585 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5586 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5587 getF32Constant(DAG, 0x3fbc278b, dl)); 5588 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5589 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5590 getF32Constant(DAG, 0x40348e95, dl)); 5591 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5592 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5593 getF32Constant(DAG, 0x3fdef31a, dl)); 5594 } else { // LimitFloatPrecision <= 18 5595 // For floating-point precision of 18: 5596 // 5597 // LogOfMantissa = 5598 // -2.1072184f + 5599 // (4.2372794f + 5600 // (-3.7029485f + 5601 // (2.2781945f + 5602 // (-0.87823314f + 5603 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5604 // 5605 // error 0.0000023660568, which is better than 18 bits 5606 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5607 getF32Constant(DAG, 0xbc91e5ac, dl)); 5608 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5609 getF32Constant(DAG, 0x3e4350aa, dl)); 5610 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5611 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5612 getF32Constant(DAG, 0x3f60d3e3, dl)); 5613 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5614 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5615 getF32Constant(DAG, 0x4011cdf0, dl)); 5616 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5617 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5618 getF32Constant(DAG, 0x406cfd1c, dl)); 5619 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5620 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5621 getF32Constant(DAG, 0x408797cb, dl)); 5622 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5623 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5624 getF32Constant(DAG, 0x4006dcab, dl)); 5625 } 5626 5627 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5628 } 5629 5630 // No special expansion. 5631 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5632 } 5633 5634 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5635 /// limited-precision mode. 5636 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5637 const TargetLowering &TLI, SDNodeFlags Flags) { 5638 // TODO: What fast-math-flags should be set on the floating-point nodes? 5639 5640 if (Op.getValueType() == MVT::f32 && 5641 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5642 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5643 5644 // Get the exponent. 5645 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5646 5647 // Get the significand and build it into a floating-point number with 5648 // exponent of 1. 5649 SDValue X = GetSignificand(DAG, Op1, dl); 5650 5651 // Different possible minimax approximations of significand in 5652 // floating-point for various degrees of accuracy over [1,2]. 5653 SDValue Log2ofMantissa; 5654 if (LimitFloatPrecision <= 6) { 5655 // For floating-point precision of 6: 5656 // 5657 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5658 // 5659 // error 0.0049451742, which is more than 7 bits 5660 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5661 getF32Constant(DAG, 0xbeb08fe0, dl)); 5662 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5663 getF32Constant(DAG, 0x40019463, dl)); 5664 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5665 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5666 getF32Constant(DAG, 0x3fd6633d, dl)); 5667 } else if (LimitFloatPrecision <= 12) { 5668 // For floating-point precision of 12: 5669 // 5670 // Log2ofMantissa = 5671 // -2.51285454f + 5672 // (4.07009056f + 5673 // (-2.12067489f + 5674 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5675 // 5676 // error 0.0000876136000, which is better than 13 bits 5677 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5678 getF32Constant(DAG, 0xbda7262e, dl)); 5679 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5680 getF32Constant(DAG, 0x3f25280b, dl)); 5681 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5682 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5683 getF32Constant(DAG, 0x4007b923, dl)); 5684 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5685 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5686 getF32Constant(DAG, 0x40823e2f, dl)); 5687 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5688 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5689 getF32Constant(DAG, 0x4020d29c, dl)); 5690 } else { // LimitFloatPrecision <= 18 5691 // For floating-point precision of 18: 5692 // 5693 // Log2ofMantissa = 5694 // -3.0400495f + 5695 // (6.1129976f + 5696 // (-5.3420409f + 5697 // (3.2865683f + 5698 // (-1.2669343f + 5699 // (0.27515199f - 5700 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5701 // 5702 // error 0.0000018516, which is better than 18 bits 5703 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5704 getF32Constant(DAG, 0xbcd2769e, dl)); 5705 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5706 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5707 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5708 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5709 getF32Constant(DAG, 0x3fa22ae7, dl)); 5710 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5711 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5712 getF32Constant(DAG, 0x40525723, dl)); 5713 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5714 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5715 getF32Constant(DAG, 0x40aaf200, dl)); 5716 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5717 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5718 getF32Constant(DAG, 0x40c39dad, dl)); 5719 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5720 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5721 getF32Constant(DAG, 0x4042902c, dl)); 5722 } 5723 5724 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5725 } 5726 5727 // No special expansion. 5728 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5729 } 5730 5731 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5732 /// limited-precision mode. 5733 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5734 const TargetLowering &TLI, SDNodeFlags Flags) { 5735 // TODO: What fast-math-flags should be set on the floating-point nodes? 5736 5737 if (Op.getValueType() == MVT::f32 && 5738 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5739 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5740 5741 // Scale the exponent by log10(2) [0.30102999f]. 5742 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5743 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5744 getF32Constant(DAG, 0x3e9a209a, dl)); 5745 5746 // Get the significand and build it into a floating-point number with 5747 // exponent of 1. 5748 SDValue X = GetSignificand(DAG, Op1, dl); 5749 5750 SDValue Log10ofMantissa; 5751 if (LimitFloatPrecision <= 6) { 5752 // For floating-point precision of 6: 5753 // 5754 // Log10ofMantissa = 5755 // -0.50419619f + 5756 // (0.60948995f - 0.10380950f * x) * x; 5757 // 5758 // error 0.0014886165, which is 6 bits 5759 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5760 getF32Constant(DAG, 0xbdd49a13, dl)); 5761 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5762 getF32Constant(DAG, 0x3f1c0789, dl)); 5763 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5764 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5765 getF32Constant(DAG, 0x3f011300, dl)); 5766 } else if (LimitFloatPrecision <= 12) { 5767 // For floating-point precision of 12: 5768 // 5769 // Log10ofMantissa = 5770 // -0.64831180f + 5771 // (0.91751397f + 5772 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5773 // 5774 // error 0.00019228036, which is better than 12 bits 5775 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5776 getF32Constant(DAG, 0x3d431f31, dl)); 5777 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5778 getF32Constant(DAG, 0x3ea21fb2, dl)); 5779 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5780 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5781 getF32Constant(DAG, 0x3f6ae232, dl)); 5782 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5783 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5784 getF32Constant(DAG, 0x3f25f7c3, dl)); 5785 } else { // LimitFloatPrecision <= 18 5786 // For floating-point precision of 18: 5787 // 5788 // Log10ofMantissa = 5789 // -0.84299375f + 5790 // (1.5327582f + 5791 // (-1.0688956f + 5792 // (0.49102474f + 5793 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5794 // 5795 // error 0.0000037995730, which is better than 18 bits 5796 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5797 getF32Constant(DAG, 0x3c5d51ce, dl)); 5798 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5799 getF32Constant(DAG, 0x3e00685a, dl)); 5800 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5801 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5802 getF32Constant(DAG, 0x3efb6798, dl)); 5803 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5804 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5805 getF32Constant(DAG, 0x3f88d192, dl)); 5806 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5807 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5808 getF32Constant(DAG, 0x3fc4316c, dl)); 5809 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5810 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5811 getF32Constant(DAG, 0x3f57ce70, dl)); 5812 } 5813 5814 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5815 } 5816 5817 // No special expansion. 5818 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5819 } 5820 5821 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5822 /// limited-precision mode. 5823 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5824 const TargetLowering &TLI, SDNodeFlags Flags) { 5825 if (Op.getValueType() == MVT::f32 && 5826 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5827 return getLimitedPrecisionExp2(Op, dl, DAG); 5828 5829 // No special expansion. 5830 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5831 } 5832 5833 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5834 /// limited-precision mode with x == 10.0f. 5835 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5836 SelectionDAG &DAG, const TargetLowering &TLI, 5837 SDNodeFlags Flags) { 5838 bool IsExp10 = false; 5839 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5840 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5841 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5842 APFloat Ten(10.0f); 5843 IsExp10 = LHSC->isExactlyValue(Ten); 5844 } 5845 } 5846 5847 // TODO: What fast-math-flags should be set on the FMUL node? 5848 if (IsExp10) { 5849 // Put the exponent in the right bit position for later addition to the 5850 // final result: 5851 // 5852 // #define LOG2OF10 3.3219281f 5853 // t0 = Op * LOG2OF10; 5854 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5855 getF32Constant(DAG, 0x40549a78, dl)); 5856 return getLimitedPrecisionExp2(t0, dl, DAG); 5857 } 5858 5859 // No special expansion. 5860 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5861 } 5862 5863 /// ExpandPowI - Expand a llvm.powi intrinsic. 5864 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5865 SelectionDAG &DAG) { 5866 // If RHS is a constant, we can expand this out to a multiplication tree if 5867 // it's beneficial on the target, otherwise we end up lowering to a call to 5868 // __powidf2 (for example). 5869 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5870 unsigned Val = RHSC->getSExtValue(); 5871 5872 // powi(x, 0) -> 1.0 5873 if (Val == 0) 5874 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5875 5876 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5877 Val, DAG.shouldOptForSize())) { 5878 // Get the exponent as a positive value. 5879 if ((int)Val < 0) 5880 Val = -Val; 5881 // We use the simple binary decomposition method to generate the multiply 5882 // sequence. There are more optimal ways to do this (for example, 5883 // powi(x,15) generates one more multiply than it should), but this has 5884 // the benefit of being both really simple and much better than a libcall. 5885 SDValue Res; // Logically starts equal to 1.0 5886 SDValue CurSquare = LHS; 5887 // TODO: Intrinsics should have fast-math-flags that propagate to these 5888 // nodes. 5889 while (Val) { 5890 if (Val & 1) { 5891 if (Res.getNode()) 5892 Res = 5893 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5894 else 5895 Res = CurSquare; // 1.0*CurSquare. 5896 } 5897 5898 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5899 CurSquare, CurSquare); 5900 Val >>= 1; 5901 } 5902 5903 // If the original was negative, invert the result, producing 1/(x*x*x). 5904 if (RHSC->getSExtValue() < 0) 5905 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5906 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5907 return Res; 5908 } 5909 } 5910 5911 // Otherwise, expand to a libcall. 5912 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5913 } 5914 5915 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5916 SDValue LHS, SDValue RHS, SDValue Scale, 5917 SelectionDAG &DAG, const TargetLowering &TLI) { 5918 EVT VT = LHS.getValueType(); 5919 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5920 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5921 LLVMContext &Ctx = *DAG.getContext(); 5922 5923 // If the type is legal but the operation isn't, this node might survive all 5924 // the way to operation legalization. If we end up there and we do not have 5925 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5926 // node. 5927 5928 // Coax the legalizer into expanding the node during type legalization instead 5929 // by bumping the size by one bit. This will force it to Promote, enabling the 5930 // early expansion and avoiding the need to expand later. 5931 5932 // We don't have to do this if Scale is 0; that can always be expanded, unless 5933 // it's a saturating signed operation. Those can experience true integer 5934 // division overflow, a case which we must avoid. 5935 5936 // FIXME: We wouldn't have to do this (or any of the early 5937 // expansion/promotion) if it was possible to expand a libcall of an 5938 // illegal type during operation legalization. But it's not, so things 5939 // get a bit hacky. 5940 unsigned ScaleInt = Scale->getAsZExtVal(); 5941 if ((ScaleInt > 0 || (Saturating && Signed)) && 5942 (TLI.isTypeLegal(VT) || 5943 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5944 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5945 Opcode, VT, ScaleInt); 5946 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5947 EVT PromVT; 5948 if (VT.isScalarInteger()) 5949 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5950 else if (VT.isVector()) { 5951 PromVT = VT.getVectorElementType(); 5952 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5953 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5954 } else 5955 llvm_unreachable("Wrong VT for DIVFIX?"); 5956 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5957 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5958 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5959 // For saturating operations, we need to shift up the LHS to get the 5960 // proper saturation width, and then shift down again afterwards. 5961 if (Saturating) 5962 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5963 DAG.getConstant(1, DL, ShiftTy)); 5964 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5965 if (Saturating) 5966 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5967 DAG.getConstant(1, DL, ShiftTy)); 5968 return DAG.getZExtOrTrunc(Res, DL, VT); 5969 } 5970 } 5971 5972 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5973 } 5974 5975 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5976 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5977 static void 5978 getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs, 5979 const SDValue &N) { 5980 switch (N.getOpcode()) { 5981 case ISD::CopyFromReg: { 5982 SDValue Op = N.getOperand(1); 5983 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5984 Op.getValueType().getSizeInBits()); 5985 return; 5986 } 5987 case ISD::BITCAST: 5988 case ISD::AssertZext: 5989 case ISD::AssertSext: 5990 case ISD::TRUNCATE: 5991 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5992 return; 5993 case ISD::BUILD_PAIR: 5994 case ISD::BUILD_VECTOR: 5995 case ISD::CONCAT_VECTORS: 5996 for (SDValue Op : N->op_values()) 5997 getUnderlyingArgRegs(Regs, Op); 5998 return; 5999 default: 6000 return; 6001 } 6002 } 6003 6004 /// If the DbgValueInst is a dbg_value of a function argument, create the 6005 /// corresponding DBG_VALUE machine instruction for it now. At the end of 6006 /// instruction selection, they will be inserted to the entry BB. 6007 /// We don't currently support this for variadic dbg_values, as they shouldn't 6008 /// appear for function arguments or in the prologue. 6009 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 6010 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 6011 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 6012 const Argument *Arg = dyn_cast<Argument>(V); 6013 if (!Arg) 6014 return false; 6015 6016 MachineFunction &MF = DAG.getMachineFunction(); 6017 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6018 6019 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 6020 // we've been asked to pursue. 6021 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 6022 bool Indirect) { 6023 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 6024 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 6025 // pointing at the VReg, which will be patched up later. 6026 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 6027 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 6028 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 6029 /* isKill */ false, /* isDead */ false, 6030 /* isUndef */ false, /* isEarlyClobber */ false, 6031 /* SubReg */ 0, /* isDebug */ true)}); 6032 6033 auto *NewDIExpr = FragExpr; 6034 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 6035 // the DIExpression. 6036 if (Indirect) 6037 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 6038 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 6039 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 6040 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 6041 } else { 6042 // Create a completely standard DBG_VALUE. 6043 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 6044 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 6045 } 6046 }; 6047 6048 if (Kind == FuncArgumentDbgValueKind::Value) { 6049 // ArgDbgValues are hoisted to the beginning of the entry block. So we 6050 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 6051 // the entry block. 6052 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 6053 if (!IsInEntryBlock) 6054 return false; 6055 6056 // ArgDbgValues are hoisted to the beginning of the entry block. So we 6057 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 6058 // variable that also is a param. 6059 // 6060 // Although, if we are at the top of the entry block already, we can still 6061 // emit using ArgDbgValue. This might catch some situations when the 6062 // dbg.value refers to an argument that isn't used in the entry block, so 6063 // any CopyToReg node would be optimized out and the only way to express 6064 // this DBG_VALUE is by using the physical reg (or FI) as done in this 6065 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 6066 // we should only emit as ArgDbgValue if the Variable is an argument to the 6067 // current function, and the dbg.value intrinsic is found in the entry 6068 // block. 6069 bool VariableIsFunctionInputArg = Variable->isParameter() && 6070 !DL->getInlinedAt(); 6071 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 6072 if (!IsInPrologue && !VariableIsFunctionInputArg) 6073 return false; 6074 6075 // Here we assume that a function argument on IR level only can be used to 6076 // describe one input parameter on source level. If we for example have 6077 // source code like this 6078 // 6079 // struct A { long x, y; }; 6080 // void foo(struct A a, long b) { 6081 // ... 6082 // b = a.x; 6083 // ... 6084 // } 6085 // 6086 // and IR like this 6087 // 6088 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 6089 // entry: 6090 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 6091 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 6092 // call void @llvm.dbg.value(metadata i32 %b, "b", 6093 // ... 6094 // call void @llvm.dbg.value(metadata i32 %a1, "b" 6095 // ... 6096 // 6097 // then the last dbg.value is describing a parameter "b" using a value that 6098 // is an argument. But since we already has used %a1 to describe a parameter 6099 // we should not handle that last dbg.value here (that would result in an 6100 // incorrect hoisting of the DBG_VALUE to the function entry). 6101 // Notice that we allow one dbg.value per IR level argument, to accommodate 6102 // for the situation with fragments above. 6103 // If there is no node for the value being handled, we return true to skip 6104 // the normal generation of debug info, as it would kill existing debug 6105 // info for the parameter in case of duplicates. 6106 if (VariableIsFunctionInputArg) { 6107 unsigned ArgNo = Arg->getArgNo(); 6108 if (ArgNo >= FuncInfo.DescribedArgs.size()) 6109 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 6110 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 6111 return !NodeMap[V].getNode(); 6112 FuncInfo.DescribedArgs.set(ArgNo); 6113 } 6114 } 6115 6116 bool IsIndirect = false; 6117 std::optional<MachineOperand> Op; 6118 // Some arguments' frame index is recorded during argument lowering. 6119 int FI = FuncInfo.getArgumentFrameIndex(Arg); 6120 if (FI != std::numeric_limits<int>::max()) 6121 Op = MachineOperand::CreateFI(FI); 6122 6123 SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes; 6124 if (!Op && N.getNode()) { 6125 getUnderlyingArgRegs(ArgRegsAndSizes, N); 6126 Register Reg; 6127 if (ArgRegsAndSizes.size() == 1) 6128 Reg = ArgRegsAndSizes.front().first; 6129 6130 if (Reg && Reg.isVirtual()) { 6131 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6132 Register PR = RegInfo.getLiveInPhysReg(Reg); 6133 if (PR) 6134 Reg = PR; 6135 } 6136 if (Reg) { 6137 Op = MachineOperand::CreateReg(Reg, false); 6138 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6139 } 6140 } 6141 6142 if (!Op && N.getNode()) { 6143 // Check if frame index is available. 6144 SDValue LCandidate = peekThroughBitcasts(N); 6145 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 6146 if (FrameIndexSDNode *FINode = 6147 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 6148 Op = MachineOperand::CreateFI(FINode->getIndex()); 6149 } 6150 6151 if (!Op) { 6152 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 6153 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<Register, TypeSize>> 6154 SplitRegs) { 6155 unsigned Offset = 0; 6156 for (const auto &RegAndSize : SplitRegs) { 6157 // If the expression is already a fragment, the current register 6158 // offset+size might extend beyond the fragment. In this case, only 6159 // the register bits that are inside the fragment are relevant. 6160 int RegFragmentSizeInBits = RegAndSize.second; 6161 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 6162 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 6163 // The register is entirely outside the expression fragment, 6164 // so is irrelevant for debug info. 6165 if (Offset >= ExprFragmentSizeInBits) 6166 break; 6167 // The register is partially outside the expression fragment, only 6168 // the low bits within the fragment are relevant for debug info. 6169 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 6170 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 6171 } 6172 } 6173 6174 auto FragmentExpr = DIExpression::createFragmentExpression( 6175 Expr, Offset, RegFragmentSizeInBits); 6176 Offset += RegAndSize.second; 6177 // If a valid fragment expression cannot be created, the variable's 6178 // correct value cannot be determined and so it is set as Undef. 6179 if (!FragmentExpr) { 6180 SDDbgValue *SDV = DAG.getConstantDbgValue( 6181 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 6182 DAG.AddDbgValue(SDV, false); 6183 continue; 6184 } 6185 MachineInstr *NewMI = 6186 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 6187 Kind != FuncArgumentDbgValueKind::Value); 6188 FuncInfo.ArgDbgValues.push_back(NewMI); 6189 } 6190 }; 6191 6192 // Check if ValueMap has reg number. 6193 DenseMap<const Value *, Register>::const_iterator 6194 VMI = FuncInfo.ValueMap.find(V); 6195 if (VMI != FuncInfo.ValueMap.end()) { 6196 const auto &TLI = DAG.getTargetLoweringInfo(); 6197 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 6198 V->getType(), std::nullopt); 6199 if (RFV.occupiesMultipleRegs()) { 6200 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 6201 return true; 6202 } 6203 6204 Op = MachineOperand::CreateReg(VMI->second, false); 6205 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6206 } else if (ArgRegsAndSizes.size() > 1) { 6207 // This was split due to the calling convention, and no virtual register 6208 // mapping exists for the value. 6209 splitMultiRegDbgValue(ArgRegsAndSizes); 6210 return true; 6211 } 6212 } 6213 6214 if (!Op) 6215 return false; 6216 6217 assert(Variable->isValidLocationForIntrinsic(DL) && 6218 "Expected inlined-at fields to agree"); 6219 MachineInstr *NewMI = nullptr; 6220 6221 if (Op->isReg()) 6222 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 6223 else 6224 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 6225 Variable, Expr); 6226 6227 // Otherwise, use ArgDbgValues. 6228 FuncInfo.ArgDbgValues.push_back(NewMI); 6229 return true; 6230 } 6231 6232 /// Return the appropriate SDDbgValue based on N. 6233 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 6234 DILocalVariable *Variable, 6235 DIExpression *Expr, 6236 const DebugLoc &dl, 6237 unsigned DbgSDNodeOrder) { 6238 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 6239 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 6240 // stack slot locations. 6241 // 6242 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 6243 // debug values here after optimization: 6244 // 6245 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 6246 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 6247 // 6248 // Both describe the direct values of their associated variables. 6249 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 6250 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6251 } 6252 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 6253 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6254 } 6255 6256 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 6257 switch (Intrinsic) { 6258 case Intrinsic::smul_fix: 6259 return ISD::SMULFIX; 6260 case Intrinsic::umul_fix: 6261 return ISD::UMULFIX; 6262 case Intrinsic::smul_fix_sat: 6263 return ISD::SMULFIXSAT; 6264 case Intrinsic::umul_fix_sat: 6265 return ISD::UMULFIXSAT; 6266 case Intrinsic::sdiv_fix: 6267 return ISD::SDIVFIX; 6268 case Intrinsic::udiv_fix: 6269 return ISD::UDIVFIX; 6270 case Intrinsic::sdiv_fix_sat: 6271 return ISD::SDIVFIXSAT; 6272 case Intrinsic::udiv_fix_sat: 6273 return ISD::UDIVFIXSAT; 6274 default: 6275 llvm_unreachable("Unhandled fixed point intrinsic"); 6276 } 6277 } 6278 6279 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6280 const char *FunctionName) { 6281 assert(FunctionName && "FunctionName must not be nullptr"); 6282 SDValue Callee = DAG.getExternalSymbol( 6283 FunctionName, 6284 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6285 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6286 } 6287 6288 /// Given a @llvm.call.preallocated.setup, return the corresponding 6289 /// preallocated call. 6290 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6291 assert(cast<CallBase>(PreallocatedSetup) 6292 ->getCalledFunction() 6293 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6294 "expected call_preallocated_setup Value"); 6295 for (const auto *U : PreallocatedSetup->users()) { 6296 auto *UseCall = cast<CallBase>(U); 6297 const Function *Fn = UseCall->getCalledFunction(); 6298 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6299 return UseCall; 6300 } 6301 } 6302 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6303 } 6304 6305 /// If DI is a debug value with an EntryValue expression, lower it using the 6306 /// corresponding physical register of the associated Argument value 6307 /// (guaranteed to exist by the verifier). 6308 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6309 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6310 DIExpression *Expr, DebugLoc DbgLoc) { 6311 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6312 return false; 6313 6314 // These properties are guaranteed by the verifier. 6315 const Argument *Arg = cast<Argument>(Values[0]); 6316 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6317 6318 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6319 if (ArgIt == FuncInfo.ValueMap.end()) { 6320 LLVM_DEBUG( 6321 dbgs() << "Dropping dbg.value: expression is entry_value but " 6322 "couldn't find an associated register for the Argument\n"); 6323 return true; 6324 } 6325 Register ArgVReg = ArgIt->getSecond(); 6326 6327 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6328 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6329 SDDbgValue *SDV = DAG.getVRegDbgValue( 6330 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6331 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6332 return true; 6333 } 6334 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6335 "couldn't find a physical register\n"); 6336 return true; 6337 } 6338 6339 /// Lower the call to the specified intrinsic function. 6340 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I, 6341 unsigned Intrinsic) { 6342 SDLoc sdl = getCurSDLoc(); 6343 switch (Intrinsic) { 6344 case Intrinsic::experimental_convergence_anchor: 6345 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped)); 6346 break; 6347 case Intrinsic::experimental_convergence_entry: 6348 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped)); 6349 break; 6350 case Intrinsic::experimental_convergence_loop: { 6351 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl); 6352 auto *Token = Bundle->Inputs[0].get(); 6353 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped, 6354 getValue(Token))); 6355 break; 6356 } 6357 } 6358 } 6359 6360 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I, 6361 unsigned IntrinsicID) { 6362 // For now, we're only lowering an 'add' histogram. 6363 // We can add others later, e.g. saturating adds, min/max. 6364 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add && 6365 "Tried to lower unsupported histogram type"); 6366 SDLoc sdl = getCurSDLoc(); 6367 Value *Ptr = I.getOperand(0); 6368 SDValue Inc = getValue(I.getOperand(1)); 6369 SDValue Mask = getValue(I.getOperand(2)); 6370 6371 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6372 DataLayout TargetDL = DAG.getDataLayout(); 6373 EVT VT = Inc.getValueType(); 6374 Align Alignment = DAG.getEVTAlign(VT); 6375 6376 const MDNode *Ranges = getRangeMetadata(I); 6377 6378 SDValue Root = DAG.getRoot(); 6379 SDValue Base; 6380 SDValue Index; 6381 ISD::MemIndexType IndexType; 6382 SDValue Scale; 6383 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 6384 I.getParent(), VT.getScalarStoreSize()); 6385 6386 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 6387 6388 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6389 MachinePointerInfo(AS), 6390 MachineMemOperand::MOLoad | MachineMemOperand::MOStore, 6391 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 6392 6393 if (!UniformBase) { 6394 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6395 Index = getValue(Ptr); 6396 IndexType = ISD::SIGNED_SCALED; 6397 Scale = 6398 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6399 } 6400 6401 EVT IdxVT = Index.getValueType(); 6402 EVT EltTy = IdxVT.getVectorElementType(); 6403 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 6404 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 6405 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 6406 } 6407 6408 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32); 6409 6410 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID}; 6411 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl, 6412 Ops, MMO, IndexType); 6413 6414 setValue(&I, Histogram); 6415 DAG.setRoot(Histogram); 6416 } 6417 6418 void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I, 6419 unsigned Intrinsic) { 6420 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active && 6421 "Tried lowering invalid vector extract last"); 6422 SDLoc sdl = getCurSDLoc(); 6423 SDValue Data = getValue(I.getOperand(0)); 6424 SDValue Mask = getValue(I.getOperand(1)); 6425 SDValue PassThru = getValue(I.getOperand(2)); 6426 6427 EVT DataVT = Data.getValueType(); 6428 EVT ScalarVT = PassThru.getValueType(); 6429 EVT BoolVT = Mask.getValueType().getScalarType(); 6430 6431 // Find a suitable type for a stepvector. 6432 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Dummy value. 6433 if (DataVT.isScalableVector()) 6434 VScaleRange = getVScaleRange(I.getCaller(), 64); 6435 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6436 unsigned EltWidth = TLI.getBitWidthForCttzElements( 6437 I.getType(), DataVT.getVectorElementCount(), /*ZeroIsPoison=*/true, 6438 &VScaleRange); 6439 MVT StepVT = MVT::getIntegerVT(EltWidth); 6440 EVT StepVecVT = DataVT.changeVectorElementType(StepVT); 6441 6442 // Zero out lanes with inactive elements, then find the highest remaining 6443 // value from the stepvector. 6444 SDValue Zeroes = DAG.getConstant(0, sdl, StepVecVT); 6445 SDValue StepVec = DAG.getStepVector(sdl, StepVecVT); 6446 SDValue ActiveElts = DAG.getSelect(sdl, StepVecVT, Mask, StepVec, Zeroes); 6447 SDValue HighestIdx = 6448 DAG.getNode(ISD::VECREDUCE_UMAX, sdl, StepVT, ActiveElts); 6449 6450 // Extract the corresponding lane from the data vector 6451 EVT ExtVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 6452 SDValue Idx = DAG.getZExtOrTrunc(HighestIdx, sdl, ExtVT); 6453 SDValue Extract = 6454 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ScalarVT, Data, Idx); 6455 6456 // If all mask lanes were inactive, choose the passthru value instead. 6457 SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask); 6458 SDValue Result = DAG.getSelect(sdl, ScalarVT, AnyActive, Extract, PassThru); 6459 setValue(&I, Result); 6460 } 6461 6462 /// Lower the call to the specified intrinsic function. 6463 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6464 unsigned Intrinsic) { 6465 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6466 SDLoc sdl = getCurSDLoc(); 6467 DebugLoc dl = getCurDebugLoc(); 6468 SDValue Res; 6469 6470 SDNodeFlags Flags; 6471 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6472 Flags.copyFMF(*FPOp); 6473 6474 switch (Intrinsic) { 6475 default: 6476 // By default, turn this into a target intrinsic node. 6477 visitTargetIntrinsic(I, Intrinsic); 6478 return; 6479 case Intrinsic::vscale: { 6480 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6481 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6482 return; 6483 } 6484 case Intrinsic::vastart: visitVAStart(I); return; 6485 case Intrinsic::vaend: visitVAEnd(I); return; 6486 case Intrinsic::vacopy: visitVACopy(I); return; 6487 case Intrinsic::returnaddress: 6488 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6489 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6490 getValue(I.getArgOperand(0)))); 6491 return; 6492 case Intrinsic::addressofreturnaddress: 6493 setValue(&I, 6494 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6495 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6496 return; 6497 case Intrinsic::sponentry: 6498 setValue(&I, 6499 DAG.getNode(ISD::SPONENTRY, sdl, 6500 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6501 return; 6502 case Intrinsic::frameaddress: 6503 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6504 TLI.getFrameIndexTy(DAG.getDataLayout()), 6505 getValue(I.getArgOperand(0)))); 6506 return; 6507 case Intrinsic::read_volatile_register: 6508 case Intrinsic::read_register: { 6509 Value *Reg = I.getArgOperand(0); 6510 SDValue Chain = getRoot(); 6511 SDValue RegName = 6512 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6513 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6514 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6515 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6516 setValue(&I, Res); 6517 DAG.setRoot(Res.getValue(1)); 6518 return; 6519 } 6520 case Intrinsic::write_register: { 6521 Value *Reg = I.getArgOperand(0); 6522 Value *RegValue = I.getArgOperand(1); 6523 SDValue Chain = getRoot(); 6524 SDValue RegName = 6525 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6526 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6527 RegName, getValue(RegValue))); 6528 return; 6529 } 6530 case Intrinsic::memcpy: { 6531 const auto &MCI = cast<MemCpyInst>(I); 6532 SDValue Op1 = getValue(I.getArgOperand(0)); 6533 SDValue Op2 = getValue(I.getArgOperand(1)); 6534 SDValue Op3 = getValue(I.getArgOperand(2)); 6535 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6536 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6537 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6538 Align Alignment = std::min(DstAlign, SrcAlign); 6539 bool isVol = MCI.isVolatile(); 6540 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6541 // node. 6542 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6543 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6544 /* AlwaysInline */ false, &I, std::nullopt, 6545 MachinePointerInfo(I.getArgOperand(0)), 6546 MachinePointerInfo(I.getArgOperand(1)), 6547 I.getAAMetadata(), AA); 6548 updateDAGForMaybeTailCall(MC); 6549 return; 6550 } 6551 case Intrinsic::memcpy_inline: { 6552 const auto &MCI = cast<MemCpyInlineInst>(I); 6553 SDValue Dst = getValue(I.getArgOperand(0)); 6554 SDValue Src = getValue(I.getArgOperand(1)); 6555 SDValue Size = getValue(I.getArgOperand(2)); 6556 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6557 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6558 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6559 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6560 Align Alignment = std::min(DstAlign, SrcAlign); 6561 bool isVol = MCI.isVolatile(); 6562 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6563 // node. 6564 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6565 /* AlwaysInline */ true, &I, std::nullopt, 6566 MachinePointerInfo(I.getArgOperand(0)), 6567 MachinePointerInfo(I.getArgOperand(1)), 6568 I.getAAMetadata(), AA); 6569 updateDAGForMaybeTailCall(MC); 6570 return; 6571 } 6572 case Intrinsic::memset: { 6573 const auto &MSI = cast<MemSetInst>(I); 6574 SDValue Op1 = getValue(I.getArgOperand(0)); 6575 SDValue Op2 = getValue(I.getArgOperand(1)); 6576 SDValue Op3 = getValue(I.getArgOperand(2)); 6577 // @llvm.memset defines 0 and 1 to both mean no alignment. 6578 Align Alignment = MSI.getDestAlign().valueOrOne(); 6579 bool isVol = MSI.isVolatile(); 6580 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6581 SDValue MS = DAG.getMemset( 6582 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6583 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6584 updateDAGForMaybeTailCall(MS); 6585 return; 6586 } 6587 case Intrinsic::memset_inline: { 6588 const auto &MSII = cast<MemSetInlineInst>(I); 6589 SDValue Dst = getValue(I.getArgOperand(0)); 6590 SDValue Value = getValue(I.getArgOperand(1)); 6591 SDValue Size = getValue(I.getArgOperand(2)); 6592 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6593 // @llvm.memset defines 0 and 1 to both mean no alignment. 6594 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6595 bool isVol = MSII.isVolatile(); 6596 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6597 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6598 /* AlwaysInline */ true, &I, 6599 MachinePointerInfo(I.getArgOperand(0)), 6600 I.getAAMetadata()); 6601 updateDAGForMaybeTailCall(MC); 6602 return; 6603 } 6604 case Intrinsic::memmove: { 6605 const auto &MMI = cast<MemMoveInst>(I); 6606 SDValue Op1 = getValue(I.getArgOperand(0)); 6607 SDValue Op2 = getValue(I.getArgOperand(1)); 6608 SDValue Op3 = getValue(I.getArgOperand(2)); 6609 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6610 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6611 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6612 Align Alignment = std::min(DstAlign, SrcAlign); 6613 bool isVol = MMI.isVolatile(); 6614 // FIXME: Support passing different dest/src alignments to the memmove DAG 6615 // node. 6616 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6617 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I, 6618 /* OverrideTailCall */ std::nullopt, 6619 MachinePointerInfo(I.getArgOperand(0)), 6620 MachinePointerInfo(I.getArgOperand(1)), 6621 I.getAAMetadata(), AA); 6622 updateDAGForMaybeTailCall(MM); 6623 return; 6624 } 6625 case Intrinsic::memcpy_element_unordered_atomic: { 6626 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6627 SDValue Dst = getValue(MI.getRawDest()); 6628 SDValue Src = getValue(MI.getRawSource()); 6629 SDValue Length = getValue(MI.getLength()); 6630 6631 Type *LengthTy = MI.getLength()->getType(); 6632 unsigned ElemSz = MI.getElementSizeInBytes(); 6633 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6634 SDValue MC = 6635 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6636 isTC, MachinePointerInfo(MI.getRawDest()), 6637 MachinePointerInfo(MI.getRawSource())); 6638 updateDAGForMaybeTailCall(MC); 6639 return; 6640 } 6641 case Intrinsic::memmove_element_unordered_atomic: { 6642 auto &MI = cast<AtomicMemMoveInst>(I); 6643 SDValue Dst = getValue(MI.getRawDest()); 6644 SDValue Src = getValue(MI.getRawSource()); 6645 SDValue Length = getValue(MI.getLength()); 6646 6647 Type *LengthTy = MI.getLength()->getType(); 6648 unsigned ElemSz = MI.getElementSizeInBytes(); 6649 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6650 SDValue MC = 6651 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6652 isTC, MachinePointerInfo(MI.getRawDest()), 6653 MachinePointerInfo(MI.getRawSource())); 6654 updateDAGForMaybeTailCall(MC); 6655 return; 6656 } 6657 case Intrinsic::memset_element_unordered_atomic: { 6658 auto &MI = cast<AtomicMemSetInst>(I); 6659 SDValue Dst = getValue(MI.getRawDest()); 6660 SDValue Val = getValue(MI.getValue()); 6661 SDValue Length = getValue(MI.getLength()); 6662 6663 Type *LengthTy = MI.getLength()->getType(); 6664 unsigned ElemSz = MI.getElementSizeInBytes(); 6665 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6666 SDValue MC = 6667 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6668 isTC, MachinePointerInfo(MI.getRawDest())); 6669 updateDAGForMaybeTailCall(MC); 6670 return; 6671 } 6672 case Intrinsic::call_preallocated_setup: { 6673 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6674 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6675 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6676 getRoot(), SrcValue); 6677 setValue(&I, Res); 6678 DAG.setRoot(Res); 6679 return; 6680 } 6681 case Intrinsic::call_preallocated_arg: { 6682 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6683 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6684 SDValue Ops[3]; 6685 Ops[0] = getRoot(); 6686 Ops[1] = SrcValue; 6687 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6688 MVT::i32); // arg index 6689 SDValue Res = DAG.getNode( 6690 ISD::PREALLOCATED_ARG, sdl, 6691 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6692 setValue(&I, Res); 6693 DAG.setRoot(Res.getValue(1)); 6694 return; 6695 } 6696 case Intrinsic::dbg_declare: { 6697 const auto &DI = cast<DbgDeclareInst>(I); 6698 // Debug intrinsics are handled separately in assignment tracking mode. 6699 // Some intrinsics are handled right after Argument lowering. 6700 if (AssignmentTrackingEnabled || 6701 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6702 return; 6703 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6704 DILocalVariable *Variable = DI.getVariable(); 6705 DIExpression *Expression = DI.getExpression(); 6706 dropDanglingDebugInfo(Variable, Expression); 6707 // Assume dbg.declare can not currently use DIArgList, i.e. 6708 // it is non-variadic. 6709 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6710 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6711 DI.getDebugLoc()); 6712 return; 6713 } 6714 case Intrinsic::dbg_label: { 6715 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6716 DILabel *Label = DI.getLabel(); 6717 assert(Label && "Missing label"); 6718 6719 SDDbgLabel *SDV; 6720 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6721 DAG.AddDbgLabel(SDV); 6722 return; 6723 } 6724 case Intrinsic::dbg_assign: { 6725 // Debug intrinsics are handled separately in assignment tracking mode. 6726 if (AssignmentTrackingEnabled) 6727 return; 6728 // If assignment tracking hasn't been enabled then fall through and treat 6729 // the dbg.assign as a dbg.value. 6730 [[fallthrough]]; 6731 } 6732 case Intrinsic::dbg_value: { 6733 // Debug intrinsics are handled separately in assignment tracking mode. 6734 if (AssignmentTrackingEnabled) 6735 return; 6736 const DbgValueInst &DI = cast<DbgValueInst>(I); 6737 assert(DI.getVariable() && "Missing variable"); 6738 6739 DILocalVariable *Variable = DI.getVariable(); 6740 DIExpression *Expression = DI.getExpression(); 6741 dropDanglingDebugInfo(Variable, Expression); 6742 6743 if (DI.isKillLocation()) { 6744 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6745 return; 6746 } 6747 6748 SmallVector<Value *, 4> Values(DI.getValues()); 6749 if (Values.empty()) 6750 return; 6751 6752 bool IsVariadic = DI.hasArgList(); 6753 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6754 SDNodeOrder, IsVariadic)) 6755 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6756 DI.getDebugLoc(), SDNodeOrder); 6757 return; 6758 } 6759 6760 case Intrinsic::eh_typeid_for: { 6761 // Find the type id for the given typeinfo. 6762 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6763 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6764 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6765 setValue(&I, Res); 6766 return; 6767 } 6768 6769 case Intrinsic::eh_return_i32: 6770 case Intrinsic::eh_return_i64: 6771 DAG.getMachineFunction().setCallsEHReturn(true); 6772 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6773 MVT::Other, 6774 getControlRoot(), 6775 getValue(I.getArgOperand(0)), 6776 getValue(I.getArgOperand(1)))); 6777 return; 6778 case Intrinsic::eh_unwind_init: 6779 DAG.getMachineFunction().setCallsUnwindInit(true); 6780 return; 6781 case Intrinsic::eh_dwarf_cfa: 6782 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6783 TLI.getPointerTy(DAG.getDataLayout()), 6784 getValue(I.getArgOperand(0)))); 6785 return; 6786 case Intrinsic::eh_sjlj_callsite: { 6787 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6788 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6789 6790 FuncInfo.setCurrentCallSite(CI->getZExtValue()); 6791 return; 6792 } 6793 case Intrinsic::eh_sjlj_functioncontext: { 6794 // Get and store the index of the function context. 6795 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6796 AllocaInst *FnCtx = 6797 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6798 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6799 MFI.setFunctionContextIndex(FI); 6800 return; 6801 } 6802 case Intrinsic::eh_sjlj_setjmp: { 6803 SDValue Ops[2]; 6804 Ops[0] = getRoot(); 6805 Ops[1] = getValue(I.getArgOperand(0)); 6806 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6807 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6808 setValue(&I, Op.getValue(0)); 6809 DAG.setRoot(Op.getValue(1)); 6810 return; 6811 } 6812 case Intrinsic::eh_sjlj_longjmp: 6813 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6814 getRoot(), getValue(I.getArgOperand(0)))); 6815 return; 6816 case Intrinsic::eh_sjlj_setup_dispatch: 6817 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6818 getRoot())); 6819 return; 6820 case Intrinsic::masked_gather: 6821 visitMaskedGather(I); 6822 return; 6823 case Intrinsic::masked_load: 6824 visitMaskedLoad(I); 6825 return; 6826 case Intrinsic::masked_scatter: 6827 visitMaskedScatter(I); 6828 return; 6829 case Intrinsic::masked_store: 6830 visitMaskedStore(I); 6831 return; 6832 case Intrinsic::masked_expandload: 6833 visitMaskedLoad(I, true /* IsExpanding */); 6834 return; 6835 case Intrinsic::masked_compressstore: 6836 visitMaskedStore(I, true /* IsCompressing */); 6837 return; 6838 case Intrinsic::powi: 6839 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6840 getValue(I.getArgOperand(1)), DAG)); 6841 return; 6842 case Intrinsic::log: 6843 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6844 return; 6845 case Intrinsic::log2: 6846 setValue(&I, 6847 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6848 return; 6849 case Intrinsic::log10: 6850 setValue(&I, 6851 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6852 return; 6853 case Intrinsic::exp: 6854 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6855 return; 6856 case Intrinsic::exp2: 6857 setValue(&I, 6858 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6859 return; 6860 case Intrinsic::pow: 6861 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6862 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6863 return; 6864 case Intrinsic::sqrt: 6865 case Intrinsic::fabs: 6866 case Intrinsic::sin: 6867 case Intrinsic::cos: 6868 case Intrinsic::tan: 6869 case Intrinsic::asin: 6870 case Intrinsic::acos: 6871 case Intrinsic::atan: 6872 case Intrinsic::sinh: 6873 case Intrinsic::cosh: 6874 case Intrinsic::tanh: 6875 case Intrinsic::exp10: 6876 case Intrinsic::floor: 6877 case Intrinsic::ceil: 6878 case Intrinsic::trunc: 6879 case Intrinsic::rint: 6880 case Intrinsic::nearbyint: 6881 case Intrinsic::round: 6882 case Intrinsic::roundeven: 6883 case Intrinsic::canonicalize: { 6884 unsigned Opcode; 6885 // clang-format off 6886 switch (Intrinsic) { 6887 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6888 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6889 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6890 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6891 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6892 case Intrinsic::tan: Opcode = ISD::FTAN; break; 6893 case Intrinsic::asin: Opcode = ISD::FASIN; break; 6894 case Intrinsic::acos: Opcode = ISD::FACOS; break; 6895 case Intrinsic::atan: Opcode = ISD::FATAN; break; 6896 case Intrinsic::sinh: Opcode = ISD::FSINH; break; 6897 case Intrinsic::cosh: Opcode = ISD::FCOSH; break; 6898 case Intrinsic::tanh: Opcode = ISD::FTANH; break; 6899 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6900 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6901 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6902 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6903 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6904 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6905 case Intrinsic::round: Opcode = ISD::FROUND; break; 6906 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6907 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6908 } 6909 // clang-format on 6910 6911 setValue(&I, DAG.getNode(Opcode, sdl, 6912 getValue(I.getArgOperand(0)).getValueType(), 6913 getValue(I.getArgOperand(0)), Flags)); 6914 return; 6915 } 6916 case Intrinsic::atan2: 6917 setValue(&I, DAG.getNode(ISD::FATAN2, sdl, 6918 getValue(I.getArgOperand(0)).getValueType(), 6919 getValue(I.getArgOperand(0)), 6920 getValue(I.getArgOperand(1)), Flags)); 6921 return; 6922 case Intrinsic::lround: 6923 case Intrinsic::llround: 6924 case Intrinsic::lrint: 6925 case Intrinsic::llrint: { 6926 unsigned Opcode; 6927 // clang-format off 6928 switch (Intrinsic) { 6929 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6930 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6931 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6932 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6933 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6934 } 6935 // clang-format on 6936 6937 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6938 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6939 getValue(I.getArgOperand(0)))); 6940 return; 6941 } 6942 case Intrinsic::minnum: 6943 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6944 getValue(I.getArgOperand(0)).getValueType(), 6945 getValue(I.getArgOperand(0)), 6946 getValue(I.getArgOperand(1)), Flags)); 6947 return; 6948 case Intrinsic::maxnum: 6949 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6950 getValue(I.getArgOperand(0)).getValueType(), 6951 getValue(I.getArgOperand(0)), 6952 getValue(I.getArgOperand(1)), Flags)); 6953 return; 6954 case Intrinsic::minimum: 6955 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6956 getValue(I.getArgOperand(0)).getValueType(), 6957 getValue(I.getArgOperand(0)), 6958 getValue(I.getArgOperand(1)), Flags)); 6959 return; 6960 case Intrinsic::maximum: 6961 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6962 getValue(I.getArgOperand(0)).getValueType(), 6963 getValue(I.getArgOperand(0)), 6964 getValue(I.getArgOperand(1)), Flags)); 6965 return; 6966 case Intrinsic::minimumnum: 6967 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl, 6968 getValue(I.getArgOperand(0)).getValueType(), 6969 getValue(I.getArgOperand(0)), 6970 getValue(I.getArgOperand(1)), Flags)); 6971 return; 6972 case Intrinsic::maximumnum: 6973 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl, 6974 getValue(I.getArgOperand(0)).getValueType(), 6975 getValue(I.getArgOperand(0)), 6976 getValue(I.getArgOperand(1)), Flags)); 6977 return; 6978 case Intrinsic::copysign: 6979 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6980 getValue(I.getArgOperand(0)).getValueType(), 6981 getValue(I.getArgOperand(0)), 6982 getValue(I.getArgOperand(1)), Flags)); 6983 return; 6984 case Intrinsic::ldexp: 6985 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6986 getValue(I.getArgOperand(0)).getValueType(), 6987 getValue(I.getArgOperand(0)), 6988 getValue(I.getArgOperand(1)), Flags)); 6989 return; 6990 case Intrinsic::sincos: 6991 case Intrinsic::frexp: { 6992 unsigned Opcode; 6993 switch (Intrinsic) { 6994 default: 6995 llvm_unreachable("unexpected intrinsic"); 6996 case Intrinsic::sincos: 6997 Opcode = ISD::FSINCOS; 6998 break; 6999 case Intrinsic::frexp: 7000 Opcode = ISD::FFREXP; 7001 break; 7002 } 7003 SmallVector<EVT, 2> ValueVTs; 7004 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 7005 SDVTList VTs = DAG.getVTList(ValueVTs); 7006 setValue( 7007 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags)); 7008 return; 7009 } 7010 case Intrinsic::arithmetic_fence: { 7011 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 7012 getValue(I.getArgOperand(0)).getValueType(), 7013 getValue(I.getArgOperand(0)), Flags)); 7014 return; 7015 } 7016 case Intrinsic::fma: 7017 setValue(&I, DAG.getNode( 7018 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 7019 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 7020 getValue(I.getArgOperand(2)), Flags)); 7021 return; 7022 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 7023 case Intrinsic::INTRINSIC: 7024 #include "llvm/IR/ConstrainedOps.def" 7025 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 7026 return; 7027 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 7028 #include "llvm/IR/VPIntrinsics.def" 7029 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 7030 return; 7031 case Intrinsic::fptrunc_round: { 7032 // Get the last argument, the metadata and convert it to an integer in the 7033 // call 7034 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 7035 std::optional<RoundingMode> RoundMode = 7036 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 7037 7038 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7039 7040 // Propagate fast-math-flags from IR to node(s). 7041 SDNodeFlags Flags; 7042 Flags.copyFMF(*cast<FPMathOperator>(&I)); 7043 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 7044 7045 SDValue Result; 7046 Result = DAG.getNode( 7047 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 7048 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32)); 7049 setValue(&I, Result); 7050 7051 return; 7052 } 7053 case Intrinsic::fmuladd: { 7054 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7055 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7056 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7057 setValue(&I, DAG.getNode(ISD::FMA, sdl, 7058 getValue(I.getArgOperand(0)).getValueType(), 7059 getValue(I.getArgOperand(0)), 7060 getValue(I.getArgOperand(1)), 7061 getValue(I.getArgOperand(2)), Flags)); 7062 } else { 7063 // TODO: Intrinsic calls should have fast-math-flags. 7064 SDValue Mul = DAG.getNode( 7065 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 7066 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 7067 SDValue Add = DAG.getNode(ISD::FADD, sdl, 7068 getValue(I.getArgOperand(0)).getValueType(), 7069 Mul, getValue(I.getArgOperand(2)), Flags); 7070 setValue(&I, Add); 7071 } 7072 return; 7073 } 7074 case Intrinsic::convert_to_fp16: 7075 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 7076 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 7077 getValue(I.getArgOperand(0)), 7078 DAG.getTargetConstant(0, sdl, 7079 MVT::i32)))); 7080 return; 7081 case Intrinsic::convert_from_fp16: 7082 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 7083 TLI.getValueType(DAG.getDataLayout(), I.getType()), 7084 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 7085 getValue(I.getArgOperand(0))))); 7086 return; 7087 case Intrinsic::fptosi_sat: { 7088 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7089 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 7090 getValue(I.getArgOperand(0)), 7091 DAG.getValueType(VT.getScalarType()))); 7092 return; 7093 } 7094 case Intrinsic::fptoui_sat: { 7095 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7096 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 7097 getValue(I.getArgOperand(0)), 7098 DAG.getValueType(VT.getScalarType()))); 7099 return; 7100 } 7101 case Intrinsic::set_rounding: 7102 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 7103 {getRoot(), getValue(I.getArgOperand(0))}); 7104 setValue(&I, Res); 7105 DAG.setRoot(Res.getValue(0)); 7106 return; 7107 case Intrinsic::is_fpclass: { 7108 const DataLayout DLayout = DAG.getDataLayout(); 7109 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 7110 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 7111 FPClassTest Test = static_cast<FPClassTest>( 7112 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 7113 MachineFunction &MF = DAG.getMachineFunction(); 7114 const Function &F = MF.getFunction(); 7115 SDValue Op = getValue(I.getArgOperand(0)); 7116 SDNodeFlags Flags; 7117 Flags.setNoFPExcept( 7118 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 7119 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 7120 // expansion can use illegal types. Making expansion early allows 7121 // legalizing these types prior to selection. 7122 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) && 7123 !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) { 7124 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 7125 setValue(&I, Result); 7126 return; 7127 } 7128 7129 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 7130 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 7131 setValue(&I, V); 7132 return; 7133 } 7134 case Intrinsic::get_fpenv: { 7135 const DataLayout DLayout = DAG.getDataLayout(); 7136 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 7137 Align TempAlign = DAG.getEVTAlign(EnvVT); 7138 SDValue Chain = getRoot(); 7139 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 7140 // and temporary storage in stack. 7141 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 7142 Res = DAG.getNode( 7143 ISD::GET_FPENV, sdl, 7144 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7145 MVT::Other), 7146 Chain); 7147 } else { 7148 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7149 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7150 auto MPI = 7151 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7152 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7153 MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(), 7154 TempAlign); 7155 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7156 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 7157 } 7158 setValue(&I, Res); 7159 DAG.setRoot(Res.getValue(1)); 7160 return; 7161 } 7162 case Intrinsic::set_fpenv: { 7163 const DataLayout DLayout = DAG.getDataLayout(); 7164 SDValue Env = getValue(I.getArgOperand(0)); 7165 EVT EnvVT = Env.getValueType(); 7166 Align TempAlign = DAG.getEVTAlign(EnvVT); 7167 SDValue Chain = getRoot(); 7168 // If SET_FPENV is custom or legal, use it. Otherwise use loading 7169 // environment from memory. 7170 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 7171 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 7172 } else { 7173 // Allocate space in stack, copy environment bits into it and use this 7174 // memory in SET_FPENV_MEM. 7175 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7176 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7177 auto MPI = 7178 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7179 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 7180 MachineMemOperand::MOStore); 7181 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7182 MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(), 7183 TempAlign); 7184 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7185 } 7186 DAG.setRoot(Chain); 7187 return; 7188 } 7189 case Intrinsic::reset_fpenv: 7190 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 7191 return; 7192 case Intrinsic::get_fpmode: 7193 Res = DAG.getNode( 7194 ISD::GET_FPMODE, sdl, 7195 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7196 MVT::Other), 7197 DAG.getRoot()); 7198 setValue(&I, Res); 7199 DAG.setRoot(Res.getValue(1)); 7200 return; 7201 case Intrinsic::set_fpmode: 7202 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 7203 getValue(I.getArgOperand(0))); 7204 DAG.setRoot(Res); 7205 return; 7206 case Intrinsic::reset_fpmode: { 7207 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 7208 DAG.setRoot(Res); 7209 return; 7210 } 7211 case Intrinsic::pcmarker: { 7212 SDValue Tmp = getValue(I.getArgOperand(0)); 7213 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 7214 return; 7215 } 7216 case Intrinsic::readcyclecounter: { 7217 SDValue Op = getRoot(); 7218 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 7219 DAG.getVTList(MVT::i64, MVT::Other), Op); 7220 setValue(&I, Res); 7221 DAG.setRoot(Res.getValue(1)); 7222 return; 7223 } 7224 case Intrinsic::readsteadycounter: { 7225 SDValue Op = getRoot(); 7226 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 7227 DAG.getVTList(MVT::i64, MVT::Other), Op); 7228 setValue(&I, Res); 7229 DAG.setRoot(Res.getValue(1)); 7230 return; 7231 } 7232 case Intrinsic::bitreverse: 7233 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 7234 getValue(I.getArgOperand(0)).getValueType(), 7235 getValue(I.getArgOperand(0)))); 7236 return; 7237 case Intrinsic::bswap: 7238 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 7239 getValue(I.getArgOperand(0)).getValueType(), 7240 getValue(I.getArgOperand(0)))); 7241 return; 7242 case Intrinsic::cttz: { 7243 SDValue Arg = getValue(I.getArgOperand(0)); 7244 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7245 EVT Ty = Arg.getValueType(); 7246 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 7247 sdl, Ty, Arg)); 7248 return; 7249 } 7250 case Intrinsic::ctlz: { 7251 SDValue Arg = getValue(I.getArgOperand(0)); 7252 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7253 EVT Ty = Arg.getValueType(); 7254 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 7255 sdl, Ty, Arg)); 7256 return; 7257 } 7258 case Intrinsic::ctpop: { 7259 SDValue Arg = getValue(I.getArgOperand(0)); 7260 EVT Ty = Arg.getValueType(); 7261 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 7262 return; 7263 } 7264 case Intrinsic::fshl: 7265 case Intrinsic::fshr: { 7266 bool IsFSHL = Intrinsic == Intrinsic::fshl; 7267 SDValue X = getValue(I.getArgOperand(0)); 7268 SDValue Y = getValue(I.getArgOperand(1)); 7269 SDValue Z = getValue(I.getArgOperand(2)); 7270 EVT VT = X.getValueType(); 7271 7272 if (X == Y) { 7273 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 7274 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 7275 } else { 7276 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 7277 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 7278 } 7279 return; 7280 } 7281 case Intrinsic::sadd_sat: { 7282 SDValue Op1 = getValue(I.getArgOperand(0)); 7283 SDValue Op2 = getValue(I.getArgOperand(1)); 7284 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7285 return; 7286 } 7287 case Intrinsic::uadd_sat: { 7288 SDValue Op1 = getValue(I.getArgOperand(0)); 7289 SDValue Op2 = getValue(I.getArgOperand(1)); 7290 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7291 return; 7292 } 7293 case Intrinsic::ssub_sat: { 7294 SDValue Op1 = getValue(I.getArgOperand(0)); 7295 SDValue Op2 = getValue(I.getArgOperand(1)); 7296 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7297 return; 7298 } 7299 case Intrinsic::usub_sat: { 7300 SDValue Op1 = getValue(I.getArgOperand(0)); 7301 SDValue Op2 = getValue(I.getArgOperand(1)); 7302 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7303 return; 7304 } 7305 case Intrinsic::sshl_sat: { 7306 SDValue Op1 = getValue(I.getArgOperand(0)); 7307 SDValue Op2 = getValue(I.getArgOperand(1)); 7308 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7309 return; 7310 } 7311 case Intrinsic::ushl_sat: { 7312 SDValue Op1 = getValue(I.getArgOperand(0)); 7313 SDValue Op2 = getValue(I.getArgOperand(1)); 7314 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7315 return; 7316 } 7317 case Intrinsic::smul_fix: 7318 case Intrinsic::umul_fix: 7319 case Intrinsic::smul_fix_sat: 7320 case Intrinsic::umul_fix_sat: { 7321 SDValue Op1 = getValue(I.getArgOperand(0)); 7322 SDValue Op2 = getValue(I.getArgOperand(1)); 7323 SDValue Op3 = getValue(I.getArgOperand(2)); 7324 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7325 Op1.getValueType(), Op1, Op2, Op3)); 7326 return; 7327 } 7328 case Intrinsic::sdiv_fix: 7329 case Intrinsic::udiv_fix: 7330 case Intrinsic::sdiv_fix_sat: 7331 case Intrinsic::udiv_fix_sat: { 7332 SDValue Op1 = getValue(I.getArgOperand(0)); 7333 SDValue Op2 = getValue(I.getArgOperand(1)); 7334 SDValue Op3 = getValue(I.getArgOperand(2)); 7335 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7336 Op1, Op2, Op3, DAG, TLI)); 7337 return; 7338 } 7339 case Intrinsic::smax: { 7340 SDValue Op1 = getValue(I.getArgOperand(0)); 7341 SDValue Op2 = getValue(I.getArgOperand(1)); 7342 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 7343 return; 7344 } 7345 case Intrinsic::smin: { 7346 SDValue Op1 = getValue(I.getArgOperand(0)); 7347 SDValue Op2 = getValue(I.getArgOperand(1)); 7348 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 7349 return; 7350 } 7351 case Intrinsic::umax: { 7352 SDValue Op1 = getValue(I.getArgOperand(0)); 7353 SDValue Op2 = getValue(I.getArgOperand(1)); 7354 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 7355 return; 7356 } 7357 case Intrinsic::umin: { 7358 SDValue Op1 = getValue(I.getArgOperand(0)); 7359 SDValue Op2 = getValue(I.getArgOperand(1)); 7360 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 7361 return; 7362 } 7363 case Intrinsic::abs: { 7364 // TODO: Preserve "int min is poison" arg in SDAG? 7365 SDValue Op1 = getValue(I.getArgOperand(0)); 7366 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 7367 return; 7368 } 7369 case Intrinsic::scmp: { 7370 SDValue Op1 = getValue(I.getArgOperand(0)); 7371 SDValue Op2 = getValue(I.getArgOperand(1)); 7372 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7373 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2)); 7374 break; 7375 } 7376 case Intrinsic::ucmp: { 7377 SDValue Op1 = getValue(I.getArgOperand(0)); 7378 SDValue Op2 = getValue(I.getArgOperand(1)); 7379 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7380 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2)); 7381 break; 7382 } 7383 case Intrinsic::stacksave: { 7384 SDValue Op = getRoot(); 7385 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7386 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 7387 setValue(&I, Res); 7388 DAG.setRoot(Res.getValue(1)); 7389 return; 7390 } 7391 case Intrinsic::stackrestore: 7392 Res = getValue(I.getArgOperand(0)); 7393 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 7394 return; 7395 case Intrinsic::get_dynamic_area_offset: { 7396 SDValue Op = getRoot(); 7397 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7398 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7399 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 7400 // target. 7401 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 7402 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 7403 " intrinsic!"); 7404 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 7405 Op); 7406 DAG.setRoot(Op); 7407 setValue(&I, Res); 7408 return; 7409 } 7410 case Intrinsic::stackguard: { 7411 MachineFunction &MF = DAG.getMachineFunction(); 7412 const Module &M = *MF.getFunction().getParent(); 7413 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7414 SDValue Chain = getRoot(); 7415 if (TLI.useLoadStackGuardNode(M)) { 7416 Res = getLoadStackGuard(DAG, sdl, Chain); 7417 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 7418 } else { 7419 const Value *Global = TLI.getSDagStackGuard(M); 7420 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7421 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7422 MachinePointerInfo(Global, 0), Align, 7423 MachineMemOperand::MOVolatile); 7424 } 7425 if (TLI.useStackGuardXorFP()) 7426 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7427 DAG.setRoot(Chain); 7428 setValue(&I, Res); 7429 return; 7430 } 7431 case Intrinsic::stackprotector: { 7432 // Emit code into the DAG to store the stack guard onto the stack. 7433 MachineFunction &MF = DAG.getMachineFunction(); 7434 MachineFrameInfo &MFI = MF.getFrameInfo(); 7435 const Module &M = *MF.getFunction().getParent(); 7436 SDValue Src, Chain = getRoot(); 7437 7438 if (TLI.useLoadStackGuardNode(M)) 7439 Src = getLoadStackGuard(DAG, sdl, Chain); 7440 else 7441 Src = getValue(I.getArgOperand(0)); // The guard's value. 7442 7443 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7444 7445 int FI = FuncInfo.StaticAllocaMap[Slot]; 7446 MFI.setStackProtectorIndex(FI); 7447 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7448 7449 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7450 7451 // Store the stack protector onto the stack. 7452 Res = DAG.getStore( 7453 Chain, sdl, Src, FIN, 7454 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7455 MaybeAlign(), MachineMemOperand::MOVolatile); 7456 setValue(&I, Res); 7457 DAG.setRoot(Res); 7458 return; 7459 } 7460 case Intrinsic::objectsize: 7461 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7462 7463 case Intrinsic::is_constant: 7464 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7465 7466 case Intrinsic::annotation: 7467 case Intrinsic::ptr_annotation: 7468 case Intrinsic::launder_invariant_group: 7469 case Intrinsic::strip_invariant_group: 7470 // Drop the intrinsic, but forward the value 7471 setValue(&I, getValue(I.getOperand(0))); 7472 return; 7473 7474 case Intrinsic::assume: 7475 case Intrinsic::experimental_noalias_scope_decl: 7476 case Intrinsic::var_annotation: 7477 case Intrinsic::sideeffect: 7478 // Discard annotate attributes, noalias scope declarations, assumptions, and 7479 // artificial side-effects. 7480 return; 7481 7482 case Intrinsic::codeview_annotation: { 7483 // Emit a label associated with this metadata. 7484 MachineFunction &MF = DAG.getMachineFunction(); 7485 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true); 7486 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7487 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7488 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7489 DAG.setRoot(Res); 7490 return; 7491 } 7492 7493 case Intrinsic::init_trampoline: { 7494 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7495 7496 SDValue Ops[6]; 7497 Ops[0] = getRoot(); 7498 Ops[1] = getValue(I.getArgOperand(0)); 7499 Ops[2] = getValue(I.getArgOperand(1)); 7500 Ops[3] = getValue(I.getArgOperand(2)); 7501 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7502 Ops[5] = DAG.getSrcValue(F); 7503 7504 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7505 7506 DAG.setRoot(Res); 7507 return; 7508 } 7509 case Intrinsic::adjust_trampoline: 7510 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7511 TLI.getPointerTy(DAG.getDataLayout()), 7512 getValue(I.getArgOperand(0)))); 7513 return; 7514 case Intrinsic::gcroot: { 7515 assert(DAG.getMachineFunction().getFunction().hasGC() && 7516 "only valid in functions with gc specified, enforced by Verifier"); 7517 assert(GFI && "implied by previous"); 7518 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7519 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7520 7521 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7522 GFI->addStackRoot(FI->getIndex(), TypeMap); 7523 return; 7524 } 7525 case Intrinsic::gcread: 7526 case Intrinsic::gcwrite: 7527 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7528 case Intrinsic::get_rounding: 7529 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7530 setValue(&I, Res); 7531 DAG.setRoot(Res.getValue(1)); 7532 return; 7533 7534 case Intrinsic::expect: 7535 case Intrinsic::expect_with_probability: 7536 // Just replace __builtin_expect(exp, c) and 7537 // __builtin_expect_with_probability(exp, c, p) with EXP. 7538 setValue(&I, getValue(I.getArgOperand(0))); 7539 return; 7540 7541 case Intrinsic::ubsantrap: 7542 case Intrinsic::debugtrap: 7543 case Intrinsic::trap: { 7544 StringRef TrapFuncName = 7545 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7546 if (TrapFuncName.empty()) { 7547 switch (Intrinsic) { 7548 case Intrinsic::trap: 7549 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7550 break; 7551 case Intrinsic::debugtrap: 7552 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7553 break; 7554 case Intrinsic::ubsantrap: 7555 DAG.setRoot(DAG.getNode( 7556 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7557 DAG.getTargetConstant( 7558 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7559 MVT::i32))); 7560 break; 7561 default: llvm_unreachable("unknown trap intrinsic"); 7562 } 7563 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(), 7564 I.hasFnAttr(Attribute::NoMerge)); 7565 return; 7566 } 7567 TargetLowering::ArgListTy Args; 7568 if (Intrinsic == Intrinsic::ubsantrap) { 7569 Args.push_back(TargetLoweringBase::ArgListEntry()); 7570 Args[0].Val = I.getArgOperand(0); 7571 Args[0].Node = getValue(Args[0].Val); 7572 Args[0].Ty = Args[0].Val->getType(); 7573 } 7574 7575 TargetLowering::CallLoweringInfo CLI(DAG); 7576 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7577 CallingConv::C, I.getType(), 7578 DAG.getExternalSymbol(TrapFuncName.data(), 7579 TLI.getPointerTy(DAG.getDataLayout())), 7580 std::move(Args)); 7581 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge); 7582 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7583 DAG.setRoot(Result.second); 7584 return; 7585 } 7586 7587 case Intrinsic::allow_runtime_check: 7588 case Intrinsic::allow_ubsan_check: 7589 setValue(&I, getValue(ConstantInt::getTrue(I.getType()))); 7590 return; 7591 7592 case Intrinsic::uadd_with_overflow: 7593 case Intrinsic::sadd_with_overflow: 7594 case Intrinsic::usub_with_overflow: 7595 case Intrinsic::ssub_with_overflow: 7596 case Intrinsic::umul_with_overflow: 7597 case Intrinsic::smul_with_overflow: { 7598 ISD::NodeType Op; 7599 switch (Intrinsic) { 7600 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7601 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7602 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7603 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7604 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7605 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7606 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7607 } 7608 SDValue Op1 = getValue(I.getArgOperand(0)); 7609 SDValue Op2 = getValue(I.getArgOperand(1)); 7610 7611 EVT ResultVT = Op1.getValueType(); 7612 EVT OverflowVT = MVT::i1; 7613 if (ResultVT.isVector()) 7614 OverflowVT = EVT::getVectorVT( 7615 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7616 7617 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7618 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7619 return; 7620 } 7621 case Intrinsic::prefetch: { 7622 SDValue Ops[5]; 7623 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7624 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7625 Ops[0] = DAG.getRoot(); 7626 Ops[1] = getValue(I.getArgOperand(0)); 7627 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7628 MVT::i32); 7629 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7630 MVT::i32); 7631 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7632 MVT::i32); 7633 SDValue Result = DAG.getMemIntrinsicNode( 7634 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7635 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7636 /* align */ std::nullopt, Flags); 7637 7638 // Chain the prefetch in parallel with any pending loads, to stay out of 7639 // the way of later optimizations. 7640 PendingLoads.push_back(Result); 7641 Result = getRoot(); 7642 DAG.setRoot(Result); 7643 return; 7644 } 7645 case Intrinsic::lifetime_start: 7646 case Intrinsic::lifetime_end: { 7647 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7648 // Stack coloring is not enabled in O0, discard region information. 7649 if (TM.getOptLevel() == CodeGenOptLevel::None) 7650 return; 7651 7652 const int64_t ObjectSize = 7653 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7654 Value *const ObjectPtr = I.getArgOperand(1); 7655 SmallVector<const Value *, 4> Allocas; 7656 getUnderlyingObjects(ObjectPtr, Allocas); 7657 7658 for (const Value *Alloca : Allocas) { 7659 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7660 7661 // Could not find an Alloca. 7662 if (!LifetimeObject) 7663 continue; 7664 7665 // First check that the Alloca is static, otherwise it won't have a 7666 // valid frame index. 7667 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7668 if (SI == FuncInfo.StaticAllocaMap.end()) 7669 return; 7670 7671 const int FrameIndex = SI->second; 7672 int64_t Offset; 7673 if (GetPointerBaseWithConstantOffset( 7674 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7675 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7676 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7677 Offset); 7678 DAG.setRoot(Res); 7679 } 7680 return; 7681 } 7682 case Intrinsic::pseudoprobe: { 7683 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7684 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7685 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7686 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7687 DAG.setRoot(Res); 7688 return; 7689 } 7690 case Intrinsic::invariant_start: 7691 // Discard region information. 7692 setValue(&I, 7693 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7694 return; 7695 case Intrinsic::invariant_end: 7696 // Discard region information. 7697 return; 7698 case Intrinsic::clear_cache: { 7699 SDValue InputChain = DAG.getRoot(); 7700 SDValue StartVal = getValue(I.getArgOperand(0)); 7701 SDValue EndVal = getValue(I.getArgOperand(1)); 7702 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other), 7703 {InputChain, StartVal, EndVal}); 7704 setValue(&I, Res); 7705 DAG.setRoot(Res); 7706 return; 7707 } 7708 case Intrinsic::donothing: 7709 case Intrinsic::seh_try_begin: 7710 case Intrinsic::seh_scope_begin: 7711 case Intrinsic::seh_try_end: 7712 case Intrinsic::seh_scope_end: 7713 // ignore 7714 return; 7715 case Intrinsic::experimental_stackmap: 7716 visitStackmap(I); 7717 return; 7718 case Intrinsic::experimental_patchpoint_void: 7719 case Intrinsic::experimental_patchpoint: 7720 visitPatchpoint(I); 7721 return; 7722 case Intrinsic::experimental_gc_statepoint: 7723 LowerStatepoint(cast<GCStatepointInst>(I)); 7724 return; 7725 case Intrinsic::experimental_gc_result: 7726 visitGCResult(cast<GCResultInst>(I)); 7727 return; 7728 case Intrinsic::experimental_gc_relocate: 7729 visitGCRelocate(cast<GCRelocateInst>(I)); 7730 return; 7731 case Intrinsic::instrprof_cover: 7732 llvm_unreachable("instrprof failed to lower a cover"); 7733 case Intrinsic::instrprof_increment: 7734 llvm_unreachable("instrprof failed to lower an increment"); 7735 case Intrinsic::instrprof_timestamp: 7736 llvm_unreachable("instrprof failed to lower a timestamp"); 7737 case Intrinsic::instrprof_value_profile: 7738 llvm_unreachable("instrprof failed to lower a value profiling call"); 7739 case Intrinsic::instrprof_mcdc_parameters: 7740 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7741 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7742 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7743 case Intrinsic::localescape: { 7744 MachineFunction &MF = DAG.getMachineFunction(); 7745 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7746 7747 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7748 // is the same on all targets. 7749 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7750 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7751 if (isa<ConstantPointerNull>(Arg)) 7752 continue; // Skip null pointers. They represent a hole in index space. 7753 AllocaInst *Slot = cast<AllocaInst>(Arg); 7754 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7755 "can only escape static allocas"); 7756 int FI = FuncInfo.StaticAllocaMap[Slot]; 7757 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol( 7758 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7759 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7760 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7761 .addSym(FrameAllocSym) 7762 .addFrameIndex(FI); 7763 } 7764 7765 return; 7766 } 7767 7768 case Intrinsic::localrecover: { 7769 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7770 MachineFunction &MF = DAG.getMachineFunction(); 7771 7772 // Get the symbol that defines the frame offset. 7773 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7774 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7775 unsigned IdxVal = 7776 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7777 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol( 7778 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7779 7780 Value *FP = I.getArgOperand(1); 7781 SDValue FPVal = getValue(FP); 7782 EVT PtrVT = FPVal.getValueType(); 7783 7784 // Create a MCSymbol for the label to avoid any target lowering 7785 // that would make this PC relative. 7786 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7787 SDValue OffsetVal = 7788 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7789 7790 // Add the offset to the FP. 7791 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7792 setValue(&I, Add); 7793 7794 return; 7795 } 7796 7797 case Intrinsic::fake_use: { 7798 Value *V = I.getArgOperand(0); 7799 SDValue Ops[2]; 7800 // For Values not declared or previously used in this basic block, the 7801 // NodeMap will not have an entry, and `getValue` will assert if V has no 7802 // valid register value. 7803 auto FakeUseValue = [&]() -> SDValue { 7804 SDValue &N = NodeMap[V]; 7805 if (N.getNode()) 7806 return N; 7807 7808 // If there's a virtual register allocated and initialized for this 7809 // value, use it. 7810 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 7811 return copyFromReg; 7812 // FIXME: Do we want to preserve constants? It seems pointless. 7813 if (isa<Constant>(V)) 7814 return getValue(V); 7815 return SDValue(); 7816 }(); 7817 if (!FakeUseValue || FakeUseValue.isUndef()) 7818 return; 7819 Ops[0] = getRoot(); 7820 Ops[1] = FakeUseValue; 7821 // Also, do not translate a fake use with an undef operand, or any other 7822 // empty SDValues. 7823 if (!Ops[1] || Ops[1].isUndef()) 7824 return; 7825 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops)); 7826 return; 7827 } 7828 7829 case Intrinsic::eh_exceptionpointer: 7830 case Intrinsic::eh_exceptioncode: { 7831 // Get the exception pointer vreg, copy from it, and resize it to fit. 7832 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7833 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7834 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7835 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7836 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7837 if (Intrinsic == Intrinsic::eh_exceptioncode) 7838 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7839 setValue(&I, N); 7840 return; 7841 } 7842 case Intrinsic::xray_customevent: { 7843 // Here we want to make sure that the intrinsic behaves as if it has a 7844 // specific calling convention. 7845 const auto &Triple = DAG.getTarget().getTargetTriple(); 7846 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7847 return; 7848 7849 SmallVector<SDValue, 8> Ops; 7850 7851 // We want to say that we always want the arguments in registers. 7852 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7853 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7854 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7855 SDValue Chain = getRoot(); 7856 Ops.push_back(LogEntryVal); 7857 Ops.push_back(StrSizeVal); 7858 Ops.push_back(Chain); 7859 7860 // We need to enforce the calling convention for the callsite, so that 7861 // argument ordering is enforced correctly, and that register allocation can 7862 // see that some registers may be assumed clobbered and have to preserve 7863 // them across calls to the intrinsic. 7864 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7865 sdl, NodeTys, Ops); 7866 SDValue patchableNode = SDValue(MN, 0); 7867 DAG.setRoot(patchableNode); 7868 setValue(&I, patchableNode); 7869 return; 7870 } 7871 case Intrinsic::xray_typedevent: { 7872 // Here we want to make sure that the intrinsic behaves as if it has a 7873 // specific calling convention. 7874 const auto &Triple = DAG.getTarget().getTargetTriple(); 7875 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7876 return; 7877 7878 SmallVector<SDValue, 8> Ops; 7879 7880 // We want to say that we always want the arguments in registers. 7881 // It's unclear to me how manipulating the selection DAG here forces callers 7882 // to provide arguments in registers instead of on the stack. 7883 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7884 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7885 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7886 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7887 SDValue Chain = getRoot(); 7888 Ops.push_back(LogTypeId); 7889 Ops.push_back(LogEntryVal); 7890 Ops.push_back(StrSizeVal); 7891 Ops.push_back(Chain); 7892 7893 // We need to enforce the calling convention for the callsite, so that 7894 // argument ordering is enforced correctly, and that register allocation can 7895 // see that some registers may be assumed clobbered and have to preserve 7896 // them across calls to the intrinsic. 7897 MachineSDNode *MN = DAG.getMachineNode( 7898 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7899 SDValue patchableNode = SDValue(MN, 0); 7900 DAG.setRoot(patchableNode); 7901 setValue(&I, patchableNode); 7902 return; 7903 } 7904 case Intrinsic::experimental_deoptimize: 7905 LowerDeoptimizeCall(&I); 7906 return; 7907 case Intrinsic::stepvector: 7908 visitStepVector(I); 7909 return; 7910 case Intrinsic::vector_reduce_fadd: 7911 case Intrinsic::vector_reduce_fmul: 7912 case Intrinsic::vector_reduce_add: 7913 case Intrinsic::vector_reduce_mul: 7914 case Intrinsic::vector_reduce_and: 7915 case Intrinsic::vector_reduce_or: 7916 case Intrinsic::vector_reduce_xor: 7917 case Intrinsic::vector_reduce_smax: 7918 case Intrinsic::vector_reduce_smin: 7919 case Intrinsic::vector_reduce_umax: 7920 case Intrinsic::vector_reduce_umin: 7921 case Intrinsic::vector_reduce_fmax: 7922 case Intrinsic::vector_reduce_fmin: 7923 case Intrinsic::vector_reduce_fmaximum: 7924 case Intrinsic::vector_reduce_fminimum: 7925 visitVectorReduce(I, Intrinsic); 7926 return; 7927 7928 case Intrinsic::icall_branch_funnel: { 7929 SmallVector<SDValue, 16> Ops; 7930 Ops.push_back(getValue(I.getArgOperand(0))); 7931 7932 int64_t Offset; 7933 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7934 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7935 if (!Base) 7936 report_fatal_error( 7937 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7938 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7939 7940 struct BranchFunnelTarget { 7941 int64_t Offset; 7942 SDValue Target; 7943 }; 7944 SmallVector<BranchFunnelTarget, 8> Targets; 7945 7946 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7947 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7948 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7949 if (ElemBase != Base) 7950 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7951 "to the same GlobalValue"); 7952 7953 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7954 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7955 if (!GA) 7956 report_fatal_error( 7957 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7958 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7959 GA->getGlobal(), sdl, Val.getValueType(), 7960 GA->getOffset())}); 7961 } 7962 llvm::sort(Targets, 7963 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7964 return T1.Offset < T2.Offset; 7965 }); 7966 7967 for (auto &T : Targets) { 7968 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7969 Ops.push_back(T.Target); 7970 } 7971 7972 Ops.push_back(DAG.getRoot()); // Chain 7973 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7974 MVT::Other, Ops), 7975 0); 7976 DAG.setRoot(N); 7977 setValue(&I, N); 7978 HasTailCall = true; 7979 return; 7980 } 7981 7982 case Intrinsic::wasm_landingpad_index: 7983 // Information this intrinsic contained has been transferred to 7984 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7985 // delete it now. 7986 return; 7987 7988 case Intrinsic::aarch64_settag: 7989 case Intrinsic::aarch64_settag_zero: { 7990 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7991 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7992 SDValue Val = TSI.EmitTargetCodeForSetTag( 7993 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7994 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7995 ZeroMemory); 7996 DAG.setRoot(Val); 7997 setValue(&I, Val); 7998 return; 7999 } 8000 case Intrinsic::amdgcn_cs_chain: { 8001 assert(I.arg_size() == 5 && "Additional args not supported yet"); 8002 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 8003 "Non-zero flags not supported yet"); 8004 8005 // At this point we don't care if it's amdgpu_cs_chain or 8006 // amdgpu_cs_chain_preserve. 8007 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 8008 8009 Type *RetTy = I.getType(); 8010 assert(RetTy->isVoidTy() && "Should not return"); 8011 8012 SDValue Callee = getValue(I.getOperand(0)); 8013 8014 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 8015 // We'll also tack the value of the EXEC mask at the end. 8016 TargetLowering::ArgListTy Args; 8017 Args.reserve(3); 8018 8019 for (unsigned Idx : {2, 3, 1}) { 8020 TargetLowering::ArgListEntry Arg; 8021 Arg.Node = getValue(I.getOperand(Idx)); 8022 Arg.Ty = I.getOperand(Idx)->getType(); 8023 Arg.setAttributes(&I, Idx); 8024 Args.push_back(Arg); 8025 } 8026 8027 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 8028 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 8029 Args[2].IsInReg = true; // EXEC should be inreg 8030 8031 TargetLowering::CallLoweringInfo CLI(DAG); 8032 CLI.setDebugLoc(getCurSDLoc()) 8033 .setChain(getRoot()) 8034 .setCallee(CC, RetTy, Callee, std::move(Args)) 8035 .setNoReturn(true) 8036 .setTailCall(true) 8037 .setConvergent(I.isConvergent()); 8038 CLI.CB = &I; 8039 std::pair<SDValue, SDValue> Result = 8040 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 8041 (void)Result; 8042 assert(!Result.first.getNode() && !Result.second.getNode() && 8043 "Should've lowered as tail call"); 8044 8045 HasTailCall = true; 8046 return; 8047 } 8048 case Intrinsic::ptrmask: { 8049 SDValue Ptr = getValue(I.getOperand(0)); 8050 SDValue Mask = getValue(I.getOperand(1)); 8051 8052 // On arm64_32, pointers are 32 bits when stored in memory, but 8053 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to 8054 // match the index type, but the pointer is 64 bits, so the the mask must be 8055 // zero-extended up to 64 bits to match the pointer. 8056 EVT PtrVT = 8057 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 8058 EVT MemVT = 8059 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 8060 assert(PtrVT == Ptr.getValueType()); 8061 assert(MemVT == Mask.getValueType()); 8062 if (MemVT != PtrVT) 8063 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT); 8064 8065 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 8066 return; 8067 } 8068 case Intrinsic::threadlocal_address: { 8069 setValue(&I, getValue(I.getOperand(0))); 8070 return; 8071 } 8072 case Intrinsic::get_active_lane_mask: { 8073 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8074 SDValue Index = getValue(I.getOperand(0)); 8075 EVT ElementVT = Index.getValueType(); 8076 8077 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 8078 visitTargetIntrinsic(I, Intrinsic); 8079 return; 8080 } 8081 8082 SDValue TripCount = getValue(I.getOperand(1)); 8083 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 8084 CCVT.getVectorElementCount()); 8085 8086 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 8087 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 8088 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 8089 SDValue VectorInduction = DAG.getNode( 8090 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 8091 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 8092 VectorTripCount, ISD::CondCode::SETULT); 8093 setValue(&I, SetCC); 8094 return; 8095 } 8096 case Intrinsic::experimental_get_vector_length: { 8097 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 8098 "Expected positive VF"); 8099 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 8100 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 8101 8102 SDValue Count = getValue(I.getOperand(0)); 8103 EVT CountVT = Count.getValueType(); 8104 8105 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 8106 visitTargetIntrinsic(I, Intrinsic); 8107 return; 8108 } 8109 8110 // Expand to a umin between the trip count and the maximum elements the type 8111 // can hold. 8112 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8113 8114 // Extend the trip count to at least the result VT. 8115 if (CountVT.bitsLT(VT)) { 8116 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 8117 CountVT = VT; 8118 } 8119 8120 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 8121 ElementCount::get(VF, IsScalable)); 8122 8123 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 8124 // Clip to the result type if needed. 8125 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 8126 8127 setValue(&I, Trunc); 8128 return; 8129 } 8130 case Intrinsic::experimental_vector_partial_reduce_add: { 8131 8132 if (!TLI.shouldExpandPartialReductionIntrinsic(cast<IntrinsicInst>(&I))) { 8133 visitTargetIntrinsic(I, Intrinsic); 8134 return; 8135 } 8136 8137 setValue(&I, DAG.getPartialReduceAdd(sdl, EVT::getEVT(I.getType()), 8138 getValue(I.getOperand(0)), 8139 getValue(I.getOperand(1)))); 8140 return; 8141 } 8142 case Intrinsic::experimental_cttz_elts: { 8143 auto DL = getCurSDLoc(); 8144 SDValue Op = getValue(I.getOperand(0)); 8145 EVT OpVT = Op.getValueType(); 8146 8147 if (!TLI.shouldExpandCttzElements(OpVT)) { 8148 visitTargetIntrinsic(I, Intrinsic); 8149 return; 8150 } 8151 8152 if (OpVT.getScalarType() != MVT::i1) { 8153 // Compare the input vector elements to zero & use to count trailing zeros 8154 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 8155 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 8156 OpVT.getVectorElementCount()); 8157 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 8158 } 8159 8160 // If the zero-is-poison flag is set, we can assume the upper limit 8161 // of the result is VF-1. 8162 bool ZeroIsPoison = 8163 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero(); 8164 ConstantRange VScaleRange(1, true); // Dummy value. 8165 if (isa<ScalableVectorType>(I.getOperand(0)->getType())) 8166 VScaleRange = getVScaleRange(I.getCaller(), 64); 8167 unsigned EltWidth = TLI.getBitWidthForCttzElements( 8168 I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange); 8169 8170 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 8171 8172 // Create the new vector type & get the vector length 8173 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 8174 OpVT.getVectorElementCount()); 8175 8176 SDValue VL = 8177 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 8178 8179 SDValue StepVec = DAG.getStepVector(DL, NewVT); 8180 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 8181 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 8182 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 8183 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 8184 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 8185 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 8186 8187 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8188 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 8189 8190 setValue(&I, Ret); 8191 return; 8192 } 8193 case Intrinsic::vector_insert: { 8194 SDValue Vec = getValue(I.getOperand(0)); 8195 SDValue SubVec = getValue(I.getOperand(1)); 8196 SDValue Index = getValue(I.getOperand(2)); 8197 8198 // The intrinsic's index type is i64, but the SDNode requires an index type 8199 // suitable for the target. Convert the index as required. 8200 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8201 if (Index.getValueType() != VectorIdxTy) 8202 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 8203 8204 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8205 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 8206 Index)); 8207 return; 8208 } 8209 case Intrinsic::vector_extract: { 8210 SDValue Vec = getValue(I.getOperand(0)); 8211 SDValue Index = getValue(I.getOperand(1)); 8212 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8213 8214 // The intrinsic's index type is i64, but the SDNode requires an index type 8215 // suitable for the target. Convert the index as required. 8216 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8217 if (Index.getValueType() != VectorIdxTy) 8218 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 8219 8220 setValue(&I, 8221 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 8222 return; 8223 } 8224 case Intrinsic::experimental_vector_match: { 8225 SDValue Op1 = getValue(I.getOperand(0)); 8226 SDValue Op2 = getValue(I.getOperand(1)); 8227 SDValue Mask = getValue(I.getOperand(2)); 8228 EVT Op1VT = Op1.getValueType(); 8229 EVT Op2VT = Op2.getValueType(); 8230 EVT ResVT = Mask.getValueType(); 8231 unsigned SearchSize = Op2VT.getVectorNumElements(); 8232 8233 // If the target has native support for this vector match operation, lower 8234 // the intrinsic untouched; otherwise, expand it below. 8235 if (!TLI.shouldExpandVectorMatch(Op1VT, SearchSize)) { 8236 visitTargetIntrinsic(I, Intrinsic); 8237 return; 8238 } 8239 8240 SDValue Ret = DAG.getConstant(0, sdl, ResVT); 8241 8242 for (unsigned i = 0; i < SearchSize; ++i) { 8243 SDValue Op2Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, 8244 Op2VT.getVectorElementType(), Op2, 8245 DAG.getVectorIdxConstant(i, sdl)); 8246 SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, sdl, Op1VT, Op2Elem); 8247 SDValue Cmp = DAG.getSetCC(sdl, ResVT, Op1, Splat, ISD::SETEQ); 8248 Ret = DAG.getNode(ISD::OR, sdl, ResVT, Ret, Cmp); 8249 } 8250 8251 setValue(&I, DAG.getNode(ISD::AND, sdl, ResVT, Ret, Mask)); 8252 return; 8253 } 8254 case Intrinsic::vector_reverse: 8255 visitVectorReverse(I); 8256 return; 8257 case Intrinsic::vector_splice: 8258 visitVectorSplice(I); 8259 return; 8260 case Intrinsic::callbr_landingpad: 8261 visitCallBrLandingPad(I); 8262 return; 8263 case Intrinsic::vector_interleave2: 8264 visitVectorInterleave(I); 8265 return; 8266 case Intrinsic::vector_deinterleave2: 8267 visitVectorDeinterleave(I); 8268 return; 8269 case Intrinsic::experimental_vector_compress: 8270 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl, 8271 getValue(I.getArgOperand(0)).getValueType(), 8272 getValue(I.getArgOperand(0)), 8273 getValue(I.getArgOperand(1)), 8274 getValue(I.getArgOperand(2)), Flags)); 8275 return; 8276 case Intrinsic::experimental_convergence_anchor: 8277 case Intrinsic::experimental_convergence_entry: 8278 case Intrinsic::experimental_convergence_loop: 8279 visitConvergenceControl(I, Intrinsic); 8280 return; 8281 case Intrinsic::experimental_vector_histogram_add: { 8282 visitVectorHistogram(I, Intrinsic); 8283 return; 8284 } 8285 case Intrinsic::experimental_vector_extract_last_active: { 8286 visitVectorExtractLastActive(I, Intrinsic); 8287 return; 8288 } 8289 } 8290 } 8291 8292 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 8293 const ConstrainedFPIntrinsic &FPI) { 8294 SDLoc sdl = getCurSDLoc(); 8295 8296 // We do not need to serialize constrained FP intrinsics against 8297 // each other or against (nonvolatile) loads, so they can be 8298 // chained like loads. 8299 SDValue Chain = DAG.getRoot(); 8300 SmallVector<SDValue, 4> Opers; 8301 Opers.push_back(Chain); 8302 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I) 8303 Opers.push_back(getValue(FPI.getArgOperand(I))); 8304 8305 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 8306 assert(Result.getNode()->getNumValues() == 2); 8307 8308 // Push node to the appropriate list so that future instructions can be 8309 // chained up correctly. 8310 SDValue OutChain = Result.getValue(1); 8311 switch (EB) { 8312 case fp::ExceptionBehavior::ebIgnore: 8313 // The only reason why ebIgnore nodes still need to be chained is that 8314 // they might depend on the current rounding mode, and therefore must 8315 // not be moved across instruction that may change that mode. 8316 [[fallthrough]]; 8317 case fp::ExceptionBehavior::ebMayTrap: 8318 // These must not be moved across calls or instructions that may change 8319 // floating-point exception masks. 8320 PendingConstrainedFP.push_back(OutChain); 8321 break; 8322 case fp::ExceptionBehavior::ebStrict: 8323 // These must not be moved across calls or instructions that may change 8324 // floating-point exception masks or read floating-point exception flags. 8325 // In addition, they cannot be optimized out even if unused. 8326 PendingConstrainedFPStrict.push_back(OutChain); 8327 break; 8328 } 8329 }; 8330 8331 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8332 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 8333 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 8334 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 8335 8336 SDNodeFlags Flags; 8337 if (EB == fp::ExceptionBehavior::ebIgnore) 8338 Flags.setNoFPExcept(true); 8339 8340 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 8341 Flags.copyFMF(*FPOp); 8342 8343 unsigned Opcode; 8344 switch (FPI.getIntrinsicID()) { 8345 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8346 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8347 case Intrinsic::INTRINSIC: \ 8348 Opcode = ISD::STRICT_##DAGN; \ 8349 break; 8350 #include "llvm/IR/ConstrainedOps.def" 8351 case Intrinsic::experimental_constrained_fmuladd: { 8352 Opcode = ISD::STRICT_FMA; 8353 // Break fmuladd into fmul and fadd. 8354 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 8355 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 8356 Opers.pop_back(); 8357 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 8358 pushOutChain(Mul, EB); 8359 Opcode = ISD::STRICT_FADD; 8360 Opers.clear(); 8361 Opers.push_back(Mul.getValue(1)); 8362 Opers.push_back(Mul.getValue(0)); 8363 Opers.push_back(getValue(FPI.getArgOperand(2))); 8364 } 8365 break; 8366 } 8367 } 8368 8369 // A few strict DAG nodes carry additional operands that are not 8370 // set up by the default code above. 8371 switch (Opcode) { 8372 default: break; 8373 case ISD::STRICT_FP_ROUND: 8374 Opers.push_back( 8375 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 8376 break; 8377 case ISD::STRICT_FSETCC: 8378 case ISD::STRICT_FSETCCS: { 8379 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 8380 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 8381 if (TM.Options.NoNaNsFPMath) 8382 Condition = getFCmpCodeWithoutNaN(Condition); 8383 Opers.push_back(DAG.getCondCode(Condition)); 8384 break; 8385 } 8386 } 8387 8388 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 8389 pushOutChain(Result, EB); 8390 8391 SDValue FPResult = Result.getValue(0); 8392 setValue(&FPI, FPResult); 8393 } 8394 8395 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 8396 std::optional<unsigned> ResOPC; 8397 switch (VPIntrin.getIntrinsicID()) { 8398 case Intrinsic::vp_ctlz: { 8399 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8400 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 8401 break; 8402 } 8403 case Intrinsic::vp_cttz: { 8404 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8405 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 8406 break; 8407 } 8408 case Intrinsic::vp_cttz_elts: { 8409 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8410 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS; 8411 break; 8412 } 8413 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 8414 case Intrinsic::VPID: \ 8415 ResOPC = ISD::VPSD; \ 8416 break; 8417 #include "llvm/IR/VPIntrinsics.def" 8418 } 8419 8420 if (!ResOPC) 8421 llvm_unreachable( 8422 "Inconsistency: no SDNode available for this VPIntrinsic!"); 8423 8424 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 8425 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 8426 if (VPIntrin.getFastMathFlags().allowReassoc()) 8427 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 8428 : ISD::VP_REDUCE_FMUL; 8429 } 8430 8431 return *ResOPC; 8432 } 8433 8434 void SelectionDAGBuilder::visitVPLoad( 8435 const VPIntrinsic &VPIntrin, EVT VT, 8436 const SmallVectorImpl<SDValue> &OpValues) { 8437 SDLoc DL = getCurSDLoc(); 8438 Value *PtrOperand = VPIntrin.getArgOperand(0); 8439 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8440 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8441 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8442 SDValue LD; 8443 // Do not serialize variable-length loads of constant memory with 8444 // anything. 8445 if (!Alignment) 8446 Alignment = DAG.getEVTAlign(VT); 8447 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8448 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8449 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8450 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8451 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8452 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8453 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 8454 MMO, false /*IsExpanding */); 8455 if (AddToChain) 8456 PendingLoads.push_back(LD.getValue(1)); 8457 setValue(&VPIntrin, LD); 8458 } 8459 8460 void SelectionDAGBuilder::visitVPGather( 8461 const VPIntrinsic &VPIntrin, EVT VT, 8462 const SmallVectorImpl<SDValue> &OpValues) { 8463 SDLoc DL = getCurSDLoc(); 8464 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8465 Value *PtrOperand = VPIntrin.getArgOperand(0); 8466 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8467 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8468 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8469 SDValue LD; 8470 if (!Alignment) 8471 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8472 unsigned AS = 8473 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8474 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8475 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8476 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8477 SDValue Base, Index, Scale; 8478 ISD::MemIndexType IndexType; 8479 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8480 this, VPIntrin.getParent(), 8481 VT.getScalarStoreSize()); 8482 if (!UniformBase) { 8483 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8484 Index = getValue(PtrOperand); 8485 IndexType = ISD::SIGNED_SCALED; 8486 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8487 } 8488 EVT IdxVT = Index.getValueType(); 8489 EVT EltTy = IdxVT.getVectorElementType(); 8490 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8491 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8492 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8493 } 8494 LD = DAG.getGatherVP( 8495 DAG.getVTList(VT, MVT::Other), VT, DL, 8496 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 8497 IndexType); 8498 PendingLoads.push_back(LD.getValue(1)); 8499 setValue(&VPIntrin, LD); 8500 } 8501 8502 void SelectionDAGBuilder::visitVPStore( 8503 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8504 SDLoc DL = getCurSDLoc(); 8505 Value *PtrOperand = VPIntrin.getArgOperand(1); 8506 EVT VT = OpValues[0].getValueType(); 8507 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8508 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8509 SDValue ST; 8510 if (!Alignment) 8511 Alignment = DAG.getEVTAlign(VT); 8512 SDValue Ptr = OpValues[1]; 8513 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 8514 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8515 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8516 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8517 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 8518 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 8519 /* IsTruncating */ false, /*IsCompressing*/ false); 8520 DAG.setRoot(ST); 8521 setValue(&VPIntrin, ST); 8522 } 8523 8524 void SelectionDAGBuilder::visitVPScatter( 8525 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8526 SDLoc DL = getCurSDLoc(); 8527 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8528 Value *PtrOperand = VPIntrin.getArgOperand(1); 8529 EVT VT = OpValues[0].getValueType(); 8530 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8531 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8532 SDValue ST; 8533 if (!Alignment) 8534 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8535 unsigned AS = 8536 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8537 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8538 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8539 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8540 SDValue Base, Index, Scale; 8541 ISD::MemIndexType IndexType; 8542 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8543 this, VPIntrin.getParent(), 8544 VT.getScalarStoreSize()); 8545 if (!UniformBase) { 8546 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8547 Index = getValue(PtrOperand); 8548 IndexType = ISD::SIGNED_SCALED; 8549 Scale = 8550 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8551 } 8552 EVT IdxVT = Index.getValueType(); 8553 EVT EltTy = IdxVT.getVectorElementType(); 8554 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8555 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8556 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8557 } 8558 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8559 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8560 OpValues[2], OpValues[3]}, 8561 MMO, IndexType); 8562 DAG.setRoot(ST); 8563 setValue(&VPIntrin, ST); 8564 } 8565 8566 void SelectionDAGBuilder::visitVPStridedLoad( 8567 const VPIntrinsic &VPIntrin, EVT VT, 8568 const SmallVectorImpl<SDValue> &OpValues) { 8569 SDLoc DL = getCurSDLoc(); 8570 Value *PtrOperand = VPIntrin.getArgOperand(0); 8571 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8572 if (!Alignment) 8573 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8574 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8575 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8576 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8577 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8578 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8579 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8580 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8581 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8582 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8583 8584 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8585 OpValues[2], OpValues[3], MMO, 8586 false /*IsExpanding*/); 8587 8588 if (AddToChain) 8589 PendingLoads.push_back(LD.getValue(1)); 8590 setValue(&VPIntrin, LD); 8591 } 8592 8593 void SelectionDAGBuilder::visitVPStridedStore( 8594 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8595 SDLoc DL = getCurSDLoc(); 8596 Value *PtrOperand = VPIntrin.getArgOperand(1); 8597 EVT VT = OpValues[0].getValueType(); 8598 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8599 if (!Alignment) 8600 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8601 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8602 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8603 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8604 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8605 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8606 8607 SDValue ST = DAG.getStridedStoreVP( 8608 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8609 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8610 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8611 /*IsCompressing*/ false); 8612 8613 DAG.setRoot(ST); 8614 setValue(&VPIntrin, ST); 8615 } 8616 8617 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8618 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8619 SDLoc DL = getCurSDLoc(); 8620 8621 ISD::CondCode Condition; 8622 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8623 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8624 if (IsFP) { 8625 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8626 // flags, but calls that don't return floating-point types can't be 8627 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8628 Condition = getFCmpCondCode(CondCode); 8629 if (TM.Options.NoNaNsFPMath) 8630 Condition = getFCmpCodeWithoutNaN(Condition); 8631 } else { 8632 Condition = getICmpCondCode(CondCode); 8633 } 8634 8635 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8636 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8637 // #2 is the condition code 8638 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8639 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8640 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8641 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8642 "Unexpected target EVL type"); 8643 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8644 8645 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8646 VPIntrin.getType()); 8647 setValue(&VPIntrin, 8648 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8649 } 8650 8651 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8652 const VPIntrinsic &VPIntrin) { 8653 SDLoc DL = getCurSDLoc(); 8654 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8655 8656 auto IID = VPIntrin.getIntrinsicID(); 8657 8658 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8659 return visitVPCmp(*CmpI); 8660 8661 SmallVector<EVT, 4> ValueVTs; 8662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8663 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8664 SDVTList VTs = DAG.getVTList(ValueVTs); 8665 8666 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8667 8668 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8669 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8670 "Unexpected target EVL type"); 8671 8672 // Request operands. 8673 SmallVector<SDValue, 7> OpValues; 8674 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8675 auto Op = getValue(VPIntrin.getArgOperand(I)); 8676 if (I == EVLParamPos) 8677 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8678 OpValues.push_back(Op); 8679 } 8680 8681 switch (Opcode) { 8682 default: { 8683 SDNodeFlags SDFlags; 8684 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8685 SDFlags.copyFMF(*FPMO); 8686 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8687 setValue(&VPIntrin, Result); 8688 break; 8689 } 8690 case ISD::VP_LOAD: 8691 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8692 break; 8693 case ISD::VP_GATHER: 8694 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8695 break; 8696 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8697 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8698 break; 8699 case ISD::VP_STORE: 8700 visitVPStore(VPIntrin, OpValues); 8701 break; 8702 case ISD::VP_SCATTER: 8703 visitVPScatter(VPIntrin, OpValues); 8704 break; 8705 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8706 visitVPStridedStore(VPIntrin, OpValues); 8707 break; 8708 case ISD::VP_FMULADD: { 8709 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8710 SDNodeFlags SDFlags; 8711 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8712 SDFlags.copyFMF(*FPMO); 8713 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8714 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8715 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8716 } else { 8717 SDValue Mul = DAG.getNode( 8718 ISD::VP_FMUL, DL, VTs, 8719 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8720 SDValue Add = 8721 DAG.getNode(ISD::VP_FADD, DL, VTs, 8722 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8723 setValue(&VPIntrin, Add); 8724 } 8725 break; 8726 } 8727 case ISD::VP_IS_FPCLASS: { 8728 const DataLayout DLayout = DAG.getDataLayout(); 8729 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8730 auto Constant = OpValues[1]->getAsZExtVal(); 8731 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8732 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8733 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8734 setValue(&VPIntrin, V); 8735 return; 8736 } 8737 case ISD::VP_INTTOPTR: { 8738 SDValue N = OpValues[0]; 8739 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8740 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8741 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8742 OpValues[2]); 8743 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8744 OpValues[2]); 8745 setValue(&VPIntrin, N); 8746 break; 8747 } 8748 case ISD::VP_PTRTOINT: { 8749 SDValue N = OpValues[0]; 8750 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8751 VPIntrin.getType()); 8752 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8753 VPIntrin.getOperand(0)->getType()); 8754 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8755 OpValues[2]); 8756 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8757 OpValues[2]); 8758 setValue(&VPIntrin, N); 8759 break; 8760 } 8761 case ISD::VP_ABS: 8762 case ISD::VP_CTLZ: 8763 case ISD::VP_CTLZ_ZERO_UNDEF: 8764 case ISD::VP_CTTZ: 8765 case ISD::VP_CTTZ_ZERO_UNDEF: 8766 case ISD::VP_CTTZ_ELTS_ZERO_UNDEF: 8767 case ISD::VP_CTTZ_ELTS: { 8768 SDValue Result = 8769 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8770 setValue(&VPIntrin, Result); 8771 break; 8772 } 8773 } 8774 } 8775 8776 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8777 const BasicBlock *EHPadBB, 8778 MCSymbol *&BeginLabel) { 8779 MachineFunction &MF = DAG.getMachineFunction(); 8780 8781 // Insert a label before the invoke call to mark the try range. This can be 8782 // used to detect deletion of the invoke via the MachineModuleInfo. 8783 BeginLabel = MF.getContext().createTempSymbol(); 8784 8785 // For SjLj, keep track of which landing pads go with which invokes 8786 // so as to maintain the ordering of pads in the LSDA. 8787 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite(); 8788 if (CallSiteIndex) { 8789 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8790 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex); 8791 8792 // Now that the call site is handled, stop tracking it. 8793 FuncInfo.setCurrentCallSite(0); 8794 } 8795 8796 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8797 } 8798 8799 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8800 const BasicBlock *EHPadBB, 8801 MCSymbol *BeginLabel) { 8802 assert(BeginLabel && "BeginLabel should've been set"); 8803 8804 MachineFunction &MF = DAG.getMachineFunction(); 8805 8806 // Insert a label at the end of the invoke call to mark the try range. This 8807 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8808 MCSymbol *EndLabel = MF.getContext().createTempSymbol(); 8809 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8810 8811 // Inform MachineModuleInfo of range. 8812 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8813 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8814 // actually use outlined funclets and their LSDA info style. 8815 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8816 assert(II && "II should've been set"); 8817 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8818 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8819 } else if (!isScopedEHPersonality(Pers)) { 8820 assert(EHPadBB); 8821 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel); 8822 } 8823 8824 return Chain; 8825 } 8826 8827 std::pair<SDValue, SDValue> 8828 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8829 const BasicBlock *EHPadBB) { 8830 MCSymbol *BeginLabel = nullptr; 8831 8832 if (EHPadBB) { 8833 // Both PendingLoads and PendingExports must be flushed here; 8834 // this call might not return. 8835 (void)getRoot(); 8836 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8837 CLI.setChain(getRoot()); 8838 } 8839 8840 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8841 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8842 8843 assert((CLI.IsTailCall || Result.second.getNode()) && 8844 "Non-null chain expected with non-tail call!"); 8845 assert((Result.second.getNode() || !Result.first.getNode()) && 8846 "Null value expected with tail call!"); 8847 8848 if (!Result.second.getNode()) { 8849 // As a special case, a null chain means that a tail call has been emitted 8850 // and the DAG root is already updated. 8851 HasTailCall = true; 8852 8853 // Since there's no actual continuation from this block, nothing can be 8854 // relying on us setting vregs for them. 8855 PendingExports.clear(); 8856 } else { 8857 DAG.setRoot(Result.second); 8858 } 8859 8860 if (EHPadBB) { 8861 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8862 BeginLabel)); 8863 Result.second = getRoot(); 8864 } 8865 8866 return Result; 8867 } 8868 8869 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8870 bool isTailCall, bool isMustTailCall, 8871 const BasicBlock *EHPadBB, 8872 const TargetLowering::PtrAuthInfo *PAI) { 8873 auto &DL = DAG.getDataLayout(); 8874 FunctionType *FTy = CB.getFunctionType(); 8875 Type *RetTy = CB.getType(); 8876 8877 TargetLowering::ArgListTy Args; 8878 Args.reserve(CB.arg_size()); 8879 8880 const Value *SwiftErrorVal = nullptr; 8881 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8882 8883 if (isTailCall) { 8884 // Avoid emitting tail calls in functions with the disable-tail-calls 8885 // attribute. 8886 auto *Caller = CB.getParent()->getParent(); 8887 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8888 "true" && !isMustTailCall) 8889 isTailCall = false; 8890 8891 // We can't tail call inside a function with a swifterror argument. Lowering 8892 // does not support this yet. It would have to move into the swifterror 8893 // register before the call. 8894 if (TLI.supportSwiftError() && 8895 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8896 isTailCall = false; 8897 } 8898 8899 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8900 TargetLowering::ArgListEntry Entry; 8901 const Value *V = *I; 8902 8903 // Skip empty types 8904 if (V->getType()->isEmptyTy()) 8905 continue; 8906 8907 SDValue ArgNode = getValue(V); 8908 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8909 8910 Entry.setAttributes(&CB, I - CB.arg_begin()); 8911 8912 // Use swifterror virtual register as input to the call. 8913 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8914 SwiftErrorVal = V; 8915 // We find the virtual register for the actual swifterror argument. 8916 // Instead of using the Value, we use the virtual register instead. 8917 Entry.Node = 8918 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8919 EVT(TLI.getPointerTy(DL))); 8920 } 8921 8922 Args.push_back(Entry); 8923 8924 // If we have an explicit sret argument that is an Instruction, (i.e., it 8925 // might point to function-local memory), we can't meaningfully tail-call. 8926 if (Entry.IsSRet && isa<Instruction>(V)) 8927 isTailCall = false; 8928 } 8929 8930 // If call site has a cfguardtarget operand bundle, create and add an 8931 // additional ArgListEntry. 8932 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8933 TargetLowering::ArgListEntry Entry; 8934 Value *V = Bundle->Inputs[0]; 8935 SDValue ArgNode = getValue(V); 8936 Entry.Node = ArgNode; 8937 Entry.Ty = V->getType(); 8938 Entry.IsCFGuardTarget = true; 8939 Args.push_back(Entry); 8940 } 8941 8942 // Check if target-independent constraints permit a tail call here. 8943 // Target-dependent constraints are checked within TLI->LowerCallTo. 8944 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8945 isTailCall = false; 8946 8947 // Disable tail calls if there is an swifterror argument. Targets have not 8948 // been updated to support tail calls. 8949 if (TLI.supportSwiftError() && SwiftErrorVal) 8950 isTailCall = false; 8951 8952 ConstantInt *CFIType = nullptr; 8953 if (CB.isIndirectCall()) { 8954 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8955 if (!TLI.supportKCFIBundles()) 8956 report_fatal_error( 8957 "Target doesn't support calls with kcfi operand bundles."); 8958 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8959 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8960 } 8961 } 8962 8963 SDValue ConvControlToken; 8964 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) { 8965 auto *Token = Bundle->Inputs[0].get(); 8966 ConvControlToken = getValue(Token); 8967 } 8968 8969 TargetLowering::CallLoweringInfo CLI(DAG); 8970 CLI.setDebugLoc(getCurSDLoc()) 8971 .setChain(getRoot()) 8972 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8973 .setTailCall(isTailCall) 8974 .setConvergent(CB.isConvergent()) 8975 .setIsPreallocated( 8976 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8977 .setCFIType(CFIType) 8978 .setConvergenceControlToken(ConvControlToken); 8979 8980 // Set the pointer authentication info if we have it. 8981 if (PAI) { 8982 if (!TLI.supportPtrAuthBundles()) 8983 report_fatal_error( 8984 "This target doesn't support calls with ptrauth operand bundles."); 8985 CLI.setPtrAuth(*PAI); 8986 } 8987 8988 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8989 8990 if (Result.first.getNode()) { 8991 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8992 setValue(&CB, Result.first); 8993 } 8994 8995 // The last element of CLI.InVals has the SDValue for swifterror return. 8996 // Here we copy it to a virtual register and update SwiftErrorMap for 8997 // book-keeping. 8998 if (SwiftErrorVal && TLI.supportSwiftError()) { 8999 // Get the last element of InVals. 9000 SDValue Src = CLI.InVals.back(); 9001 Register VReg = 9002 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 9003 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 9004 DAG.setRoot(CopyNode); 9005 } 9006 } 9007 9008 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 9009 SelectionDAGBuilder &Builder) { 9010 // Check to see if this load can be trivially constant folded, e.g. if the 9011 // input is from a string literal. 9012 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 9013 // Cast pointer to the type we really want to load. 9014 Type *LoadTy = 9015 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 9016 if (LoadVT.isVector()) 9017 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 9018 9019 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 9020 PointerType::getUnqual(LoadTy)); 9021 9022 if (const Constant *LoadCst = 9023 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 9024 LoadTy, Builder.DAG.getDataLayout())) 9025 return Builder.getValue(LoadCst); 9026 } 9027 9028 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 9029 // still constant memory, the input chain can be the entry node. 9030 SDValue Root; 9031 bool ConstantMemory = false; 9032 9033 // Do not serialize (non-volatile) loads of constant memory with anything. 9034 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 9035 Root = Builder.DAG.getEntryNode(); 9036 ConstantMemory = true; 9037 } else { 9038 // Do not serialize non-volatile loads against each other. 9039 Root = Builder.DAG.getRoot(); 9040 } 9041 9042 SDValue Ptr = Builder.getValue(PtrVal); 9043 SDValue LoadVal = 9044 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 9045 MachinePointerInfo(PtrVal), Align(1)); 9046 9047 if (!ConstantMemory) 9048 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 9049 return LoadVal; 9050 } 9051 9052 /// Record the value for an instruction that produces an integer result, 9053 /// converting the type where necessary. 9054 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 9055 SDValue Value, 9056 bool IsSigned) { 9057 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 9058 I.getType(), true); 9059 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 9060 setValue(&I, Value); 9061 } 9062 9063 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 9064 /// true and lower it. Otherwise return false, and it will be lowered like a 9065 /// normal call. 9066 /// The caller already checked that \p I calls the appropriate LibFunc with a 9067 /// correct prototype. 9068 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 9069 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 9070 const Value *Size = I.getArgOperand(2); 9071 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 9072 if (CSize && CSize->getZExtValue() == 0) { 9073 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 9074 I.getType(), true); 9075 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 9076 return true; 9077 } 9078 9079 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9080 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 9081 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 9082 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 9083 if (Res.first.getNode()) { 9084 processIntegerCallValue(I, Res.first, true); 9085 PendingLoads.push_back(Res.second); 9086 return true; 9087 } 9088 9089 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 9090 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 9091 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 9092 return false; 9093 9094 // If the target has a fast compare for the given size, it will return a 9095 // preferred load type for that size. Require that the load VT is legal and 9096 // that the target supports unaligned loads of that type. Otherwise, return 9097 // INVALID. 9098 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 9099 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9100 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 9101 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 9102 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 9103 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 9104 // TODO: Check alignment of src and dest ptrs. 9105 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 9106 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 9107 if (!TLI.isTypeLegal(LVT) || 9108 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 9109 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 9110 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 9111 } 9112 9113 return LVT; 9114 }; 9115 9116 // This turns into unaligned loads. We only do this if the target natively 9117 // supports the MVT we'll be loading or if it is small enough (<= 4) that 9118 // we'll only produce a small number of byte loads. 9119 MVT LoadVT; 9120 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 9121 switch (NumBitsToCompare) { 9122 default: 9123 return false; 9124 case 16: 9125 LoadVT = MVT::i16; 9126 break; 9127 case 32: 9128 LoadVT = MVT::i32; 9129 break; 9130 case 64: 9131 case 128: 9132 case 256: 9133 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 9134 break; 9135 } 9136 9137 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 9138 return false; 9139 9140 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 9141 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 9142 9143 // Bitcast to a wide integer type if the loads are vectors. 9144 if (LoadVT.isVector()) { 9145 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 9146 LoadL = DAG.getBitcast(CmpVT, LoadL); 9147 LoadR = DAG.getBitcast(CmpVT, LoadR); 9148 } 9149 9150 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 9151 processIntegerCallValue(I, Cmp, false); 9152 return true; 9153 } 9154 9155 /// See if we can lower a memchr call into an optimized form. If so, return 9156 /// true and lower it. Otherwise return false, and it will be lowered like a 9157 /// normal call. 9158 /// The caller already checked that \p I calls the appropriate LibFunc with a 9159 /// correct prototype. 9160 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 9161 const Value *Src = I.getArgOperand(0); 9162 const Value *Char = I.getArgOperand(1); 9163 const Value *Length = I.getArgOperand(2); 9164 9165 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9166 std::pair<SDValue, SDValue> Res = 9167 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 9168 getValue(Src), getValue(Char), getValue(Length), 9169 MachinePointerInfo(Src)); 9170 if (Res.first.getNode()) { 9171 setValue(&I, Res.first); 9172 PendingLoads.push_back(Res.second); 9173 return true; 9174 } 9175 9176 return false; 9177 } 9178 9179 /// See if we can lower a mempcpy 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::visitMemPCpyCall(const CallInst &I) { 9185 SDValue Dst = getValue(I.getArgOperand(0)); 9186 SDValue Src = getValue(I.getArgOperand(1)); 9187 SDValue Size = getValue(I.getArgOperand(2)); 9188 9189 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 9190 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 9191 // DAG::getMemcpy needs Alignment to be defined. 9192 Align Alignment = std::min(DstAlign, SrcAlign); 9193 9194 SDLoc sdl = getCurSDLoc(); 9195 9196 // In the mempcpy context we need to pass in a false value for isTailCall 9197 // because the return pointer needs to be adjusted by the size of 9198 // the copied memory. 9199 SDValue Root = getMemoryRoot(); 9200 SDValue MC = DAG.getMemcpy( 9201 Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr, 9202 std::nullopt, MachinePointerInfo(I.getArgOperand(0)), 9203 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata()); 9204 assert(MC.getNode() != nullptr && 9205 "** memcpy should not be lowered as TailCall in mempcpy context **"); 9206 DAG.setRoot(MC); 9207 9208 // Check if Size needs to be truncated or extended. 9209 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 9210 9211 // Adjust return pointer to point just past the last dst byte. 9212 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 9213 Dst, Size); 9214 setValue(&I, DstPlusSize); 9215 return true; 9216 } 9217 9218 /// See if we can lower a strcpy call into an optimized form. If so, return 9219 /// true and lower it, otherwise return false and it will be lowered like a 9220 /// normal call. 9221 /// The caller already checked that \p I calls the appropriate LibFunc with a 9222 /// correct prototype. 9223 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 9224 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9225 9226 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9227 std::pair<SDValue, SDValue> Res = 9228 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 9229 getValue(Arg0), getValue(Arg1), 9230 MachinePointerInfo(Arg0), 9231 MachinePointerInfo(Arg1), isStpcpy); 9232 if (Res.first.getNode()) { 9233 setValue(&I, Res.first); 9234 DAG.setRoot(Res.second); 9235 return true; 9236 } 9237 9238 return false; 9239 } 9240 9241 /// See if we can lower a strcmp call into an optimized form. If so, return 9242 /// true and lower it, otherwise return false and it will be lowered like a 9243 /// normal call. 9244 /// The caller already checked that \p I calls the appropriate LibFunc with a 9245 /// correct prototype. 9246 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 9247 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9248 9249 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9250 std::pair<SDValue, SDValue> Res = 9251 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 9252 getValue(Arg0), getValue(Arg1), 9253 MachinePointerInfo(Arg0), 9254 MachinePointerInfo(Arg1)); 9255 if (Res.first.getNode()) { 9256 processIntegerCallValue(I, Res.first, true); 9257 PendingLoads.push_back(Res.second); 9258 return true; 9259 } 9260 9261 return false; 9262 } 9263 9264 /// See if we can lower a strlen call into an optimized form. If so, return 9265 /// true and lower it, otherwise return false and it will be lowered like a 9266 /// normal call. 9267 /// The caller already checked that \p I calls the appropriate LibFunc with a 9268 /// correct prototype. 9269 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 9270 const Value *Arg0 = I.getArgOperand(0); 9271 9272 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9273 std::pair<SDValue, SDValue> Res = 9274 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 9275 getValue(Arg0), MachinePointerInfo(Arg0)); 9276 if (Res.first.getNode()) { 9277 processIntegerCallValue(I, Res.first, false); 9278 PendingLoads.push_back(Res.second); 9279 return true; 9280 } 9281 9282 return false; 9283 } 9284 9285 /// See if we can lower a strnlen call into an optimized form. If so, return 9286 /// true and lower it, otherwise return false and it will be lowered like a 9287 /// normal call. 9288 /// The caller already checked that \p I calls the appropriate LibFunc with a 9289 /// correct prototype. 9290 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 9291 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9292 9293 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9294 std::pair<SDValue, SDValue> Res = 9295 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 9296 getValue(Arg0), getValue(Arg1), 9297 MachinePointerInfo(Arg0)); 9298 if (Res.first.getNode()) { 9299 processIntegerCallValue(I, Res.first, false); 9300 PendingLoads.push_back(Res.second); 9301 return true; 9302 } 9303 9304 return false; 9305 } 9306 9307 /// See if we can lower a unary floating-point operation into an SDNode with 9308 /// the specified Opcode. If so, return true and lower it, otherwise return 9309 /// false and it will be lowered like a normal call. 9310 /// The caller already checked that \p I calls the appropriate LibFunc with a 9311 /// correct prototype. 9312 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 9313 unsigned Opcode) { 9314 // We already checked this call's prototype; verify it doesn't modify errno. 9315 if (!I.onlyReadsMemory()) 9316 return false; 9317 9318 SDNodeFlags Flags; 9319 Flags.copyFMF(cast<FPMathOperator>(I)); 9320 9321 SDValue Tmp = getValue(I.getArgOperand(0)); 9322 setValue(&I, 9323 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 9324 return true; 9325 } 9326 9327 /// See if we can lower a binary floating-point operation into an SDNode with 9328 /// the specified Opcode. If so, return true and lower it. Otherwise return 9329 /// false, and it will be lowered like a normal call. 9330 /// The caller already checked that \p I calls the appropriate LibFunc with a 9331 /// correct prototype. 9332 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 9333 unsigned Opcode) { 9334 // We already checked this call's prototype; verify it doesn't modify errno. 9335 if (!I.onlyReadsMemory()) 9336 return false; 9337 9338 SDNodeFlags Flags; 9339 Flags.copyFMF(cast<FPMathOperator>(I)); 9340 9341 SDValue Tmp0 = getValue(I.getArgOperand(0)); 9342 SDValue Tmp1 = getValue(I.getArgOperand(1)); 9343 EVT VT = Tmp0.getValueType(); 9344 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 9345 return true; 9346 } 9347 9348 void SelectionDAGBuilder::visitCall(const CallInst &I) { 9349 // Handle inline assembly differently. 9350 if (I.isInlineAsm()) { 9351 visitInlineAsm(I); 9352 return; 9353 } 9354 9355 diagnoseDontCall(I); 9356 9357 if (Function *F = I.getCalledFunction()) { 9358 if (F->isDeclaration()) { 9359 // Is this an LLVM intrinsic or a target-specific intrinsic? 9360 unsigned IID = F->getIntrinsicID(); 9361 if (!IID) 9362 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 9363 IID = II->getIntrinsicID(F); 9364 9365 if (IID) { 9366 visitIntrinsicCall(I, IID); 9367 return; 9368 } 9369 } 9370 9371 // Check for well-known libc/libm calls. If the function is internal, it 9372 // can't be a library call. Don't do the check if marked as nobuiltin for 9373 // some reason or the call site requires strict floating point semantics. 9374 LibFunc Func; 9375 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 9376 F->hasName() && LibInfo->getLibFunc(*F, Func) && 9377 LibInfo->hasOptimizedCodeGen(Func)) { 9378 switch (Func) { 9379 default: break; 9380 case LibFunc_bcmp: 9381 if (visitMemCmpBCmpCall(I)) 9382 return; 9383 break; 9384 case LibFunc_copysign: 9385 case LibFunc_copysignf: 9386 case LibFunc_copysignl: 9387 // We already checked this call's prototype; verify it doesn't modify 9388 // errno. 9389 if (I.onlyReadsMemory()) { 9390 SDValue LHS = getValue(I.getArgOperand(0)); 9391 SDValue RHS = getValue(I.getArgOperand(1)); 9392 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 9393 LHS.getValueType(), LHS, RHS)); 9394 return; 9395 } 9396 break; 9397 case LibFunc_fabs: 9398 case LibFunc_fabsf: 9399 case LibFunc_fabsl: 9400 if (visitUnaryFloatCall(I, ISD::FABS)) 9401 return; 9402 break; 9403 case LibFunc_fmin: 9404 case LibFunc_fminf: 9405 case LibFunc_fminl: 9406 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 9407 return; 9408 break; 9409 case LibFunc_fmax: 9410 case LibFunc_fmaxf: 9411 case LibFunc_fmaxl: 9412 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 9413 return; 9414 break; 9415 case LibFunc_fminimum_num: 9416 case LibFunc_fminimum_numf: 9417 case LibFunc_fminimum_numl: 9418 if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM)) 9419 return; 9420 break; 9421 case LibFunc_fmaximum_num: 9422 case LibFunc_fmaximum_numf: 9423 case LibFunc_fmaximum_numl: 9424 if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM)) 9425 return; 9426 break; 9427 case LibFunc_sin: 9428 case LibFunc_sinf: 9429 case LibFunc_sinl: 9430 if (visitUnaryFloatCall(I, ISD::FSIN)) 9431 return; 9432 break; 9433 case LibFunc_cos: 9434 case LibFunc_cosf: 9435 case LibFunc_cosl: 9436 if (visitUnaryFloatCall(I, ISD::FCOS)) 9437 return; 9438 break; 9439 case LibFunc_tan: 9440 case LibFunc_tanf: 9441 case LibFunc_tanl: 9442 if (visitUnaryFloatCall(I, ISD::FTAN)) 9443 return; 9444 break; 9445 case LibFunc_asin: 9446 case LibFunc_asinf: 9447 case LibFunc_asinl: 9448 if (visitUnaryFloatCall(I, ISD::FASIN)) 9449 return; 9450 break; 9451 case LibFunc_acos: 9452 case LibFunc_acosf: 9453 case LibFunc_acosl: 9454 if (visitUnaryFloatCall(I, ISD::FACOS)) 9455 return; 9456 break; 9457 case LibFunc_atan: 9458 case LibFunc_atanf: 9459 case LibFunc_atanl: 9460 if (visitUnaryFloatCall(I, ISD::FATAN)) 9461 return; 9462 break; 9463 case LibFunc_atan2: 9464 case LibFunc_atan2f: 9465 case LibFunc_atan2l: 9466 if (visitBinaryFloatCall(I, ISD::FATAN2)) 9467 return; 9468 break; 9469 case LibFunc_sinh: 9470 case LibFunc_sinhf: 9471 case LibFunc_sinhl: 9472 if (visitUnaryFloatCall(I, ISD::FSINH)) 9473 return; 9474 break; 9475 case LibFunc_cosh: 9476 case LibFunc_coshf: 9477 case LibFunc_coshl: 9478 if (visitUnaryFloatCall(I, ISD::FCOSH)) 9479 return; 9480 break; 9481 case LibFunc_tanh: 9482 case LibFunc_tanhf: 9483 case LibFunc_tanhl: 9484 if (visitUnaryFloatCall(I, ISD::FTANH)) 9485 return; 9486 break; 9487 case LibFunc_sqrt: 9488 case LibFunc_sqrtf: 9489 case LibFunc_sqrtl: 9490 case LibFunc_sqrt_finite: 9491 case LibFunc_sqrtf_finite: 9492 case LibFunc_sqrtl_finite: 9493 if (visitUnaryFloatCall(I, ISD::FSQRT)) 9494 return; 9495 break; 9496 case LibFunc_floor: 9497 case LibFunc_floorf: 9498 case LibFunc_floorl: 9499 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 9500 return; 9501 break; 9502 case LibFunc_nearbyint: 9503 case LibFunc_nearbyintf: 9504 case LibFunc_nearbyintl: 9505 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 9506 return; 9507 break; 9508 case LibFunc_ceil: 9509 case LibFunc_ceilf: 9510 case LibFunc_ceill: 9511 if (visitUnaryFloatCall(I, ISD::FCEIL)) 9512 return; 9513 break; 9514 case LibFunc_rint: 9515 case LibFunc_rintf: 9516 case LibFunc_rintl: 9517 if (visitUnaryFloatCall(I, ISD::FRINT)) 9518 return; 9519 break; 9520 case LibFunc_round: 9521 case LibFunc_roundf: 9522 case LibFunc_roundl: 9523 if (visitUnaryFloatCall(I, ISD::FROUND)) 9524 return; 9525 break; 9526 case LibFunc_trunc: 9527 case LibFunc_truncf: 9528 case LibFunc_truncl: 9529 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 9530 return; 9531 break; 9532 case LibFunc_log2: 9533 case LibFunc_log2f: 9534 case LibFunc_log2l: 9535 if (visitUnaryFloatCall(I, ISD::FLOG2)) 9536 return; 9537 break; 9538 case LibFunc_exp2: 9539 case LibFunc_exp2f: 9540 case LibFunc_exp2l: 9541 if (visitUnaryFloatCall(I, ISD::FEXP2)) 9542 return; 9543 break; 9544 case LibFunc_exp10: 9545 case LibFunc_exp10f: 9546 case LibFunc_exp10l: 9547 if (visitUnaryFloatCall(I, ISD::FEXP10)) 9548 return; 9549 break; 9550 case LibFunc_ldexp: 9551 case LibFunc_ldexpf: 9552 case LibFunc_ldexpl: 9553 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 9554 return; 9555 break; 9556 case LibFunc_memcmp: 9557 if (visitMemCmpBCmpCall(I)) 9558 return; 9559 break; 9560 case LibFunc_mempcpy: 9561 if (visitMemPCpyCall(I)) 9562 return; 9563 break; 9564 case LibFunc_memchr: 9565 if (visitMemChrCall(I)) 9566 return; 9567 break; 9568 case LibFunc_strcpy: 9569 if (visitStrCpyCall(I, false)) 9570 return; 9571 break; 9572 case LibFunc_stpcpy: 9573 if (visitStrCpyCall(I, true)) 9574 return; 9575 break; 9576 case LibFunc_strcmp: 9577 if (visitStrCmpCall(I)) 9578 return; 9579 break; 9580 case LibFunc_strlen: 9581 if (visitStrLenCall(I)) 9582 return; 9583 break; 9584 case LibFunc_strnlen: 9585 if (visitStrNLenCall(I)) 9586 return; 9587 break; 9588 } 9589 } 9590 } 9591 9592 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 9593 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr); 9594 return; 9595 } 9596 9597 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9598 // have to do anything here to lower funclet bundles. 9599 // CFGuardTarget bundles are lowered in LowerCallTo. 9600 assert(!I.hasOperandBundlesOtherThan( 9601 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9602 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9603 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi, 9604 LLVMContext::OB_convergencectrl}) && 9605 "Cannot lower calls with arbitrary operand bundles!"); 9606 9607 SDValue Callee = getValue(I.getCalledOperand()); 9608 9609 if (I.hasDeoptState()) 9610 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9611 else 9612 // Check if we can potentially perform a tail call. More detailed checking 9613 // is be done within LowerCallTo, after more information about the call is 9614 // known. 9615 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9616 } 9617 9618 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle( 9619 const CallBase &CB, const BasicBlock *EHPadBB) { 9620 auto PAB = CB.getOperandBundle("ptrauth"); 9621 const Value *CalleeV = CB.getCalledOperand(); 9622 9623 // Gather the call ptrauth data from the operand bundle: 9624 // [ i32 <key>, i64 <discriminator> ] 9625 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]); 9626 const Value *Discriminator = PAB->Inputs[1]; 9627 9628 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key"); 9629 assert(Discriminator->getType()->isIntegerTy(64) && 9630 "Invalid ptrauth discriminator"); 9631 9632 // Look through ptrauth constants to find the raw callee. 9633 // Do a direct unauthenticated call if we found it and everything matches. 9634 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV)) 9635 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator, 9636 DAG.getDataLayout())) 9637 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(), 9638 CB.isMustTailCall(), EHPadBB); 9639 9640 // Functions should never be ptrauth-called directly. 9641 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call"); 9642 9643 // Otherwise, do an authenticated indirect call. 9644 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(), 9645 getValue(Discriminator)}; 9646 9647 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(), 9648 EHPadBB, &PAI); 9649 } 9650 9651 namespace { 9652 9653 /// AsmOperandInfo - This contains information for each constraint that we are 9654 /// lowering. 9655 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9656 public: 9657 /// CallOperand - If this is the result output operand or a clobber 9658 /// this is null, otherwise it is the incoming operand to the CallInst. 9659 /// This gets modified as the asm is processed. 9660 SDValue CallOperand; 9661 9662 /// AssignedRegs - If this is a register or register class operand, this 9663 /// contains the set of register corresponding to the operand. 9664 RegsForValue AssignedRegs; 9665 9666 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9667 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9668 } 9669 9670 /// Whether or not this operand accesses memory 9671 bool hasMemory(const TargetLowering &TLI) const { 9672 // Indirect operand accesses access memory. 9673 if (isIndirect) 9674 return true; 9675 9676 for (const auto &Code : Codes) 9677 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9678 return true; 9679 9680 return false; 9681 } 9682 }; 9683 9684 9685 } // end anonymous namespace 9686 9687 /// Make sure that the output operand \p OpInfo and its corresponding input 9688 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9689 /// out). 9690 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9691 SDISelAsmOperandInfo &MatchingOpInfo, 9692 SelectionDAG &DAG) { 9693 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9694 return; 9695 9696 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9697 const auto &TLI = DAG.getTargetLoweringInfo(); 9698 9699 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9700 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9701 OpInfo.ConstraintVT); 9702 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9703 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9704 MatchingOpInfo.ConstraintVT); 9705 const bool OutOpIsIntOrFP = 9706 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint(); 9707 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() || 9708 MatchingOpInfo.ConstraintVT.isFloatingPoint(); 9709 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) { 9710 // FIXME: error out in a more elegant fashion 9711 report_fatal_error("Unsupported asm: input constraint" 9712 " with a matching output constraint of" 9713 " incompatible type!"); 9714 } 9715 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9716 } 9717 9718 /// Get a direct memory input to behave well as an indirect operand. 9719 /// This may introduce stores, hence the need for a \p Chain. 9720 /// \return The (possibly updated) chain. 9721 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9722 SDISelAsmOperandInfo &OpInfo, 9723 SelectionDAG &DAG) { 9724 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9725 9726 // If we don't have an indirect input, put it in the constpool if we can, 9727 // otherwise spill it to a stack slot. 9728 // TODO: This isn't quite right. We need to handle these according to 9729 // the addressing mode that the constraint wants. Also, this may take 9730 // an additional register for the computation and we don't want that 9731 // either. 9732 9733 // If the operand is a float, integer, or vector constant, spill to a 9734 // constant pool entry to get its address. 9735 const Value *OpVal = OpInfo.CallOperandVal; 9736 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9737 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9738 OpInfo.CallOperand = DAG.getConstantPool( 9739 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9740 return Chain; 9741 } 9742 9743 // Otherwise, create a stack slot and emit a store to it before the asm. 9744 Type *Ty = OpVal->getType(); 9745 auto &DL = DAG.getDataLayout(); 9746 TypeSize TySize = DL.getTypeAllocSize(Ty); 9747 MachineFunction &MF = DAG.getMachineFunction(); 9748 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 9749 int StackID = 0; 9750 if (TySize.isScalable()) 9751 StackID = TFI->getStackIDForScalableVectors(); 9752 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(), 9753 DL.getPrefTypeAlign(Ty), false, 9754 nullptr, StackID); 9755 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9756 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9757 MachinePointerInfo::getFixedStack(MF, SSFI), 9758 TLI.getMemValueType(DL, Ty)); 9759 OpInfo.CallOperand = StackSlot; 9760 9761 return Chain; 9762 } 9763 9764 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9765 /// specified operand. We prefer to assign virtual registers, to allow the 9766 /// register allocator to handle the assignment process. However, if the asm 9767 /// uses features that we can't model on machineinstrs, we have SDISel do the 9768 /// allocation. This produces generally horrible, but correct, code. 9769 /// 9770 /// OpInfo describes the operand 9771 /// RefOpInfo describes the matching operand if any, the operand otherwise 9772 static std::optional<unsigned> 9773 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9774 SDISelAsmOperandInfo &OpInfo, 9775 SDISelAsmOperandInfo &RefOpInfo) { 9776 LLVMContext &Context = *DAG.getContext(); 9777 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9778 9779 MachineFunction &MF = DAG.getMachineFunction(); 9780 SmallVector<Register, 4> Regs; 9781 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9782 9783 // No work to do for memory/address operands. 9784 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9785 OpInfo.ConstraintType == TargetLowering::C_Address) 9786 return std::nullopt; 9787 9788 // If this is a constraint for a single physreg, or a constraint for a 9789 // register class, find it. 9790 unsigned AssignedReg; 9791 const TargetRegisterClass *RC; 9792 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9793 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9794 // RC is unset only on failure. Return immediately. 9795 if (!RC) 9796 return std::nullopt; 9797 9798 // Get the actual register value type. This is important, because the user 9799 // may have asked for (e.g.) the AX register in i32 type. We need to 9800 // remember that AX is actually i16 to get the right extension. 9801 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9802 9803 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9804 // If this is an FP operand in an integer register (or visa versa), or more 9805 // generally if the operand value disagrees with the register class we plan 9806 // to stick it in, fix the operand type. 9807 // 9808 // If this is an input value, the bitcast to the new type is done now. 9809 // Bitcast for output value is done at the end of visitInlineAsm(). 9810 if ((OpInfo.Type == InlineAsm::isOutput || 9811 OpInfo.Type == InlineAsm::isInput) && 9812 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9813 // Try to convert to the first EVT that the reg class contains. If the 9814 // types are identical size, use a bitcast to convert (e.g. two differing 9815 // vector types). Note: output bitcast is done at the end of 9816 // visitInlineAsm(). 9817 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9818 // Exclude indirect inputs while they are unsupported because the code 9819 // to perform the load is missing and thus OpInfo.CallOperand still 9820 // refers to the input address rather than the pointed-to value. 9821 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9822 OpInfo.CallOperand = 9823 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9824 OpInfo.ConstraintVT = RegVT; 9825 // If the operand is an FP value and we want it in integer registers, 9826 // use the corresponding integer type. This turns an f64 value into 9827 // i64, which can be passed with two i32 values on a 32-bit machine. 9828 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9829 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9830 if (OpInfo.Type == InlineAsm::isInput) 9831 OpInfo.CallOperand = 9832 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9833 OpInfo.ConstraintVT = VT; 9834 } 9835 } 9836 } 9837 9838 // No need to allocate a matching input constraint since the constraint it's 9839 // matching to has already been allocated. 9840 if (OpInfo.isMatchingInputConstraint()) 9841 return std::nullopt; 9842 9843 EVT ValueVT = OpInfo.ConstraintVT; 9844 if (OpInfo.ConstraintVT == MVT::Other) 9845 ValueVT = RegVT; 9846 9847 // Initialize NumRegs. 9848 unsigned NumRegs = 1; 9849 if (OpInfo.ConstraintVT != MVT::Other) 9850 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9851 9852 // If this is a constraint for a specific physical register, like {r17}, 9853 // assign it now. 9854 9855 // If this associated to a specific register, initialize iterator to correct 9856 // place. If virtual, make sure we have enough registers 9857 9858 // Initialize iterator if necessary 9859 TargetRegisterClass::iterator I = RC->begin(); 9860 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9861 9862 // Do not check for single registers. 9863 if (AssignedReg) { 9864 I = std::find(I, RC->end(), AssignedReg); 9865 if (I == RC->end()) { 9866 // RC does not contain the selected register, which indicates a 9867 // mismatch between the register and the required type/bitwidth. 9868 return {AssignedReg}; 9869 } 9870 } 9871 9872 for (; NumRegs; --NumRegs, ++I) { 9873 assert(I != RC->end() && "Ran out of registers to allocate!"); 9874 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9875 Regs.push_back(R); 9876 } 9877 9878 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9879 return std::nullopt; 9880 } 9881 9882 static unsigned 9883 findMatchingInlineAsmOperand(unsigned OperandNo, 9884 const std::vector<SDValue> &AsmNodeOperands) { 9885 // Scan until we find the definition we already emitted of this operand. 9886 unsigned CurOp = InlineAsm::Op_FirstOperand; 9887 for (; OperandNo; --OperandNo) { 9888 // Advance to the next operand. 9889 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9890 const InlineAsm::Flag F(OpFlag); 9891 assert( 9892 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9893 "Skipped past definitions?"); 9894 CurOp += F.getNumOperandRegisters() + 1; 9895 } 9896 return CurOp; 9897 } 9898 9899 namespace { 9900 9901 class ExtraFlags { 9902 unsigned Flags = 0; 9903 9904 public: 9905 explicit ExtraFlags(const CallBase &Call) { 9906 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9907 if (IA->hasSideEffects()) 9908 Flags |= InlineAsm::Extra_HasSideEffects; 9909 if (IA->isAlignStack()) 9910 Flags |= InlineAsm::Extra_IsAlignStack; 9911 if (Call.isConvergent()) 9912 Flags |= InlineAsm::Extra_IsConvergent; 9913 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9914 } 9915 9916 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9917 // Ideally, we would only check against memory constraints. However, the 9918 // meaning of an Other constraint can be target-specific and we can't easily 9919 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9920 // for Other constraints as well. 9921 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9922 OpInfo.ConstraintType == TargetLowering::C_Other) { 9923 if (OpInfo.Type == InlineAsm::isInput) 9924 Flags |= InlineAsm::Extra_MayLoad; 9925 else if (OpInfo.Type == InlineAsm::isOutput) 9926 Flags |= InlineAsm::Extra_MayStore; 9927 else if (OpInfo.Type == InlineAsm::isClobber) 9928 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9929 } 9930 } 9931 9932 unsigned get() const { return Flags; } 9933 }; 9934 9935 } // end anonymous namespace 9936 9937 static bool isFunction(SDValue Op) { 9938 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9939 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9940 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9941 9942 // In normal "call dllimport func" instruction (non-inlineasm) it force 9943 // indirect access by specifing call opcode. And usually specially print 9944 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9945 // not do in this way now. (In fact, this is similar with "Data Access" 9946 // action). So here we ignore dllimport function. 9947 if (Fn && !Fn->hasDLLImportStorageClass()) 9948 return true; 9949 } 9950 } 9951 return false; 9952 } 9953 9954 /// visitInlineAsm - Handle a call to an InlineAsm object. 9955 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9956 const BasicBlock *EHPadBB) { 9957 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9958 9959 /// ConstraintOperands - Information about all of the constraints. 9960 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9961 9962 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9963 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9964 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9965 9966 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9967 // AsmDialect, MayLoad, MayStore). 9968 bool HasSideEffect = IA->hasSideEffects(); 9969 ExtraFlags ExtraInfo(Call); 9970 9971 for (auto &T : TargetConstraints) { 9972 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9973 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9974 9975 if (OpInfo.CallOperandVal) 9976 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9977 9978 if (!HasSideEffect) 9979 HasSideEffect = OpInfo.hasMemory(TLI); 9980 9981 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9982 // FIXME: Could we compute this on OpInfo rather than T? 9983 9984 // Compute the constraint code and ConstraintType to use. 9985 TLI.ComputeConstraintToUse(T, SDValue()); 9986 9987 if (T.ConstraintType == TargetLowering::C_Immediate && 9988 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9989 // We've delayed emitting a diagnostic like the "n" constraint because 9990 // inlining could cause an integer showing up. 9991 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9992 "' expects an integer constant " 9993 "expression"); 9994 9995 ExtraInfo.update(T); 9996 } 9997 9998 // We won't need to flush pending loads if this asm doesn't touch 9999 // memory and is nonvolatile. 10000 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 10001 10002 bool EmitEHLabels = isa<InvokeInst>(Call); 10003 if (EmitEHLabels) { 10004 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 10005 } 10006 bool IsCallBr = isa<CallBrInst>(Call); 10007 10008 if (IsCallBr || EmitEHLabels) { 10009 // If this is a callbr or invoke we need to flush pending exports since 10010 // inlineasm_br and invoke are terminators. 10011 // We need to do this before nodes are glued to the inlineasm_br node. 10012 Chain = getControlRoot(); 10013 } 10014 10015 MCSymbol *BeginLabel = nullptr; 10016 if (EmitEHLabels) { 10017 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 10018 } 10019 10020 int OpNo = -1; 10021 SmallVector<StringRef> AsmStrs; 10022 IA->collectAsmStrs(AsmStrs); 10023 10024 // Second pass over the constraints: compute which constraint option to use. 10025 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10026 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 10027 OpNo++; 10028 10029 // If this is an output operand with a matching input operand, look up the 10030 // matching input. If their types mismatch, e.g. one is an integer, the 10031 // other is floating point, or their sizes are different, flag it as an 10032 // error. 10033 if (OpInfo.hasMatchingInput()) { 10034 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 10035 patchMatchingInput(OpInfo, Input, DAG); 10036 } 10037 10038 // Compute the constraint code and ConstraintType to use. 10039 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 10040 10041 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 10042 OpInfo.Type == InlineAsm::isClobber) || 10043 OpInfo.ConstraintType == TargetLowering::C_Address) 10044 continue; 10045 10046 // In Linux PIC model, there are 4 cases about value/label addressing: 10047 // 10048 // 1: Function call or Label jmp inside the module. 10049 // 2: Data access (such as global variable, static variable) inside module. 10050 // 3: Function call or Label jmp outside the module. 10051 // 4: Data access (such as global variable) outside the module. 10052 // 10053 // Due to current llvm inline asm architecture designed to not "recognize" 10054 // the asm code, there are quite troubles for us to treat mem addressing 10055 // differently for same value/adress used in different instuctions. 10056 // For example, in pic model, call a func may in plt way or direclty 10057 // pc-related, but lea/mov a function adress may use got. 10058 // 10059 // Here we try to "recognize" function call for the case 1 and case 3 in 10060 // inline asm. And try to adjust the constraint for them. 10061 // 10062 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 10063 // label, so here we don't handle jmp function label now, but we need to 10064 // enhance it (especilly in PIC model) if we meet meaningful requirements. 10065 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 10066 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 10067 TM.getCodeModel() != CodeModel::Large) { 10068 OpInfo.isIndirect = false; 10069 OpInfo.ConstraintType = TargetLowering::C_Address; 10070 } 10071 10072 // If this is a memory input, and if the operand is not indirect, do what we 10073 // need to provide an address for the memory input. 10074 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 10075 !OpInfo.isIndirect) { 10076 assert((OpInfo.isMultipleAlternative || 10077 (OpInfo.Type == InlineAsm::isInput)) && 10078 "Can only indirectify direct input operands!"); 10079 10080 // Memory operands really want the address of the value. 10081 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 10082 10083 // There is no longer a Value* corresponding to this operand. 10084 OpInfo.CallOperandVal = nullptr; 10085 10086 // It is now an indirect operand. 10087 OpInfo.isIndirect = true; 10088 } 10089 10090 } 10091 10092 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 10093 std::vector<SDValue> AsmNodeOperands; 10094 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 10095 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 10096 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 10097 10098 // If we have a !srcloc metadata node associated with it, we want to attach 10099 // this to the ultimately generated inline asm machineinstr. To do this, we 10100 // pass in the third operand as this (potentially null) inline asm MDNode. 10101 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 10102 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 10103 10104 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 10105 // bits as operand 3. 10106 AsmNodeOperands.push_back(DAG.getTargetConstant( 10107 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10108 10109 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 10110 // this, assign virtual and physical registers for inputs and otput. 10111 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10112 // Assign Registers. 10113 SDISelAsmOperandInfo &RefOpInfo = 10114 OpInfo.isMatchingInputConstraint() 10115 ? ConstraintOperands[OpInfo.getMatchedOperand()] 10116 : OpInfo; 10117 const auto RegError = 10118 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 10119 if (RegError) { 10120 const MachineFunction &MF = DAG.getMachineFunction(); 10121 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 10122 const char *RegName = TRI.getName(*RegError); 10123 emitInlineAsmError(Call, "register '" + Twine(RegName) + 10124 "' allocated for constraint '" + 10125 Twine(OpInfo.ConstraintCode) + 10126 "' does not match required type"); 10127 return; 10128 } 10129 10130 auto DetectWriteToReservedRegister = [&]() { 10131 const MachineFunction &MF = DAG.getMachineFunction(); 10132 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 10133 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 10134 if (Register::isPhysicalRegister(Reg) && 10135 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 10136 const char *RegName = TRI.getName(Reg); 10137 emitInlineAsmError(Call, "write to reserved register '" + 10138 Twine(RegName) + "'"); 10139 return true; 10140 } 10141 } 10142 return false; 10143 }; 10144 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 10145 (OpInfo.Type == InlineAsm::isInput && 10146 !OpInfo.isMatchingInputConstraint())) && 10147 "Only address as input operand is allowed."); 10148 10149 switch (OpInfo.Type) { 10150 case InlineAsm::isOutput: 10151 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 10152 const InlineAsm::ConstraintCode ConstraintID = 10153 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10154 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10155 "Failed to convert memory constraint code to constraint id."); 10156 10157 // Add information to the INLINEASM node to know about this output. 10158 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 10159 OpFlags.setMemConstraint(ConstraintID); 10160 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 10161 MVT::i32)); 10162 AsmNodeOperands.push_back(OpInfo.CallOperand); 10163 } else { 10164 // Otherwise, this outputs to a register (directly for C_Register / 10165 // C_RegisterClass, and a target-defined fashion for 10166 // C_Immediate/C_Other). Find a register that we can use. 10167 if (OpInfo.AssignedRegs.Regs.empty()) { 10168 emitInlineAsmError( 10169 Call, "couldn't allocate output register for constraint '" + 10170 Twine(OpInfo.ConstraintCode) + "'"); 10171 return; 10172 } 10173 10174 if (DetectWriteToReservedRegister()) 10175 return; 10176 10177 // Add information to the INLINEASM node to know that this register is 10178 // set. 10179 OpInfo.AssignedRegs.AddInlineAsmOperands( 10180 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 10181 : InlineAsm::Kind::RegDef, 10182 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 10183 } 10184 break; 10185 10186 case InlineAsm::isInput: 10187 case InlineAsm::isLabel: { 10188 SDValue InOperandVal = OpInfo.CallOperand; 10189 10190 if (OpInfo.isMatchingInputConstraint()) { 10191 // If this is required to match an output register we have already set, 10192 // just use its register. 10193 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 10194 AsmNodeOperands); 10195 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 10196 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 10197 if (OpInfo.isIndirect) { 10198 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 10199 emitInlineAsmError(Call, "inline asm not supported yet: " 10200 "don't know how to handle tied " 10201 "indirect register inputs"); 10202 return; 10203 } 10204 10205 SmallVector<Register, 4> Regs; 10206 MachineFunction &MF = DAG.getMachineFunction(); 10207 MachineRegisterInfo &MRI = MF.getRegInfo(); 10208 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 10209 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 10210 Register TiedReg = R->getReg(); 10211 MVT RegVT = R->getSimpleValueType(0); 10212 const TargetRegisterClass *RC = 10213 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 10214 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 10215 : TRI.getMinimalPhysRegClass(TiedReg); 10216 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 10217 Regs.push_back(MRI.createVirtualRegister(RC)); 10218 10219 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 10220 10221 SDLoc dl = getCurSDLoc(); 10222 // Use the produced MatchedRegs object to 10223 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 10224 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 10225 OpInfo.getMatchedOperand(), dl, DAG, 10226 AsmNodeOperands); 10227 break; 10228 } 10229 10230 assert(Flag.isMemKind() && "Unknown matching constraint!"); 10231 assert(Flag.getNumOperandRegisters() == 1 && 10232 "Unexpected number of operands"); 10233 // Add information to the INLINEASM node to know about this input. 10234 // See InlineAsm.h isUseOperandTiedToDef. 10235 Flag.clearMemConstraint(); 10236 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 10237 AsmNodeOperands.push_back(DAG.getTargetConstant( 10238 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10239 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 10240 break; 10241 } 10242 10243 // Treat indirect 'X' constraint as memory. 10244 if (OpInfo.ConstraintType == TargetLowering::C_Other && 10245 OpInfo.isIndirect) 10246 OpInfo.ConstraintType = TargetLowering::C_Memory; 10247 10248 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 10249 OpInfo.ConstraintType == TargetLowering::C_Other) { 10250 std::vector<SDValue> Ops; 10251 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 10252 Ops, DAG); 10253 if (Ops.empty()) { 10254 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 10255 if (isa<ConstantSDNode>(InOperandVal)) { 10256 emitInlineAsmError(Call, "value out of range for constraint '" + 10257 Twine(OpInfo.ConstraintCode) + "'"); 10258 return; 10259 } 10260 10261 emitInlineAsmError(Call, 10262 "invalid operand for inline asm constraint '" + 10263 Twine(OpInfo.ConstraintCode) + "'"); 10264 return; 10265 } 10266 10267 // Add information to the INLINEASM node to know about this input. 10268 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 10269 AsmNodeOperands.push_back(DAG.getTargetConstant( 10270 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10271 llvm::append_range(AsmNodeOperands, Ops); 10272 break; 10273 } 10274 10275 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 10276 assert((OpInfo.isIndirect || 10277 OpInfo.ConstraintType != TargetLowering::C_Memory) && 10278 "Operand must be indirect to be a mem!"); 10279 assert(InOperandVal.getValueType() == 10280 TLI.getPointerTy(DAG.getDataLayout()) && 10281 "Memory operands expect pointer values"); 10282 10283 const InlineAsm::ConstraintCode ConstraintID = 10284 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10285 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10286 "Failed to convert memory constraint code to constraint id."); 10287 10288 // Add information to the INLINEASM node to know about this input. 10289 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 10290 ResOpType.setMemConstraint(ConstraintID); 10291 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 10292 getCurSDLoc(), 10293 MVT::i32)); 10294 AsmNodeOperands.push_back(InOperandVal); 10295 break; 10296 } 10297 10298 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 10299 const InlineAsm::ConstraintCode ConstraintID = 10300 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10301 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10302 "Failed to convert memory constraint code to constraint id."); 10303 10304 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 10305 10306 SDValue AsmOp = InOperandVal; 10307 if (isFunction(InOperandVal)) { 10308 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 10309 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 10310 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 10311 InOperandVal.getValueType(), 10312 GA->getOffset()); 10313 } 10314 10315 // Add information to the INLINEASM node to know about this input. 10316 ResOpType.setMemConstraint(ConstraintID); 10317 10318 AsmNodeOperands.push_back( 10319 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 10320 10321 AsmNodeOperands.push_back(AsmOp); 10322 break; 10323 } 10324 10325 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 10326 OpInfo.ConstraintType != TargetLowering::C_Register) { 10327 emitInlineAsmError(Call, "unknown asm constraint '" + 10328 Twine(OpInfo.ConstraintCode) + "'"); 10329 return; 10330 } 10331 10332 // TODO: Support this. 10333 if (OpInfo.isIndirect) { 10334 emitInlineAsmError( 10335 Call, "Don't know how to handle indirect register inputs yet " 10336 "for constraint '" + 10337 Twine(OpInfo.ConstraintCode) + "'"); 10338 return; 10339 } 10340 10341 // Copy the input into the appropriate registers. 10342 if (OpInfo.AssignedRegs.Regs.empty()) { 10343 emitInlineAsmError(Call, 10344 "couldn't allocate input reg for constraint '" + 10345 Twine(OpInfo.ConstraintCode) + "'"); 10346 return; 10347 } 10348 10349 if (DetectWriteToReservedRegister()) 10350 return; 10351 10352 SDLoc dl = getCurSDLoc(); 10353 10354 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 10355 &Call); 10356 10357 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 10358 0, dl, DAG, AsmNodeOperands); 10359 break; 10360 } 10361 case InlineAsm::isClobber: 10362 // Add the clobbered value to the operand list, so that the register 10363 // allocator is aware that the physreg got clobbered. 10364 if (!OpInfo.AssignedRegs.Regs.empty()) 10365 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 10366 false, 0, getCurSDLoc(), DAG, 10367 AsmNodeOperands); 10368 break; 10369 } 10370 } 10371 10372 // Finish up input operands. Set the input chain and add the flag last. 10373 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 10374 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 10375 10376 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 10377 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 10378 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 10379 Glue = Chain.getValue(1); 10380 10381 // Do additional work to generate outputs. 10382 10383 SmallVector<EVT, 1> ResultVTs; 10384 SmallVector<SDValue, 1> ResultValues; 10385 SmallVector<SDValue, 8> OutChains; 10386 10387 llvm::Type *CallResultType = Call.getType(); 10388 ArrayRef<Type *> ResultTypes; 10389 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 10390 ResultTypes = StructResult->elements(); 10391 else if (!CallResultType->isVoidTy()) 10392 ResultTypes = ArrayRef(CallResultType); 10393 10394 auto CurResultType = ResultTypes.begin(); 10395 auto handleRegAssign = [&](SDValue V) { 10396 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 10397 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 10398 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 10399 ++CurResultType; 10400 // If the type of the inline asm call site return value is different but has 10401 // same size as the type of the asm output bitcast it. One example of this 10402 // is for vectors with different width / number of elements. This can 10403 // happen for register classes that can contain multiple different value 10404 // types. The preg or vreg allocated may not have the same VT as was 10405 // expected. 10406 // 10407 // This can also happen for a return value that disagrees with the register 10408 // class it is put in, eg. a double in a general-purpose register on a 10409 // 32-bit machine. 10410 if (ResultVT != V.getValueType() && 10411 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 10412 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 10413 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 10414 V.getValueType().isInteger()) { 10415 // If a result value was tied to an input value, the computed result 10416 // may have a wider width than the expected result. Extract the 10417 // relevant portion. 10418 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 10419 } 10420 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 10421 ResultVTs.push_back(ResultVT); 10422 ResultValues.push_back(V); 10423 }; 10424 10425 // Deal with output operands. 10426 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10427 if (OpInfo.Type == InlineAsm::isOutput) { 10428 SDValue Val; 10429 // Skip trivial output operands. 10430 if (OpInfo.AssignedRegs.Regs.empty()) 10431 continue; 10432 10433 switch (OpInfo.ConstraintType) { 10434 case TargetLowering::C_Register: 10435 case TargetLowering::C_RegisterClass: 10436 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 10437 Chain, &Glue, &Call); 10438 break; 10439 case TargetLowering::C_Immediate: 10440 case TargetLowering::C_Other: 10441 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 10442 OpInfo, DAG); 10443 break; 10444 case TargetLowering::C_Memory: 10445 break; // Already handled. 10446 case TargetLowering::C_Address: 10447 break; // Silence warning. 10448 case TargetLowering::C_Unknown: 10449 assert(false && "Unexpected unknown constraint"); 10450 } 10451 10452 // Indirect output manifest as stores. Record output chains. 10453 if (OpInfo.isIndirect) { 10454 const Value *Ptr = OpInfo.CallOperandVal; 10455 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 10456 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 10457 MachinePointerInfo(Ptr)); 10458 OutChains.push_back(Store); 10459 } else { 10460 // generate CopyFromRegs to associated registers. 10461 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 10462 if (Val.getOpcode() == ISD::MERGE_VALUES) { 10463 for (const SDValue &V : Val->op_values()) 10464 handleRegAssign(V); 10465 } else 10466 handleRegAssign(Val); 10467 } 10468 } 10469 } 10470 10471 // Set results. 10472 if (!ResultValues.empty()) { 10473 assert(CurResultType == ResultTypes.end() && 10474 "Mismatch in number of ResultTypes"); 10475 assert(ResultValues.size() == ResultTypes.size() && 10476 "Mismatch in number of output operands in asm result"); 10477 10478 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10479 DAG.getVTList(ResultVTs), ResultValues); 10480 setValue(&Call, V); 10481 } 10482 10483 // Collect store chains. 10484 if (!OutChains.empty()) 10485 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 10486 10487 if (EmitEHLabels) { 10488 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 10489 } 10490 10491 // Only Update Root if inline assembly has a memory effect. 10492 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 10493 EmitEHLabels) 10494 DAG.setRoot(Chain); 10495 } 10496 10497 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 10498 const Twine &Message) { 10499 LLVMContext &Ctx = *DAG.getContext(); 10500 Ctx.emitError(&Call, Message); 10501 10502 // Make sure we leave the DAG in a valid state 10503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10504 SmallVector<EVT, 1> ValueVTs; 10505 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 10506 10507 if (ValueVTs.empty()) 10508 return; 10509 10510 SmallVector<SDValue, 1> Ops; 10511 for (const EVT &VT : ValueVTs) 10512 Ops.push_back(DAG.getUNDEF(VT)); 10513 10514 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 10515 } 10516 10517 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 10518 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 10519 MVT::Other, getRoot(), 10520 getValue(I.getArgOperand(0)), 10521 DAG.getSrcValue(I.getArgOperand(0)))); 10522 } 10523 10524 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 10525 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10526 const DataLayout &DL = DAG.getDataLayout(); 10527 SDValue V = DAG.getVAArg( 10528 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 10529 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 10530 DL.getABITypeAlign(I.getType()).value()); 10531 DAG.setRoot(V.getValue(1)); 10532 10533 if (I.getType()->isPointerTy()) 10534 V = DAG.getPtrExtOrTrunc( 10535 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 10536 setValue(&I, V); 10537 } 10538 10539 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 10540 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 10541 MVT::Other, getRoot(), 10542 getValue(I.getArgOperand(0)), 10543 DAG.getSrcValue(I.getArgOperand(0)))); 10544 } 10545 10546 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 10547 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 10548 MVT::Other, getRoot(), 10549 getValue(I.getArgOperand(0)), 10550 getValue(I.getArgOperand(1)), 10551 DAG.getSrcValue(I.getArgOperand(0)), 10552 DAG.getSrcValue(I.getArgOperand(1)))); 10553 } 10554 10555 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 10556 const Instruction &I, 10557 SDValue Op) { 10558 std::optional<ConstantRange> CR = getRange(I); 10559 10560 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped()) 10561 return Op; 10562 10563 APInt Lo = CR->getUnsignedMin(); 10564 if (!Lo.isMinValue()) 10565 return Op; 10566 10567 APInt Hi = CR->getUnsignedMax(); 10568 unsigned Bits = std::max(Hi.getActiveBits(), 10569 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 10570 10571 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 10572 10573 SDLoc SL = getCurSDLoc(); 10574 10575 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 10576 DAG.getValueType(SmallVT)); 10577 unsigned NumVals = Op.getNode()->getNumValues(); 10578 if (NumVals == 1) 10579 return ZExt; 10580 10581 SmallVector<SDValue, 4> Ops; 10582 10583 Ops.push_back(ZExt); 10584 for (unsigned I = 1; I != NumVals; ++I) 10585 Ops.push_back(Op.getValue(I)); 10586 10587 return DAG.getMergeValues(Ops, SL); 10588 } 10589 10590 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 10591 /// the call being lowered. 10592 /// 10593 /// This is a helper for lowering intrinsics that follow a target calling 10594 /// convention or require stack pointer adjustment. Only a subset of the 10595 /// intrinsic's operands need to participate in the calling convention. 10596 void SelectionDAGBuilder::populateCallLoweringInfo( 10597 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 10598 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 10599 AttributeSet RetAttrs, bool IsPatchPoint) { 10600 TargetLowering::ArgListTy Args; 10601 Args.reserve(NumArgs); 10602 10603 // Populate the argument list. 10604 // Attributes for args start at offset 1, after the return attribute. 10605 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 10606 ArgI != ArgE; ++ArgI) { 10607 const Value *V = Call->getOperand(ArgI); 10608 10609 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 10610 10611 TargetLowering::ArgListEntry Entry; 10612 Entry.Node = getValue(V); 10613 Entry.Ty = V->getType(); 10614 Entry.setAttributes(Call, ArgI); 10615 Args.push_back(Entry); 10616 } 10617 10618 CLI.setDebugLoc(getCurSDLoc()) 10619 .setChain(getRoot()) 10620 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 10621 RetAttrs) 10622 .setDiscardResult(Call->use_empty()) 10623 .setIsPatchPoint(IsPatchPoint) 10624 .setIsPreallocated( 10625 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 10626 } 10627 10628 /// Add a stack map intrinsic call's live variable operands to a stackmap 10629 /// or patchpoint target node's operand list. 10630 /// 10631 /// Constants are converted to TargetConstants purely as an optimization to 10632 /// avoid constant materialization and register allocation. 10633 /// 10634 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 10635 /// generate addess computation nodes, and so FinalizeISel can convert the 10636 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10637 /// address materialization and register allocation, but may also be required 10638 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10639 /// alloca in the entry block, then the runtime may assume that the alloca's 10640 /// StackMap location can be read immediately after compilation and that the 10641 /// location is valid at any point during execution (this is similar to the 10642 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10643 /// only available in a register, then the runtime would need to trap when 10644 /// execution reaches the StackMap in order to read the alloca's location. 10645 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10646 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10647 SelectionDAGBuilder &Builder) { 10648 SelectionDAG &DAG = Builder.DAG; 10649 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10650 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10651 10652 // Things on the stack are pointer-typed, meaning that they are already 10653 // legal and can be emitted directly to target nodes. 10654 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10655 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10656 } else { 10657 // Otherwise emit a target independent node to be legalised. 10658 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10659 } 10660 } 10661 } 10662 10663 /// Lower llvm.experimental.stackmap. 10664 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10665 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10666 // [live variables...]) 10667 10668 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10669 10670 SDValue Chain, InGlue, Callee; 10671 SmallVector<SDValue, 32> Ops; 10672 10673 SDLoc DL = getCurSDLoc(); 10674 Callee = getValue(CI.getCalledOperand()); 10675 10676 // The stackmap intrinsic only records the live variables (the arguments 10677 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10678 // intrinsic, this won't be lowered to a function call. This means we don't 10679 // have to worry about calling conventions and target specific lowering code. 10680 // Instead we perform the call lowering right here. 10681 // 10682 // chain, flag = CALLSEQ_START(chain, 0, 0) 10683 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10684 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10685 // 10686 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10687 InGlue = Chain.getValue(1); 10688 10689 // Add the STACKMAP operands, starting with DAG house-keeping. 10690 Ops.push_back(Chain); 10691 Ops.push_back(InGlue); 10692 10693 // Add the <id>, <numShadowBytes> operands. 10694 // 10695 // These do not require legalisation, and can be emitted directly to target 10696 // constant nodes. 10697 SDValue ID = getValue(CI.getArgOperand(0)); 10698 assert(ID.getValueType() == MVT::i64); 10699 SDValue IDConst = 10700 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10701 Ops.push_back(IDConst); 10702 10703 SDValue Shad = getValue(CI.getArgOperand(1)); 10704 assert(Shad.getValueType() == MVT::i32); 10705 SDValue ShadConst = 10706 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10707 Ops.push_back(ShadConst); 10708 10709 // Add the live variables. 10710 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10711 10712 // Create the STACKMAP node. 10713 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10714 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10715 InGlue = Chain.getValue(1); 10716 10717 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10718 10719 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10720 10721 // Set the root to the target-lowered call chain. 10722 DAG.setRoot(Chain); 10723 10724 // Inform the Frame Information that we have a stackmap in this function. 10725 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10726 } 10727 10728 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10729 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10730 const BasicBlock *EHPadBB) { 10731 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>, 10732 // i32 <numBytes>, 10733 // i8* <target>, 10734 // i32 <numArgs>, 10735 // [Args...], 10736 // [live variables...]) 10737 10738 CallingConv::ID CC = CB.getCallingConv(); 10739 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10740 bool HasDef = !CB.getType()->isVoidTy(); 10741 SDLoc dl = getCurSDLoc(); 10742 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10743 10744 // Handle immediate and symbolic callees. 10745 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10746 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10747 /*isTarget=*/true); 10748 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10749 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10750 SDLoc(SymbolicCallee), 10751 SymbolicCallee->getValueType(0)); 10752 10753 // Get the real number of arguments participating in the call <numArgs> 10754 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10755 unsigned NumArgs = NArgVal->getAsZExtVal(); 10756 10757 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10758 // Intrinsics include all meta-operands up to but not including CC. 10759 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10760 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10761 "Not enough arguments provided to the patchpoint intrinsic"); 10762 10763 // For AnyRegCC the arguments are lowered later on manually. 10764 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10765 Type *ReturnTy = 10766 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10767 10768 TargetLowering::CallLoweringInfo CLI(DAG); 10769 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10770 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10771 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10772 10773 SDNode *CallEnd = Result.second.getNode(); 10774 if (CallEnd->getOpcode() == ISD::EH_LABEL) 10775 CallEnd = CallEnd->getOperand(0).getNode(); 10776 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10777 CallEnd = CallEnd->getOperand(0).getNode(); 10778 10779 /// Get a call instruction from the call sequence chain. 10780 /// Tail calls are not allowed. 10781 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10782 "Expected a callseq node."); 10783 SDNode *Call = CallEnd->getOperand(0).getNode(); 10784 bool HasGlue = Call->getGluedNode(); 10785 10786 // Replace the target specific call node with the patchable intrinsic. 10787 SmallVector<SDValue, 8> Ops; 10788 10789 // Push the chain. 10790 Ops.push_back(*(Call->op_begin())); 10791 10792 // Optionally, push the glue (if any). 10793 if (HasGlue) 10794 Ops.push_back(*(Call->op_end() - 1)); 10795 10796 // Push the register mask info. 10797 if (HasGlue) 10798 Ops.push_back(*(Call->op_end() - 2)); 10799 else 10800 Ops.push_back(*(Call->op_end() - 1)); 10801 10802 // Add the <id> and <numBytes> constants. 10803 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10804 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10805 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10806 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10807 10808 // Add the callee. 10809 Ops.push_back(Callee); 10810 10811 // Adjust <numArgs> to account for any arguments that have been passed on the 10812 // stack instead. 10813 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10814 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10815 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10816 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10817 10818 // Add the calling convention 10819 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10820 10821 // Add the arguments we omitted previously. The register allocator should 10822 // place these in any free register. 10823 if (IsAnyRegCC) 10824 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10825 Ops.push_back(getValue(CB.getArgOperand(i))); 10826 10827 // Push the arguments from the call instruction. 10828 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10829 Ops.append(Call->op_begin() + 2, e); 10830 10831 // Push live variables for the stack map. 10832 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10833 10834 SDVTList NodeTys; 10835 if (IsAnyRegCC && HasDef) { 10836 // Create the return types based on the intrinsic definition 10837 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10838 SmallVector<EVT, 3> ValueVTs; 10839 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10840 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10841 10842 // There is always a chain and a glue type at the end 10843 ValueVTs.push_back(MVT::Other); 10844 ValueVTs.push_back(MVT::Glue); 10845 NodeTys = DAG.getVTList(ValueVTs); 10846 } else 10847 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10848 10849 // Replace the target specific call node with a PATCHPOINT node. 10850 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10851 10852 // Update the NodeMap. 10853 if (HasDef) { 10854 if (IsAnyRegCC) 10855 setValue(&CB, SDValue(PPV.getNode(), 0)); 10856 else 10857 setValue(&CB, Result.first); 10858 } 10859 10860 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10861 // call sequence. Furthermore the location of the chain and glue can change 10862 // when the AnyReg calling convention is used and the intrinsic returns a 10863 // value. 10864 if (IsAnyRegCC && HasDef) { 10865 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10866 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10867 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10868 } else 10869 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10870 DAG.DeleteNode(Call); 10871 10872 // Inform the Frame Information that we have a patchpoint in this function. 10873 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10874 } 10875 10876 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10877 unsigned Intrinsic) { 10878 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10879 SDValue Op1 = getValue(I.getArgOperand(0)); 10880 SDValue Op2; 10881 if (I.arg_size() > 1) 10882 Op2 = getValue(I.getArgOperand(1)); 10883 SDLoc dl = getCurSDLoc(); 10884 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10885 SDValue Res; 10886 SDNodeFlags SDFlags; 10887 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10888 SDFlags.copyFMF(*FPMO); 10889 10890 switch (Intrinsic) { 10891 case Intrinsic::vector_reduce_fadd: 10892 if (SDFlags.hasAllowReassociation()) 10893 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10894 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10895 SDFlags); 10896 else 10897 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10898 break; 10899 case Intrinsic::vector_reduce_fmul: 10900 if (SDFlags.hasAllowReassociation()) 10901 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10902 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10903 SDFlags); 10904 else 10905 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10906 break; 10907 case Intrinsic::vector_reduce_add: 10908 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10909 break; 10910 case Intrinsic::vector_reduce_mul: 10911 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10912 break; 10913 case Intrinsic::vector_reduce_and: 10914 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10915 break; 10916 case Intrinsic::vector_reduce_or: 10917 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10918 break; 10919 case Intrinsic::vector_reduce_xor: 10920 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10921 break; 10922 case Intrinsic::vector_reduce_smax: 10923 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10924 break; 10925 case Intrinsic::vector_reduce_smin: 10926 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10927 break; 10928 case Intrinsic::vector_reduce_umax: 10929 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10930 break; 10931 case Intrinsic::vector_reduce_umin: 10932 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10933 break; 10934 case Intrinsic::vector_reduce_fmax: 10935 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10936 break; 10937 case Intrinsic::vector_reduce_fmin: 10938 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10939 break; 10940 case Intrinsic::vector_reduce_fmaximum: 10941 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10942 break; 10943 case Intrinsic::vector_reduce_fminimum: 10944 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10945 break; 10946 default: 10947 llvm_unreachable("Unhandled vector reduce intrinsic"); 10948 } 10949 setValue(&I, Res); 10950 } 10951 10952 /// Returns an AttributeList representing the attributes applied to the return 10953 /// value of the given call. 10954 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10955 SmallVector<Attribute::AttrKind, 2> Attrs; 10956 if (CLI.RetSExt) 10957 Attrs.push_back(Attribute::SExt); 10958 if (CLI.RetZExt) 10959 Attrs.push_back(Attribute::ZExt); 10960 if (CLI.IsInReg) 10961 Attrs.push_back(Attribute::InReg); 10962 10963 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10964 Attrs); 10965 } 10966 10967 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10968 /// implementation, which just calls LowerCall. 10969 /// FIXME: When all targets are 10970 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10971 std::pair<SDValue, SDValue> 10972 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10973 // Handle the incoming return values from the call. 10974 CLI.Ins.clear(); 10975 Type *OrigRetTy = CLI.RetTy; 10976 SmallVector<EVT, 4> RetTys; 10977 SmallVector<TypeSize, 4> Offsets; 10978 auto &DL = CLI.DAG.getDataLayout(); 10979 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 10980 10981 if (CLI.IsPostTypeLegalization) { 10982 // If we are lowering a libcall after legalization, split the return type. 10983 SmallVector<EVT, 4> OldRetTys; 10984 SmallVector<TypeSize, 4> OldOffsets; 10985 RetTys.swap(OldRetTys); 10986 Offsets.swap(OldOffsets); 10987 10988 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10989 EVT RetVT = OldRetTys[i]; 10990 uint64_t Offset = OldOffsets[i]; 10991 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10992 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10993 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10994 RetTys.append(NumRegs, RegisterVT); 10995 for (unsigned j = 0; j != NumRegs; ++j) 10996 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ)); 10997 } 10998 } 10999 11000 SmallVector<ISD::OutputArg, 4> Outs; 11001 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 11002 11003 bool CanLowerReturn = 11004 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 11005 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 11006 11007 SDValue DemoteStackSlot; 11008 int DemoteStackIdx = -100; 11009 if (!CanLowerReturn) { 11010 // FIXME: equivalent assert? 11011 // assert(!CS.hasInAllocaArgument() && 11012 // "sret demotion is incompatible with inalloca"); 11013 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 11014 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 11015 MachineFunction &MF = CLI.DAG.getMachineFunction(); 11016 DemoteStackIdx = 11017 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 11018 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 11019 DL.getAllocaAddrSpace()); 11020 11021 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 11022 ArgListEntry Entry; 11023 Entry.Node = DemoteStackSlot; 11024 Entry.Ty = StackSlotPtrType; 11025 Entry.IsSExt = false; 11026 Entry.IsZExt = false; 11027 Entry.IsInReg = false; 11028 Entry.IsSRet = true; 11029 Entry.IsNest = false; 11030 Entry.IsByVal = false; 11031 Entry.IsByRef = false; 11032 Entry.IsReturned = false; 11033 Entry.IsSwiftSelf = false; 11034 Entry.IsSwiftAsync = false; 11035 Entry.IsSwiftError = false; 11036 Entry.IsCFGuardTarget = false; 11037 Entry.Alignment = Alignment; 11038 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 11039 CLI.NumFixedArgs += 1; 11040 CLI.getArgs()[0].IndirectType = CLI.RetTy; 11041 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 11042 11043 // sret demotion isn't compatible with tail-calls, since the sret argument 11044 // points into the callers stack frame. 11045 CLI.IsTailCall = false; 11046 } else { 11047 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 11048 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 11049 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 11050 ISD::ArgFlagsTy Flags; 11051 if (NeedsRegBlock) { 11052 Flags.setInConsecutiveRegs(); 11053 if (I == RetTys.size() - 1) 11054 Flags.setInConsecutiveRegsLast(); 11055 } 11056 EVT VT = RetTys[I]; 11057 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11058 CLI.CallConv, VT); 11059 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11060 CLI.CallConv, VT); 11061 for (unsigned i = 0; i != NumRegs; ++i) { 11062 ISD::InputArg MyFlags; 11063 MyFlags.Flags = Flags; 11064 MyFlags.VT = RegisterVT; 11065 MyFlags.ArgVT = VT; 11066 MyFlags.Used = CLI.IsReturnValueUsed; 11067 if (CLI.RetTy->isPointerTy()) { 11068 MyFlags.Flags.setPointer(); 11069 MyFlags.Flags.setPointerAddrSpace( 11070 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 11071 } 11072 if (CLI.RetSExt) 11073 MyFlags.Flags.setSExt(); 11074 if (CLI.RetZExt) 11075 MyFlags.Flags.setZExt(); 11076 if (CLI.IsInReg) 11077 MyFlags.Flags.setInReg(); 11078 CLI.Ins.push_back(MyFlags); 11079 } 11080 } 11081 } 11082 11083 // We push in swifterror return as the last element of CLI.Ins. 11084 ArgListTy &Args = CLI.getArgs(); 11085 if (supportSwiftError()) { 11086 for (const ArgListEntry &Arg : Args) { 11087 if (Arg.IsSwiftError) { 11088 ISD::InputArg MyFlags; 11089 MyFlags.VT = getPointerTy(DL); 11090 MyFlags.ArgVT = EVT(getPointerTy(DL)); 11091 MyFlags.Flags.setSwiftError(); 11092 CLI.Ins.push_back(MyFlags); 11093 } 11094 } 11095 } 11096 11097 // Handle all of the outgoing arguments. 11098 CLI.Outs.clear(); 11099 CLI.OutVals.clear(); 11100 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 11101 SmallVector<EVT, 4> ValueVTs; 11102 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 11103 // FIXME: Split arguments if CLI.IsPostTypeLegalization 11104 Type *FinalType = Args[i].Ty; 11105 if (Args[i].IsByVal) 11106 FinalType = Args[i].IndirectType; 11107 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 11108 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 11109 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 11110 ++Value) { 11111 EVT VT = ValueVTs[Value]; 11112 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 11113 SDValue Op = SDValue(Args[i].Node.getNode(), 11114 Args[i].Node.getResNo() + Value); 11115 ISD::ArgFlagsTy Flags; 11116 11117 // Certain targets (such as MIPS), may have a different ABI alignment 11118 // for a type depending on the context. Give the target a chance to 11119 // specify the alignment it wants. 11120 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 11121 Flags.setOrigAlign(OriginalAlignment); 11122 11123 if (Args[i].Ty->isPointerTy()) { 11124 Flags.setPointer(); 11125 Flags.setPointerAddrSpace( 11126 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 11127 } 11128 if (Args[i].IsZExt) 11129 Flags.setZExt(); 11130 if (Args[i].IsSExt) 11131 Flags.setSExt(); 11132 if (Args[i].IsNoExt) 11133 Flags.setNoExt(); 11134 if (Args[i].IsInReg) { 11135 // If we are using vectorcall calling convention, a structure that is 11136 // passed InReg - is surely an HVA 11137 if (CLI.CallConv == CallingConv::X86_VectorCall && 11138 isa<StructType>(FinalType)) { 11139 // The first value of a structure is marked 11140 if (0 == Value) 11141 Flags.setHvaStart(); 11142 Flags.setHva(); 11143 } 11144 // Set InReg Flag 11145 Flags.setInReg(); 11146 } 11147 if (Args[i].IsSRet) 11148 Flags.setSRet(); 11149 if (Args[i].IsSwiftSelf) 11150 Flags.setSwiftSelf(); 11151 if (Args[i].IsSwiftAsync) 11152 Flags.setSwiftAsync(); 11153 if (Args[i].IsSwiftError) 11154 Flags.setSwiftError(); 11155 if (Args[i].IsCFGuardTarget) 11156 Flags.setCFGuardTarget(); 11157 if (Args[i].IsByVal) 11158 Flags.setByVal(); 11159 if (Args[i].IsByRef) 11160 Flags.setByRef(); 11161 if (Args[i].IsPreallocated) { 11162 Flags.setPreallocated(); 11163 // Set the byval flag for CCAssignFn callbacks that don't know about 11164 // preallocated. This way we can know how many bytes we should've 11165 // allocated and how many bytes a callee cleanup function will pop. If 11166 // we port preallocated to more targets, we'll have to add custom 11167 // preallocated handling in the various CC lowering callbacks. 11168 Flags.setByVal(); 11169 } 11170 if (Args[i].IsInAlloca) { 11171 Flags.setInAlloca(); 11172 // Set the byval flag for CCAssignFn callbacks that don't know about 11173 // inalloca. This way we can know how many bytes we should've allocated 11174 // and how many bytes a callee cleanup function will pop. If we port 11175 // inalloca to more targets, we'll have to add custom inalloca handling 11176 // in the various CC lowering callbacks. 11177 Flags.setByVal(); 11178 } 11179 Align MemAlign; 11180 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 11181 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 11182 Flags.setByValSize(FrameSize); 11183 11184 // info is not there but there are cases it cannot get right. 11185 if (auto MA = Args[i].Alignment) 11186 MemAlign = *MA; 11187 else 11188 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 11189 } else if (auto MA = Args[i].Alignment) { 11190 MemAlign = *MA; 11191 } else { 11192 MemAlign = OriginalAlignment; 11193 } 11194 Flags.setMemAlign(MemAlign); 11195 if (Args[i].IsNest) 11196 Flags.setNest(); 11197 if (NeedsRegBlock) 11198 Flags.setInConsecutiveRegs(); 11199 11200 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11201 CLI.CallConv, VT); 11202 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11203 CLI.CallConv, VT); 11204 SmallVector<SDValue, 4> Parts(NumParts); 11205 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 11206 11207 if (Args[i].IsSExt) 11208 ExtendKind = ISD::SIGN_EXTEND; 11209 else if (Args[i].IsZExt) 11210 ExtendKind = ISD::ZERO_EXTEND; 11211 11212 // Conservatively only handle 'returned' on non-vectors that can be lowered, 11213 // for now. 11214 if (Args[i].IsReturned && !Op.getValueType().isVector() && 11215 CanLowerReturn) { 11216 assert((CLI.RetTy == Args[i].Ty || 11217 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 11218 CLI.RetTy->getPointerAddressSpace() == 11219 Args[i].Ty->getPointerAddressSpace())) && 11220 RetTys.size() == NumValues && "unexpected use of 'returned'"); 11221 // Before passing 'returned' to the target lowering code, ensure that 11222 // either the register MVT and the actual EVT are the same size or that 11223 // the return value and argument are extended in the same way; in these 11224 // cases it's safe to pass the argument register value unchanged as the 11225 // return register value (although it's at the target's option whether 11226 // to do so) 11227 // TODO: allow code generation to take advantage of partially preserved 11228 // registers rather than clobbering the entire register when the 11229 // parameter extension method is not compatible with the return 11230 // extension method 11231 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 11232 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 11233 CLI.RetZExt == Args[i].IsZExt)) 11234 Flags.setReturned(); 11235 } 11236 11237 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 11238 CLI.CallConv, ExtendKind); 11239 11240 for (unsigned j = 0; j != NumParts; ++j) { 11241 // if it isn't first piece, alignment must be 1 11242 // For scalable vectors the scalable part is currently handled 11243 // by individual targets, so we just use the known minimum size here. 11244 ISD::OutputArg MyFlags( 11245 Flags, Parts[j].getValueType().getSimpleVT(), VT, 11246 i < CLI.NumFixedArgs, i, 11247 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 11248 if (NumParts > 1 && j == 0) 11249 MyFlags.Flags.setSplit(); 11250 else if (j != 0) { 11251 MyFlags.Flags.setOrigAlign(Align(1)); 11252 if (j == NumParts - 1) 11253 MyFlags.Flags.setSplitEnd(); 11254 } 11255 11256 CLI.Outs.push_back(MyFlags); 11257 CLI.OutVals.push_back(Parts[j]); 11258 } 11259 11260 if (NeedsRegBlock && Value == NumValues - 1) 11261 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 11262 } 11263 } 11264 11265 SmallVector<SDValue, 4> InVals; 11266 CLI.Chain = LowerCall(CLI, InVals); 11267 11268 // Update CLI.InVals to use outside of this function. 11269 CLI.InVals = InVals; 11270 11271 // Verify that the target's LowerCall behaved as expected. 11272 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 11273 "LowerCall didn't return a valid chain!"); 11274 assert((!CLI.IsTailCall || InVals.empty()) && 11275 "LowerCall emitted a return value for a tail call!"); 11276 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 11277 "LowerCall didn't emit the correct number of values!"); 11278 11279 // For a tail call, the return value is merely live-out and there aren't 11280 // any nodes in the DAG representing it. Return a special value to 11281 // indicate that a tail call has been emitted and no more Instructions 11282 // should be processed in the current block. 11283 if (CLI.IsTailCall) { 11284 CLI.DAG.setRoot(CLI.Chain); 11285 return std::make_pair(SDValue(), SDValue()); 11286 } 11287 11288 #ifndef NDEBUG 11289 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 11290 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 11291 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 11292 "LowerCall emitted a value with the wrong type!"); 11293 } 11294 #endif 11295 11296 SmallVector<SDValue, 4> ReturnValues; 11297 if (!CanLowerReturn) { 11298 // The instruction result is the result of loading from the 11299 // hidden sret parameter. 11300 SmallVector<EVT, 1> PVTs; 11301 Type *PtrRetTy = 11302 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 11303 11304 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 11305 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 11306 EVT PtrVT = PVTs[0]; 11307 11308 unsigned NumValues = RetTys.size(); 11309 ReturnValues.resize(NumValues); 11310 SmallVector<SDValue, 4> Chains(NumValues); 11311 11312 // An aggregate return value cannot wrap around the address space, so 11313 // offsets to its parts don't wrap either. 11314 MachineFunction &MF = CLI.DAG.getMachineFunction(); 11315 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 11316 for (unsigned i = 0; i < NumValues; ++i) { 11317 SDValue Add = 11318 CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 11319 CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT), 11320 SDNodeFlags::NoUnsignedWrap); 11321 SDValue L = CLI.DAG.getLoad( 11322 RetTys[i], CLI.DL, CLI.Chain, Add, 11323 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 11324 DemoteStackIdx, Offsets[i]), 11325 HiddenSRetAlign); 11326 ReturnValues[i] = L; 11327 Chains[i] = L.getValue(1); 11328 } 11329 11330 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 11331 } else { 11332 // Collect the legal value parts into potentially illegal values 11333 // that correspond to the original function's return values. 11334 std::optional<ISD::NodeType> AssertOp; 11335 if (CLI.RetSExt) 11336 AssertOp = ISD::AssertSext; 11337 else if (CLI.RetZExt) 11338 AssertOp = ISD::AssertZext; 11339 unsigned CurReg = 0; 11340 for (EVT VT : RetTys) { 11341 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11342 CLI.CallConv, VT); 11343 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11344 CLI.CallConv, VT); 11345 11346 ReturnValues.push_back(getCopyFromParts( 11347 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 11348 CLI.Chain, CLI.CallConv, AssertOp)); 11349 CurReg += NumRegs; 11350 } 11351 11352 // For a function returning void, there is no return value. We can't create 11353 // such a node, so we just return a null return value in that case. In 11354 // that case, nothing will actually look at the value. 11355 if (ReturnValues.empty()) 11356 return std::make_pair(SDValue(), CLI.Chain); 11357 } 11358 11359 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 11360 CLI.DAG.getVTList(RetTys), ReturnValues); 11361 return std::make_pair(Res, CLI.Chain); 11362 } 11363 11364 /// Places new result values for the node in Results (their number 11365 /// and types must exactly match those of the original return values of 11366 /// the node), or leaves Results empty, which indicates that the node is not 11367 /// to be custom lowered after all. 11368 void TargetLowering::LowerOperationWrapper(SDNode *N, 11369 SmallVectorImpl<SDValue> &Results, 11370 SelectionDAG &DAG) const { 11371 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 11372 11373 if (!Res.getNode()) 11374 return; 11375 11376 // If the original node has one result, take the return value from 11377 // LowerOperation as is. It might not be result number 0. 11378 if (N->getNumValues() == 1) { 11379 Results.push_back(Res); 11380 return; 11381 } 11382 11383 // If the original node has multiple results, then the return node should 11384 // have the same number of results. 11385 assert((N->getNumValues() == Res->getNumValues()) && 11386 "Lowering returned the wrong number of results!"); 11387 11388 // Places new result values base on N result number. 11389 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 11390 Results.push_back(Res.getValue(I)); 11391 } 11392 11393 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11394 llvm_unreachable("LowerOperation not implemented for this target!"); 11395 } 11396 11397 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 11398 unsigned Reg, 11399 ISD::NodeType ExtendType) { 11400 SDValue Op = getNonRegisterValue(V); 11401 assert((Op.getOpcode() != ISD::CopyFromReg || 11402 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 11403 "Copy from a reg to the same reg!"); 11404 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 11405 11406 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11407 // If this is an InlineAsm we have to match the registers required, not the 11408 // notional registers required by the type. 11409 11410 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 11411 std::nullopt); // This is not an ABI copy. 11412 SDValue Chain = DAG.getEntryNode(); 11413 11414 if (ExtendType == ISD::ANY_EXTEND) { 11415 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 11416 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 11417 ExtendType = PreferredExtendIt->second; 11418 } 11419 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 11420 PendingExports.push_back(Chain); 11421 } 11422 11423 #include "llvm/CodeGen/SelectionDAGISel.h" 11424 11425 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 11426 /// entry block, return true. This includes arguments used by switches, since 11427 /// the switch may expand into multiple basic blocks. 11428 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 11429 // With FastISel active, we may be splitting blocks, so force creation 11430 // of virtual registers for all non-dead arguments. 11431 if (FastISel) 11432 return A->use_empty(); 11433 11434 const BasicBlock &Entry = A->getParent()->front(); 11435 for (const User *U : A->users()) 11436 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 11437 return false; // Use not in entry block. 11438 11439 return true; 11440 } 11441 11442 using ArgCopyElisionMapTy = 11443 DenseMap<const Argument *, 11444 std::pair<const AllocaInst *, const StoreInst *>>; 11445 11446 /// Scan the entry block of the function in FuncInfo for arguments that look 11447 /// like copies into a local alloca. Record any copied arguments in 11448 /// ArgCopyElisionCandidates. 11449 static void 11450 findArgumentCopyElisionCandidates(const DataLayout &DL, 11451 FunctionLoweringInfo *FuncInfo, 11452 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 11453 // Record the state of every static alloca used in the entry block. Argument 11454 // allocas are all used in the entry block, so we need approximately as many 11455 // entries as we have arguments. 11456 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 11457 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 11458 unsigned NumArgs = FuncInfo->Fn->arg_size(); 11459 StaticAllocas.reserve(NumArgs * 2); 11460 11461 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 11462 if (!V) 11463 return nullptr; 11464 V = V->stripPointerCasts(); 11465 const auto *AI = dyn_cast<AllocaInst>(V); 11466 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 11467 return nullptr; 11468 auto Iter = StaticAllocas.insert({AI, Unknown}); 11469 return &Iter.first->second; 11470 }; 11471 11472 // Look for stores of arguments to static allocas. Look through bitcasts and 11473 // GEPs to handle type coercions, as long as the alloca is fully initialized 11474 // by the store. Any non-store use of an alloca escapes it and any subsequent 11475 // unanalyzed store might write it. 11476 // FIXME: Handle structs initialized with multiple stores. 11477 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 11478 // Look for stores, and handle non-store uses conservatively. 11479 const auto *SI = dyn_cast<StoreInst>(&I); 11480 if (!SI) { 11481 // We will look through cast uses, so ignore them completely. 11482 if (I.isCast()) 11483 continue; 11484 // Ignore debug info and pseudo op intrinsics, they don't escape or store 11485 // to allocas. 11486 if (I.isDebugOrPseudoInst()) 11487 continue; 11488 // This is an unknown instruction. Assume it escapes or writes to all 11489 // static alloca operands. 11490 for (const Use &U : I.operands()) { 11491 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 11492 *Info = StaticAllocaInfo::Clobbered; 11493 } 11494 continue; 11495 } 11496 11497 // If the stored value is a static alloca, mark it as escaped. 11498 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 11499 *Info = StaticAllocaInfo::Clobbered; 11500 11501 // Check if the destination is a static alloca. 11502 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 11503 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 11504 if (!Info) 11505 continue; 11506 const AllocaInst *AI = cast<AllocaInst>(Dst); 11507 11508 // Skip allocas that have been initialized or clobbered. 11509 if (*Info != StaticAllocaInfo::Unknown) 11510 continue; 11511 11512 // Check if the stored value is an argument, and that this store fully 11513 // initializes the alloca. 11514 // If the argument type has padding bits we can't directly forward a pointer 11515 // as the upper bits may contain garbage. 11516 // Don't elide copies from the same argument twice. 11517 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 11518 const auto *Arg = dyn_cast<Argument>(Val); 11519 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 11520 Arg->getType()->isEmptyTy() || 11521 DL.getTypeStoreSize(Arg->getType()) != 11522 DL.getTypeAllocSize(AI->getAllocatedType()) || 11523 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 11524 ArgCopyElisionCandidates.count(Arg)) { 11525 *Info = StaticAllocaInfo::Clobbered; 11526 continue; 11527 } 11528 11529 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 11530 << '\n'); 11531 11532 // Mark this alloca and store for argument copy elision. 11533 *Info = StaticAllocaInfo::Elidable; 11534 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 11535 11536 // Stop scanning if we've seen all arguments. This will happen early in -O0 11537 // builds, which is useful, because -O0 builds have large entry blocks and 11538 // many allocas. 11539 if (ArgCopyElisionCandidates.size() == NumArgs) 11540 break; 11541 } 11542 } 11543 11544 /// Try to elide argument copies from memory into a local alloca. Succeeds if 11545 /// ArgVal is a load from a suitable fixed stack object. 11546 static void tryToElideArgumentCopy( 11547 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 11548 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 11549 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 11550 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 11551 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 11552 // Check if this is a load from a fixed stack object. 11553 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 11554 if (!LNode) 11555 return; 11556 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 11557 if (!FINode) 11558 return; 11559 11560 // Check that the fixed stack object is the right size and alignment. 11561 // Look at the alignment that the user wrote on the alloca instead of looking 11562 // at the stack object. 11563 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 11564 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 11565 const AllocaInst *AI = ArgCopyIter->second.first; 11566 int FixedIndex = FINode->getIndex(); 11567 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 11568 int OldIndex = AllocaIndex; 11569 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 11570 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 11571 LLVM_DEBUG( 11572 dbgs() << " argument copy elision failed due to bad fixed stack " 11573 "object size\n"); 11574 return; 11575 } 11576 Align RequiredAlignment = AI->getAlign(); 11577 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 11578 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 11579 "greater than stack argument alignment (" 11580 << DebugStr(RequiredAlignment) << " vs " 11581 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 11582 return; 11583 } 11584 11585 // Perform the elision. Delete the old stack object and replace its only use 11586 // in the variable info map. Mark the stack object as mutable and aliased. 11587 LLVM_DEBUG({ 11588 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 11589 << " Replacing frame index " << OldIndex << " with " << FixedIndex 11590 << '\n'; 11591 }); 11592 MFI.RemoveStackObject(OldIndex); 11593 MFI.setIsImmutableObjectIndex(FixedIndex, false); 11594 MFI.setIsAliasedObjectIndex(FixedIndex, true); 11595 AllocaIndex = FixedIndex; 11596 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 11597 for (SDValue ArgVal : ArgVals) 11598 Chains.push_back(ArgVal.getValue(1)); 11599 11600 // Avoid emitting code for the store implementing the copy. 11601 const StoreInst *SI = ArgCopyIter->second.second; 11602 ElidedArgCopyInstrs.insert(SI); 11603 11604 // Check for uses of the argument again so that we can avoid exporting ArgVal 11605 // if it is't used by anything other than the store. 11606 for (const Value *U : Arg.users()) { 11607 if (U != SI) { 11608 ArgHasUses = true; 11609 break; 11610 } 11611 } 11612 } 11613 11614 void SelectionDAGISel::LowerArguments(const Function &F) { 11615 SelectionDAG &DAG = SDB->DAG; 11616 SDLoc dl = SDB->getCurSDLoc(); 11617 const DataLayout &DL = DAG.getDataLayout(); 11618 SmallVector<ISD::InputArg, 16> Ins; 11619 11620 // In Naked functions we aren't going to save any registers. 11621 if (F.hasFnAttribute(Attribute::Naked)) 11622 return; 11623 11624 if (!FuncInfo->CanLowerReturn) { 11625 // Put in an sret pointer parameter before all the other parameters. 11626 SmallVector<EVT, 1> ValueVTs; 11627 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11628 PointerType::get(F.getContext(), 11629 DAG.getDataLayout().getAllocaAddrSpace()), 11630 ValueVTs); 11631 11632 // NOTE: Assuming that a pointer will never break down to more than one VT 11633 // or one register. 11634 ISD::ArgFlagsTy Flags; 11635 Flags.setSRet(); 11636 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 11637 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 11638 ISD::InputArg::NoArgIndex, 0); 11639 Ins.push_back(RetArg); 11640 } 11641 11642 // Look for stores of arguments to static allocas. Mark such arguments with a 11643 // flag to ask the target to give us the memory location of that argument if 11644 // available. 11645 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11646 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11647 ArgCopyElisionCandidates); 11648 11649 // Set up the incoming argument description vector. 11650 for (const Argument &Arg : F.args()) { 11651 unsigned ArgNo = Arg.getArgNo(); 11652 SmallVector<EVT, 4> ValueVTs; 11653 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11654 bool isArgValueUsed = !Arg.use_empty(); 11655 unsigned PartBase = 0; 11656 Type *FinalType = Arg.getType(); 11657 if (Arg.hasAttribute(Attribute::ByVal)) 11658 FinalType = Arg.getParamByValType(); 11659 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11660 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11661 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11662 Value != NumValues; ++Value) { 11663 EVT VT = ValueVTs[Value]; 11664 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11665 ISD::ArgFlagsTy Flags; 11666 11667 11668 if (Arg.getType()->isPointerTy()) { 11669 Flags.setPointer(); 11670 Flags.setPointerAddrSpace( 11671 cast<PointerType>(Arg.getType())->getAddressSpace()); 11672 } 11673 if (Arg.hasAttribute(Attribute::ZExt)) 11674 Flags.setZExt(); 11675 if (Arg.hasAttribute(Attribute::SExt)) 11676 Flags.setSExt(); 11677 if (Arg.hasAttribute(Attribute::InReg)) { 11678 // If we are using vectorcall calling convention, a structure that is 11679 // passed InReg - is surely an HVA 11680 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11681 isa<StructType>(Arg.getType())) { 11682 // The first value of a structure is marked 11683 if (0 == Value) 11684 Flags.setHvaStart(); 11685 Flags.setHva(); 11686 } 11687 // Set InReg Flag 11688 Flags.setInReg(); 11689 } 11690 if (Arg.hasAttribute(Attribute::StructRet)) 11691 Flags.setSRet(); 11692 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11693 Flags.setSwiftSelf(); 11694 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11695 Flags.setSwiftAsync(); 11696 if (Arg.hasAttribute(Attribute::SwiftError)) 11697 Flags.setSwiftError(); 11698 if (Arg.hasAttribute(Attribute::ByVal)) 11699 Flags.setByVal(); 11700 if (Arg.hasAttribute(Attribute::ByRef)) 11701 Flags.setByRef(); 11702 if (Arg.hasAttribute(Attribute::InAlloca)) { 11703 Flags.setInAlloca(); 11704 // Set the byval flag for CCAssignFn callbacks that don't know about 11705 // inalloca. This way we can know how many bytes we should've allocated 11706 // and how many bytes a callee cleanup function will pop. If we port 11707 // inalloca to more targets, we'll have to add custom inalloca handling 11708 // in the various CC lowering callbacks. 11709 Flags.setByVal(); 11710 } 11711 if (Arg.hasAttribute(Attribute::Preallocated)) { 11712 Flags.setPreallocated(); 11713 // Set the byval flag for CCAssignFn callbacks that don't know about 11714 // preallocated. This way we can know how many bytes we should've 11715 // allocated and how many bytes a callee cleanup function will pop. If 11716 // we port preallocated to more targets, we'll have to add custom 11717 // preallocated handling in the various CC lowering callbacks. 11718 Flags.setByVal(); 11719 } 11720 11721 // Certain targets (such as MIPS), may have a different ABI alignment 11722 // for a type depending on the context. Give the target a chance to 11723 // specify the alignment it wants. 11724 const Align OriginalAlignment( 11725 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11726 Flags.setOrigAlign(OriginalAlignment); 11727 11728 Align MemAlign; 11729 Type *ArgMemTy = nullptr; 11730 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11731 Flags.isByRef()) { 11732 if (!ArgMemTy) 11733 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11734 11735 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11736 11737 // For in-memory arguments, size and alignment should be passed from FE. 11738 // BE will guess if this info is not there but there are cases it cannot 11739 // get right. 11740 if (auto ParamAlign = Arg.getParamStackAlign()) 11741 MemAlign = *ParamAlign; 11742 else if ((ParamAlign = Arg.getParamAlign())) 11743 MemAlign = *ParamAlign; 11744 else 11745 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11746 if (Flags.isByRef()) 11747 Flags.setByRefSize(MemSize); 11748 else 11749 Flags.setByValSize(MemSize); 11750 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11751 MemAlign = *ParamAlign; 11752 } else { 11753 MemAlign = OriginalAlignment; 11754 } 11755 Flags.setMemAlign(MemAlign); 11756 11757 if (Arg.hasAttribute(Attribute::Nest)) 11758 Flags.setNest(); 11759 if (NeedsRegBlock) 11760 Flags.setInConsecutiveRegs(); 11761 if (ArgCopyElisionCandidates.count(&Arg)) 11762 Flags.setCopyElisionCandidate(); 11763 if (Arg.hasAttribute(Attribute::Returned)) 11764 Flags.setReturned(); 11765 11766 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11767 *CurDAG->getContext(), F.getCallingConv(), VT); 11768 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11769 *CurDAG->getContext(), F.getCallingConv(), VT); 11770 for (unsigned i = 0; i != NumRegs; ++i) { 11771 // For scalable vectors, use the minimum size; individual targets 11772 // are responsible for handling scalable vector arguments and 11773 // return values. 11774 ISD::InputArg MyFlags( 11775 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11776 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11777 if (NumRegs > 1 && i == 0) 11778 MyFlags.Flags.setSplit(); 11779 // if it isn't first piece, alignment must be 1 11780 else if (i > 0) { 11781 MyFlags.Flags.setOrigAlign(Align(1)); 11782 if (i == NumRegs - 1) 11783 MyFlags.Flags.setSplitEnd(); 11784 } 11785 Ins.push_back(MyFlags); 11786 } 11787 if (NeedsRegBlock && Value == NumValues - 1) 11788 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11789 PartBase += VT.getStoreSize().getKnownMinValue(); 11790 } 11791 } 11792 11793 // Call the target to set up the argument values. 11794 SmallVector<SDValue, 8> InVals; 11795 SDValue NewRoot = TLI->LowerFormalArguments( 11796 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11797 11798 // Verify that the target's LowerFormalArguments behaved as expected. 11799 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11800 "LowerFormalArguments didn't return a valid chain!"); 11801 assert(InVals.size() == Ins.size() && 11802 "LowerFormalArguments didn't emit the correct number of values!"); 11803 LLVM_DEBUG({ 11804 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11805 assert(InVals[i].getNode() && 11806 "LowerFormalArguments emitted a null value!"); 11807 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11808 "LowerFormalArguments emitted a value with the wrong type!"); 11809 } 11810 }); 11811 11812 // Update the DAG with the new chain value resulting from argument lowering. 11813 DAG.setRoot(NewRoot); 11814 11815 // Set up the argument values. 11816 unsigned i = 0; 11817 if (!FuncInfo->CanLowerReturn) { 11818 // Create a virtual register for the sret pointer, and put in a copy 11819 // from the sret argument into it. 11820 SmallVector<EVT, 1> ValueVTs; 11821 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11822 PointerType::get(F.getContext(), 11823 DAG.getDataLayout().getAllocaAddrSpace()), 11824 ValueVTs); 11825 MVT VT = ValueVTs[0].getSimpleVT(); 11826 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11827 std::optional<ISD::NodeType> AssertOp; 11828 SDValue ArgValue = 11829 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11830 F.getCallingConv(), AssertOp); 11831 11832 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11833 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11834 Register SRetReg = 11835 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11836 FuncInfo->DemoteRegister = SRetReg; 11837 NewRoot = 11838 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11839 DAG.setRoot(NewRoot); 11840 11841 // i indexes lowered arguments. Bump it past the hidden sret argument. 11842 ++i; 11843 } 11844 11845 SmallVector<SDValue, 4> Chains; 11846 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11847 for (const Argument &Arg : F.args()) { 11848 SmallVector<SDValue, 4> ArgValues; 11849 SmallVector<EVT, 4> ValueVTs; 11850 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11851 unsigned NumValues = ValueVTs.size(); 11852 if (NumValues == 0) 11853 continue; 11854 11855 bool ArgHasUses = !Arg.use_empty(); 11856 11857 // Elide the copying store if the target loaded this argument from a 11858 // suitable fixed stack object. 11859 if (Ins[i].Flags.isCopyElisionCandidate()) { 11860 unsigned NumParts = 0; 11861 for (EVT VT : ValueVTs) 11862 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11863 F.getCallingConv(), VT); 11864 11865 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11866 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11867 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11868 } 11869 11870 // If this argument is unused then remember its value. It is used to generate 11871 // debugging information. 11872 bool isSwiftErrorArg = 11873 TLI->supportSwiftError() && 11874 Arg.hasAttribute(Attribute::SwiftError); 11875 if (!ArgHasUses && !isSwiftErrorArg) { 11876 SDB->setUnusedArgValue(&Arg, InVals[i]); 11877 11878 // Also remember any frame index for use in FastISel. 11879 if (FrameIndexSDNode *FI = 11880 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11881 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11882 } 11883 11884 for (unsigned Val = 0; Val != NumValues; ++Val) { 11885 EVT VT = ValueVTs[Val]; 11886 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11887 F.getCallingConv(), VT); 11888 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11889 *CurDAG->getContext(), F.getCallingConv(), VT); 11890 11891 // Even an apparent 'unused' swifterror argument needs to be returned. So 11892 // we do generate a copy for it that can be used on return from the 11893 // function. 11894 if (ArgHasUses || isSwiftErrorArg) { 11895 std::optional<ISD::NodeType> AssertOp; 11896 if (Arg.hasAttribute(Attribute::SExt)) 11897 AssertOp = ISD::AssertSext; 11898 else if (Arg.hasAttribute(Attribute::ZExt)) 11899 AssertOp = ISD::AssertZext; 11900 11901 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11902 PartVT, VT, nullptr, NewRoot, 11903 F.getCallingConv(), AssertOp)); 11904 } 11905 11906 i += NumParts; 11907 } 11908 11909 // We don't need to do anything else for unused arguments. 11910 if (ArgValues.empty()) 11911 continue; 11912 11913 // Note down frame index. 11914 if (FrameIndexSDNode *FI = 11915 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11916 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11917 11918 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11919 SDB->getCurSDLoc()); 11920 11921 SDB->setValue(&Arg, Res); 11922 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11923 // We want to associate the argument with the frame index, among 11924 // involved operands, that correspond to the lowest address. The 11925 // getCopyFromParts function, called earlier, is swapping the order of 11926 // the operands to BUILD_PAIR depending on endianness. The result of 11927 // that swapping is that the least significant bits of the argument will 11928 // be in the first operand of the BUILD_PAIR node, and the most 11929 // significant bits will be in the second operand. 11930 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11931 if (LoadSDNode *LNode = 11932 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11933 if (FrameIndexSDNode *FI = 11934 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11935 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11936 } 11937 11938 // Analyses past this point are naive and don't expect an assertion. 11939 if (Res.getOpcode() == ISD::AssertZext) 11940 Res = Res.getOperand(0); 11941 11942 // Update the SwiftErrorVRegDefMap. 11943 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11944 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11945 if (Reg.isVirtual()) 11946 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11947 Reg); 11948 } 11949 11950 // If this argument is live outside of the entry block, insert a copy from 11951 // wherever we got it to the vreg that other BB's will reference it as. 11952 if (Res.getOpcode() == ISD::CopyFromReg) { 11953 // If we can, though, try to skip creating an unnecessary vreg. 11954 // FIXME: This isn't very clean... it would be nice to make this more 11955 // general. 11956 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11957 if (Reg.isVirtual()) { 11958 FuncInfo->ValueMap[&Arg] = Reg; 11959 continue; 11960 } 11961 } 11962 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11963 FuncInfo->InitializeRegForValue(&Arg); 11964 SDB->CopyToExportRegsIfNeeded(&Arg); 11965 } 11966 } 11967 11968 if (!Chains.empty()) { 11969 Chains.push_back(NewRoot); 11970 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11971 } 11972 11973 DAG.setRoot(NewRoot); 11974 11975 assert(i == InVals.size() && "Argument register count mismatch!"); 11976 11977 // If any argument copy elisions occurred and we have debug info, update the 11978 // stale frame indices used in the dbg.declare variable info table. 11979 if (!ArgCopyElisionFrameIndexMap.empty()) { 11980 for (MachineFunction::VariableDbgInfo &VI : 11981 MF->getInStackSlotVariableDbgInfo()) { 11982 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11983 if (I != ArgCopyElisionFrameIndexMap.end()) 11984 VI.updateStackSlot(I->second); 11985 } 11986 } 11987 11988 // Finally, if the target has anything special to do, allow it to do so. 11989 emitFunctionEntryCode(); 11990 } 11991 11992 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11993 /// ensure constants are generated when needed. Remember the virtual registers 11994 /// that need to be added to the Machine PHI nodes as input. We cannot just 11995 /// directly add them, because expansion might result in multiple MBB's for one 11996 /// BB. As such, the start of the BB might correspond to a different MBB than 11997 /// the end. 11998 void 11999 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 12000 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12001 12002 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 12003 12004 // Check PHI nodes in successors that expect a value to be available from this 12005 // block. 12006 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 12007 if (!isa<PHINode>(SuccBB->begin())) continue; 12008 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB); 12009 12010 // If this terminator has multiple identical successors (common for 12011 // switches), only handle each succ once. 12012 if (!SuccsHandled.insert(SuccMBB).second) 12013 continue; 12014 12015 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 12016 12017 // At this point we know that there is a 1-1 correspondence between LLVM PHI 12018 // nodes and Machine PHI nodes, but the incoming operands have not been 12019 // emitted yet. 12020 for (const PHINode &PN : SuccBB->phis()) { 12021 // Ignore dead phi's. 12022 if (PN.use_empty()) 12023 continue; 12024 12025 // Skip empty types 12026 if (PN.getType()->isEmptyTy()) 12027 continue; 12028 12029 unsigned Reg; 12030 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 12031 12032 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 12033 unsigned &RegOut = ConstantsOut[C]; 12034 if (RegOut == 0) { 12035 RegOut = FuncInfo.CreateRegs(C); 12036 // We need to zero/sign extend ConstantInt phi operands to match 12037 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 12038 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 12039 if (auto *CI = dyn_cast<ConstantInt>(C)) 12040 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 12041 : ISD::ZERO_EXTEND; 12042 CopyValueToVirtualRegister(C, RegOut, ExtendType); 12043 } 12044 Reg = RegOut; 12045 } else { 12046 DenseMap<const Value *, Register>::iterator I = 12047 FuncInfo.ValueMap.find(PHIOp); 12048 if (I != FuncInfo.ValueMap.end()) 12049 Reg = I->second; 12050 else { 12051 assert(isa<AllocaInst>(PHIOp) && 12052 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 12053 "Didn't codegen value into a register!??"); 12054 Reg = FuncInfo.CreateRegs(PHIOp); 12055 CopyValueToVirtualRegister(PHIOp, Reg); 12056 } 12057 } 12058 12059 // Remember that this register needs to added to the machine PHI node as 12060 // the input for this MBB. 12061 SmallVector<EVT, 4> ValueVTs; 12062 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 12063 for (EVT VT : ValueVTs) { 12064 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 12065 for (unsigned i = 0; i != NumRegisters; ++i) 12066 FuncInfo.PHINodesToUpdate.push_back( 12067 std::make_pair(&*MBBI++, Reg + i)); 12068 Reg += NumRegisters; 12069 } 12070 } 12071 } 12072 12073 ConstantsOut.clear(); 12074 } 12075 12076 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 12077 MachineFunction::iterator I(MBB); 12078 if (++I == FuncInfo.MF->end()) 12079 return nullptr; 12080 return &*I; 12081 } 12082 12083 /// During lowering new call nodes can be created (such as memset, etc.). 12084 /// Those will become new roots of the current DAG, but complications arise 12085 /// when they are tail calls. In such cases, the call lowering will update 12086 /// the root, but the builder still needs to know that a tail call has been 12087 /// lowered in order to avoid generating an additional return. 12088 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 12089 // If the node is null, we do have a tail call. 12090 if (MaybeTC.getNode() != nullptr) 12091 DAG.setRoot(MaybeTC); 12092 else 12093 HasTailCall = true; 12094 } 12095 12096 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 12097 MachineBasicBlock *SwitchMBB, 12098 MachineBasicBlock *DefaultMBB) { 12099 MachineFunction *CurMF = FuncInfo.MF; 12100 MachineBasicBlock *NextMBB = nullptr; 12101 MachineFunction::iterator BBI(W.MBB); 12102 if (++BBI != FuncInfo.MF->end()) 12103 NextMBB = &*BBI; 12104 12105 unsigned Size = W.LastCluster - W.FirstCluster + 1; 12106 12107 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12108 12109 if (Size == 2 && W.MBB == SwitchMBB) { 12110 // If any two of the cases has the same destination, and if one value 12111 // is the same as the other, but has one bit unset that the other has set, 12112 // use bit manipulation to do two compares at once. For example: 12113 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 12114 // TODO: This could be extended to merge any 2 cases in switches with 3 12115 // cases. 12116 // TODO: Handle cases where W.CaseBB != SwitchBB. 12117 CaseCluster &Small = *W.FirstCluster; 12118 CaseCluster &Big = *W.LastCluster; 12119 12120 if (Small.Low == Small.High && Big.Low == Big.High && 12121 Small.MBB == Big.MBB) { 12122 const APInt &SmallValue = Small.Low->getValue(); 12123 const APInt &BigValue = Big.Low->getValue(); 12124 12125 // Check that there is only one bit different. 12126 APInt CommonBit = BigValue ^ SmallValue; 12127 if (CommonBit.isPowerOf2()) { 12128 SDValue CondLHS = getValue(Cond); 12129 EVT VT = CondLHS.getValueType(); 12130 SDLoc DL = getCurSDLoc(); 12131 12132 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 12133 DAG.getConstant(CommonBit, DL, VT)); 12134 SDValue Cond = DAG.getSetCC( 12135 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 12136 ISD::SETEQ); 12137 12138 // Update successor info. 12139 // Both Small and Big will jump to Small.BB, so we sum up the 12140 // probabilities. 12141 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 12142 if (BPI) 12143 addSuccessorWithProb( 12144 SwitchMBB, DefaultMBB, 12145 // The default destination is the first successor in IR. 12146 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 12147 else 12148 addSuccessorWithProb(SwitchMBB, DefaultMBB); 12149 12150 // Insert the true branch. 12151 SDValue BrCond = 12152 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 12153 DAG.getBasicBlock(Small.MBB)); 12154 // Insert the false branch. 12155 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 12156 DAG.getBasicBlock(DefaultMBB)); 12157 12158 DAG.setRoot(BrCond); 12159 return; 12160 } 12161 } 12162 } 12163 12164 if (TM.getOptLevel() != CodeGenOptLevel::None) { 12165 // Here, we order cases by probability so the most likely case will be 12166 // checked first. However, two clusters can have the same probability in 12167 // which case their relative ordering is non-deterministic. So we use Low 12168 // as a tie-breaker as clusters are guaranteed to never overlap. 12169 llvm::sort(W.FirstCluster, W.LastCluster + 1, 12170 [](const CaseCluster &a, const CaseCluster &b) { 12171 return a.Prob != b.Prob ? 12172 a.Prob > b.Prob : 12173 a.Low->getValue().slt(b.Low->getValue()); 12174 }); 12175 12176 // Rearrange the case blocks so that the last one falls through if possible 12177 // without changing the order of probabilities. 12178 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 12179 --I; 12180 if (I->Prob > W.LastCluster->Prob) 12181 break; 12182 if (I->Kind == CC_Range && I->MBB == NextMBB) { 12183 std::swap(*I, *W.LastCluster); 12184 break; 12185 } 12186 } 12187 } 12188 12189 // Compute total probability. 12190 BranchProbability DefaultProb = W.DefaultProb; 12191 BranchProbability UnhandledProbs = DefaultProb; 12192 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 12193 UnhandledProbs += I->Prob; 12194 12195 MachineBasicBlock *CurMBB = W.MBB; 12196 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 12197 bool FallthroughUnreachable = false; 12198 MachineBasicBlock *Fallthrough; 12199 if (I == W.LastCluster) { 12200 // For the last cluster, fall through to the default destination. 12201 Fallthrough = DefaultMBB; 12202 FallthroughUnreachable = isa<UnreachableInst>( 12203 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 12204 } else { 12205 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 12206 CurMF->insert(BBI, Fallthrough); 12207 // Put Cond in a virtual register to make it available from the new blocks. 12208 ExportFromCurrentBlock(Cond); 12209 } 12210 UnhandledProbs -= I->Prob; 12211 12212 switch (I->Kind) { 12213 case CC_JumpTable: { 12214 // FIXME: Optimize away range check based on pivot comparisons. 12215 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 12216 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 12217 12218 // The jump block hasn't been inserted yet; insert it here. 12219 MachineBasicBlock *JumpMBB = JT->MBB; 12220 CurMF->insert(BBI, JumpMBB); 12221 12222 auto JumpProb = I->Prob; 12223 auto FallthroughProb = UnhandledProbs; 12224 12225 // If the default statement is a target of the jump table, we evenly 12226 // distribute the default probability to successors of CurMBB. Also 12227 // update the probability on the edge from JumpMBB to Fallthrough. 12228 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 12229 SE = JumpMBB->succ_end(); 12230 SI != SE; ++SI) { 12231 if (*SI == DefaultMBB) { 12232 JumpProb += DefaultProb / 2; 12233 FallthroughProb -= DefaultProb / 2; 12234 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 12235 JumpMBB->normalizeSuccProbs(); 12236 break; 12237 } 12238 } 12239 12240 // If the default clause is unreachable, propagate that knowledge into 12241 // JTH->FallthroughUnreachable which will use it to suppress the range 12242 // check. 12243 // 12244 // However, don't do this if we're doing branch target enforcement, 12245 // because a table branch _without_ a range check can be a tempting JOP 12246 // gadget - out-of-bounds inputs that are impossible in correct 12247 // execution become possible again if an attacker can influence the 12248 // control flow. So if an attacker doesn't already have a BTI bypass 12249 // available, we don't want them to be able to get one out of this 12250 // table branch. 12251 if (FallthroughUnreachable) { 12252 Function &CurFunc = CurMF->getFunction(); 12253 if (!CurFunc.hasFnAttribute("branch-target-enforcement")) 12254 JTH->FallthroughUnreachable = true; 12255 } 12256 12257 if (!JTH->FallthroughUnreachable) 12258 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 12259 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 12260 CurMBB->normalizeSuccProbs(); 12261 12262 // The jump table header will be inserted in our current block, do the 12263 // range check, and fall through to our fallthrough block. 12264 JTH->HeaderBB = CurMBB; 12265 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 12266 12267 // If we're in the right place, emit the jump table header right now. 12268 if (CurMBB == SwitchMBB) { 12269 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 12270 JTH->Emitted = true; 12271 } 12272 break; 12273 } 12274 case CC_BitTests: { 12275 // FIXME: Optimize away range check based on pivot comparisons. 12276 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 12277 12278 // The bit test blocks haven't been inserted yet; insert them here. 12279 for (BitTestCase &BTC : BTB->Cases) 12280 CurMF->insert(BBI, BTC.ThisBB); 12281 12282 // Fill in fields of the BitTestBlock. 12283 BTB->Parent = CurMBB; 12284 BTB->Default = Fallthrough; 12285 12286 BTB->DefaultProb = UnhandledProbs; 12287 // If the cases in bit test don't form a contiguous range, we evenly 12288 // distribute the probability on the edge to Fallthrough to two 12289 // successors of CurMBB. 12290 if (!BTB->ContiguousRange) { 12291 BTB->Prob += DefaultProb / 2; 12292 BTB->DefaultProb -= DefaultProb / 2; 12293 } 12294 12295 if (FallthroughUnreachable) 12296 BTB->FallthroughUnreachable = true; 12297 12298 // If we're in the right place, emit the bit test header right now. 12299 if (CurMBB == SwitchMBB) { 12300 visitBitTestHeader(*BTB, SwitchMBB); 12301 BTB->Emitted = true; 12302 } 12303 break; 12304 } 12305 case CC_Range: { 12306 const Value *RHS, *LHS, *MHS; 12307 ISD::CondCode CC; 12308 if (I->Low == I->High) { 12309 // Check Cond == I->Low. 12310 CC = ISD::SETEQ; 12311 LHS = Cond; 12312 RHS=I->Low; 12313 MHS = nullptr; 12314 } else { 12315 // Check I->Low <= Cond <= I->High. 12316 CC = ISD::SETLE; 12317 LHS = I->Low; 12318 MHS = Cond; 12319 RHS = I->High; 12320 } 12321 12322 // If Fallthrough is unreachable, fold away the comparison. 12323 if (FallthroughUnreachable) 12324 CC = ISD::SETTRUE; 12325 12326 // The false probability is the sum of all unhandled cases. 12327 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 12328 getCurSDLoc(), I->Prob, UnhandledProbs); 12329 12330 if (CurMBB == SwitchMBB) 12331 visitSwitchCase(CB, SwitchMBB); 12332 else 12333 SL->SwitchCases.push_back(CB); 12334 12335 break; 12336 } 12337 } 12338 CurMBB = Fallthrough; 12339 } 12340 } 12341 12342 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 12343 const SwitchWorkListItem &W, 12344 Value *Cond, 12345 MachineBasicBlock *SwitchMBB) { 12346 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 12347 "Clusters not sorted?"); 12348 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 12349 12350 auto [LastLeft, FirstRight, LeftProb, RightProb] = 12351 SL->computeSplitWorkItemInfo(W); 12352 12353 // Use the first element on the right as pivot since we will make less-than 12354 // comparisons against it. 12355 CaseClusterIt PivotCluster = FirstRight; 12356 assert(PivotCluster > W.FirstCluster); 12357 assert(PivotCluster <= W.LastCluster); 12358 12359 CaseClusterIt FirstLeft = W.FirstCluster; 12360 CaseClusterIt LastRight = W.LastCluster; 12361 12362 const ConstantInt *Pivot = PivotCluster->Low; 12363 12364 // New blocks will be inserted immediately after the current one. 12365 MachineFunction::iterator BBI(W.MBB); 12366 ++BBI; 12367 12368 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 12369 // we can branch to its destination directly if it's squeezed exactly in 12370 // between the known lower bound and Pivot - 1. 12371 MachineBasicBlock *LeftMBB; 12372 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 12373 FirstLeft->Low == W.GE && 12374 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 12375 LeftMBB = FirstLeft->MBB; 12376 } else { 12377 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12378 FuncInfo.MF->insert(BBI, LeftMBB); 12379 WorkList.push_back( 12380 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 12381 // Put Cond in a virtual register to make it available from the new blocks. 12382 ExportFromCurrentBlock(Cond); 12383 } 12384 12385 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 12386 // single cluster, RHS.Low == Pivot, and we can branch to its destination 12387 // directly if RHS.High equals the current upper bound. 12388 MachineBasicBlock *RightMBB; 12389 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 12390 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 12391 RightMBB = FirstRight->MBB; 12392 } else { 12393 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12394 FuncInfo.MF->insert(BBI, RightMBB); 12395 WorkList.push_back( 12396 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 12397 // Put Cond in a virtual register to make it available from the new blocks. 12398 ExportFromCurrentBlock(Cond); 12399 } 12400 12401 // Create the CaseBlock record that will be used to lower the branch. 12402 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 12403 getCurSDLoc(), LeftProb, RightProb); 12404 12405 if (W.MBB == SwitchMBB) 12406 visitSwitchCase(CB, SwitchMBB); 12407 else 12408 SL->SwitchCases.push_back(CB); 12409 } 12410 12411 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 12412 // from the swith statement. 12413 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 12414 BranchProbability PeeledCaseProb) { 12415 if (PeeledCaseProb == BranchProbability::getOne()) 12416 return BranchProbability::getZero(); 12417 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 12418 12419 uint32_t Numerator = CaseProb.getNumerator(); 12420 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 12421 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 12422 } 12423 12424 // Try to peel the top probability case if it exceeds the threshold. 12425 // Return current MachineBasicBlock for the switch statement if the peeling 12426 // does not occur. 12427 // If the peeling is performed, return the newly created MachineBasicBlock 12428 // for the peeled switch statement. Also update Clusters to remove the peeled 12429 // case. PeeledCaseProb is the BranchProbability for the peeled case. 12430 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 12431 const SwitchInst &SI, CaseClusterVector &Clusters, 12432 BranchProbability &PeeledCaseProb) { 12433 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12434 // Don't perform if there is only one cluster or optimizing for size. 12435 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 12436 TM.getOptLevel() == CodeGenOptLevel::None || 12437 SwitchMBB->getParent()->getFunction().hasMinSize()) 12438 return SwitchMBB; 12439 12440 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 12441 unsigned PeeledCaseIndex = 0; 12442 bool SwitchPeeled = false; 12443 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 12444 CaseCluster &CC = Clusters[Index]; 12445 if (CC.Prob < TopCaseProb) 12446 continue; 12447 TopCaseProb = CC.Prob; 12448 PeeledCaseIndex = Index; 12449 SwitchPeeled = true; 12450 } 12451 if (!SwitchPeeled) 12452 return SwitchMBB; 12453 12454 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 12455 << TopCaseProb << "\n"); 12456 12457 // Record the MBB for the peeled switch statement. 12458 MachineFunction::iterator BBI(SwitchMBB); 12459 ++BBI; 12460 MachineBasicBlock *PeeledSwitchMBB = 12461 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 12462 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 12463 12464 ExportFromCurrentBlock(SI.getCondition()); 12465 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 12466 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 12467 nullptr, nullptr, TopCaseProb.getCompl()}; 12468 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 12469 12470 Clusters.erase(PeeledCaseIt); 12471 for (CaseCluster &CC : Clusters) { 12472 LLVM_DEBUG( 12473 dbgs() << "Scale the probablity for one cluster, before scaling: " 12474 << CC.Prob << "\n"); 12475 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 12476 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 12477 } 12478 PeeledCaseProb = TopCaseProb; 12479 return PeeledSwitchMBB; 12480 } 12481 12482 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 12483 // Extract cases from the switch. 12484 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12485 CaseClusterVector Clusters; 12486 Clusters.reserve(SI.getNumCases()); 12487 for (auto I : SI.cases()) { 12488 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor()); 12489 const ConstantInt *CaseVal = I.getCaseValue(); 12490 BranchProbability Prob = 12491 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 12492 : BranchProbability(1, SI.getNumCases() + 1); 12493 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 12494 } 12495 12496 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest()); 12497 12498 // Cluster adjacent cases with the same destination. We do this at all 12499 // optimization levels because it's cheap to do and will make codegen faster 12500 // if there are many clusters. 12501 sortAndRangeify(Clusters); 12502 12503 // The branch probablity of the peeled case. 12504 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 12505 MachineBasicBlock *PeeledSwitchMBB = 12506 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 12507 12508 // If there is only the default destination, jump there directly. 12509 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12510 if (Clusters.empty()) { 12511 assert(PeeledSwitchMBB == SwitchMBB); 12512 SwitchMBB->addSuccessor(DefaultMBB); 12513 if (DefaultMBB != NextBlock(SwitchMBB)) { 12514 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 12515 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 12516 } 12517 return; 12518 } 12519 12520 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 12521 DAG.getBFI()); 12522 SL->findBitTestClusters(Clusters, &SI); 12523 12524 LLVM_DEBUG({ 12525 dbgs() << "Case clusters: "; 12526 for (const CaseCluster &C : Clusters) { 12527 if (C.Kind == CC_JumpTable) 12528 dbgs() << "JT:"; 12529 if (C.Kind == CC_BitTests) 12530 dbgs() << "BT:"; 12531 12532 C.Low->getValue().print(dbgs(), true); 12533 if (C.Low != C.High) { 12534 dbgs() << '-'; 12535 C.High->getValue().print(dbgs(), true); 12536 } 12537 dbgs() << ' '; 12538 } 12539 dbgs() << '\n'; 12540 }); 12541 12542 assert(!Clusters.empty()); 12543 SwitchWorkList WorkList; 12544 CaseClusterIt First = Clusters.begin(); 12545 CaseClusterIt Last = Clusters.end() - 1; 12546 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 12547 // Scale the branchprobability for DefaultMBB if the peel occurs and 12548 // DefaultMBB is not replaced. 12549 if (PeeledCaseProb != BranchProbability::getZero() && 12550 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest())) 12551 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 12552 WorkList.push_back( 12553 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 12554 12555 while (!WorkList.empty()) { 12556 SwitchWorkListItem W = WorkList.pop_back_val(); 12557 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 12558 12559 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 12560 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 12561 // For optimized builds, lower large range as a balanced binary tree. 12562 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 12563 continue; 12564 } 12565 12566 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 12567 } 12568 } 12569 12570 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 12571 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12572 auto DL = getCurSDLoc(); 12573 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12574 setValue(&I, DAG.getStepVector(DL, ResultVT)); 12575 } 12576 12577 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 12578 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12579 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12580 12581 SDLoc DL = getCurSDLoc(); 12582 SDValue V = getValue(I.getOperand(0)); 12583 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 12584 12585 if (VT.isScalableVector()) { 12586 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 12587 return; 12588 } 12589 12590 // Use VECTOR_SHUFFLE for the fixed-length vector 12591 // to maintain existing behavior. 12592 SmallVector<int, 8> Mask; 12593 unsigned NumElts = VT.getVectorMinNumElements(); 12594 for (unsigned i = 0; i != NumElts; ++i) 12595 Mask.push_back(NumElts - 1 - i); 12596 12597 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 12598 } 12599 12600 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 12601 auto DL = getCurSDLoc(); 12602 SDValue InVec = getValue(I.getOperand(0)); 12603 EVT OutVT = 12604 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 12605 12606 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 12607 12608 // ISD Node needs the input vectors split into two equal parts 12609 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12610 DAG.getVectorIdxConstant(0, DL)); 12611 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12612 DAG.getVectorIdxConstant(OutNumElts, DL)); 12613 12614 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12615 // legalisation and combines. 12616 if (OutVT.isFixedLengthVector()) { 12617 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12618 createStrideMask(0, 2, OutNumElts)); 12619 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12620 createStrideMask(1, 2, OutNumElts)); 12621 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 12622 setValue(&I, Res); 12623 return; 12624 } 12625 12626 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12627 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12628 setValue(&I, Res); 12629 } 12630 12631 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12632 auto DL = getCurSDLoc(); 12633 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12634 SDValue InVec0 = getValue(I.getOperand(0)); 12635 SDValue InVec1 = getValue(I.getOperand(1)); 12636 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12637 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12638 12639 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12640 // legalisation and combines. 12641 if (OutVT.isFixedLengthVector()) { 12642 unsigned NumElts = InVT.getVectorMinNumElements(); 12643 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12644 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12645 createInterleaveMask(NumElts, 2))); 12646 return; 12647 } 12648 12649 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12650 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12651 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12652 Res.getValue(1)); 12653 setValue(&I, Res); 12654 } 12655 12656 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12657 SmallVector<EVT, 4> ValueVTs; 12658 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12659 ValueVTs); 12660 unsigned NumValues = ValueVTs.size(); 12661 if (NumValues == 0) return; 12662 12663 SmallVector<SDValue, 4> Values(NumValues); 12664 SDValue Op = getValue(I.getOperand(0)); 12665 12666 for (unsigned i = 0; i != NumValues; ++i) 12667 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12668 SDValue(Op.getNode(), Op.getResNo() + i)); 12669 12670 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12671 DAG.getVTList(ValueVTs), Values)); 12672 } 12673 12674 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12675 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12676 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12677 12678 SDLoc DL = getCurSDLoc(); 12679 SDValue V1 = getValue(I.getOperand(0)); 12680 SDValue V2 = getValue(I.getOperand(1)); 12681 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12682 12683 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12684 if (VT.isScalableVector()) { 12685 setValue( 12686 &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12687 DAG.getSignedConstant( 12688 Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout())))); 12689 return; 12690 } 12691 12692 unsigned NumElts = VT.getVectorNumElements(); 12693 12694 uint64_t Idx = (NumElts + Imm) % NumElts; 12695 12696 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12697 SmallVector<int, 8> Mask; 12698 for (unsigned i = 0; i < NumElts; ++i) 12699 Mask.push_back(Idx + i); 12700 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12701 } 12702 12703 // Consider the following MIR after SelectionDAG, which produces output in 12704 // phyregs in the first case or virtregs in the second case. 12705 // 12706 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12707 // %5:gr32 = COPY $ebx 12708 // %6:gr32 = COPY $edx 12709 // %1:gr32 = COPY %6:gr32 12710 // %0:gr32 = COPY %5:gr32 12711 // 12712 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12713 // %1:gr32 = COPY %6:gr32 12714 // %0:gr32 = COPY %5:gr32 12715 // 12716 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12717 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12718 // 12719 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12720 // to a single virtreg (such as %0). The remaining outputs monotonically 12721 // increase in virtreg number from there. If a callbr has no outputs, then it 12722 // should not have a corresponding callbr landingpad; in fact, the callbr 12723 // landingpad would not even be able to refer to such a callbr. 12724 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12725 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12726 // There is definitely at least one copy. 12727 assert(MI->getOpcode() == TargetOpcode::COPY && 12728 "start of copy chain MUST be COPY"); 12729 Reg = MI->getOperand(1).getReg(); 12730 MI = MRI.def_begin(Reg)->getParent(); 12731 // There may be an optional second copy. 12732 if (MI->getOpcode() == TargetOpcode::COPY) { 12733 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12734 Reg = MI->getOperand(1).getReg(); 12735 assert(Reg.isPhysical() && "expected COPY of physical register"); 12736 MI = MRI.def_begin(Reg)->getParent(); 12737 } 12738 // The start of the chain must be an INLINEASM_BR. 12739 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12740 "end of copy chain MUST be INLINEASM_BR"); 12741 return Reg; 12742 } 12743 12744 // We must do this walk rather than the simpler 12745 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12746 // otherwise we will end up with copies of virtregs only valid along direct 12747 // edges. 12748 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12749 SmallVector<EVT, 8> ResultVTs; 12750 SmallVector<SDValue, 8> ResultValues; 12751 const auto *CBR = 12752 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12753 12754 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12755 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12756 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12757 12758 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12759 SDValue Chain = DAG.getRoot(); 12760 12761 // Re-parse the asm constraints string. 12762 TargetLowering::AsmOperandInfoVector TargetConstraints = 12763 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12764 for (auto &T : TargetConstraints) { 12765 SDISelAsmOperandInfo OpInfo(T); 12766 if (OpInfo.Type != InlineAsm::isOutput) 12767 continue; 12768 12769 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12770 // individual constraint. 12771 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12772 12773 switch (OpInfo.ConstraintType) { 12774 case TargetLowering::C_Register: 12775 case TargetLowering::C_RegisterClass: { 12776 // Fill in OpInfo.AssignedRegs.Regs. 12777 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12778 12779 // getRegistersForValue may produce 1 to many registers based on whether 12780 // the OpInfo.ConstraintVT is legal on the target or not. 12781 for (Register &Reg : OpInfo.AssignedRegs.Regs) { 12782 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12783 if (Register::isPhysicalRegister(OriginalDef)) 12784 FuncInfo.MBB->addLiveIn(OriginalDef); 12785 // Update the assigned registers to use the original defs. 12786 Reg = OriginalDef; 12787 } 12788 12789 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12790 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12791 ResultValues.push_back(V); 12792 ResultVTs.push_back(OpInfo.ConstraintVT); 12793 break; 12794 } 12795 case TargetLowering::C_Other: { 12796 SDValue Flag; 12797 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12798 OpInfo, DAG); 12799 ++InitialDef; 12800 ResultValues.push_back(V); 12801 ResultVTs.push_back(OpInfo.ConstraintVT); 12802 break; 12803 } 12804 default: 12805 break; 12806 } 12807 } 12808 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12809 DAG.getVTList(ResultVTs), ResultValues); 12810 setValue(&I, V); 12811 } 12812