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/RuntimeLibcallUtil.h" 48 #include "llvm/CodeGen/SelectionDAG.h" 49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 50 #include "llvm/CodeGen/StackMaps.h" 51 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 52 #include "llvm/CodeGen/TargetFrameLowering.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetOpcodes.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/TargetSubtargetInfo.h" 57 #include "llvm/CodeGen/WinEHFuncInfo.h" 58 #include "llvm/IR/Argument.h" 59 #include "llvm/IR/Attributes.h" 60 #include "llvm/IR/BasicBlock.h" 61 #include "llvm/IR/CFG.h" 62 #include "llvm/IR/CallingConv.h" 63 #include "llvm/IR/Constant.h" 64 #include "llvm/IR/ConstantRange.h" 65 #include "llvm/IR/Constants.h" 66 #include "llvm/IR/DataLayout.h" 67 #include "llvm/IR/DebugInfo.h" 68 #include "llvm/IR/DebugInfoMetadata.h" 69 #include "llvm/IR/DerivedTypes.h" 70 #include "llvm/IR/DiagnosticInfo.h" 71 #include "llvm/IR/EHPersonalities.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsAMDGPU.h" 81 #include "llvm/IR/IntrinsicsWebAssembly.h" 82 #include "llvm/IR/LLVMContext.h" 83 #include "llvm/IR/MemoryModelRelaxationAnnotations.h" 84 #include "llvm/IR/Metadata.h" 85 #include "llvm/IR/Module.h" 86 #include "llvm/IR/Operator.h" 87 #include "llvm/IR/PatternMatch.h" 88 #include "llvm/IR/Statepoint.h" 89 #include "llvm/IR/Type.h" 90 #include "llvm/IR/User.h" 91 #include "llvm/IR/Value.h" 92 #include "llvm/MC/MCContext.h" 93 #include "llvm/Support/AtomicOrdering.h" 94 #include "llvm/Support/Casting.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/InstructionCost.h" 99 #include "llvm/Support/MathExtras.h" 100 #include "llvm/Support/raw_ostream.h" 101 #include "llvm/Target/TargetIntrinsicInfo.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.h" 104 #include "llvm/TargetParser/Triple.h" 105 #include "llvm/Transforms/Utils/Local.h" 106 #include <cstddef> 107 #include <deque> 108 #include <iterator> 109 #include <limits> 110 #include <optional> 111 #include <tuple> 112 113 using namespace llvm; 114 using namespace PatternMatch; 115 using namespace SwitchCG; 116 117 #define DEBUG_TYPE "isel" 118 119 /// LimitFloatPrecision - Generate low-precision inline sequences for 120 /// some float libcalls (6, 8 or 12 bits). 121 static unsigned LimitFloatPrecision; 122 123 static cl::opt<bool> 124 InsertAssertAlign("insert-assert-align", cl::init(true), 125 cl::desc("Insert the experimental `assertalign` node."), 126 cl::ReallyHidden); 127 128 static cl::opt<unsigned, true> 129 LimitFPPrecision("limit-float-precision", 130 cl::desc("Generate low-precision inline sequences " 131 "for some float libcalls"), 132 cl::location(LimitFloatPrecision), cl::Hidden, 133 cl::init(0)); 134 135 static cl::opt<unsigned> SwitchPeelThreshold( 136 "switch-peel-threshold", cl::Hidden, cl::init(66), 137 cl::desc("Set the case probability threshold for peeling the case from a " 138 "switch statement. A value greater than 100 will void this " 139 "optimization")); 140 141 // Limit the width of DAG chains. This is important in general to prevent 142 // DAG-based analysis from blowing up. For example, alias analysis and 143 // load clustering may not complete in reasonable time. It is difficult to 144 // recognize and avoid this situation within each individual analysis, and 145 // future analyses are likely to have the same behavior. Limiting DAG width is 146 // the safe approach and will be especially important with global DAGs. 147 // 148 // MaxParallelChains default is arbitrarily high to avoid affecting 149 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 150 // sequence over this should have been converted to llvm.memcpy by the 151 // frontend. It is easy to induce this behavior with .ll code such as: 152 // %buffer = alloca [4096 x i8] 153 // %data = load [4096 x i8]* %argPtr 154 // store [4096 x i8] %data, [4096 x i8]* %buffer 155 static const unsigned MaxParallelChains = 64; 156 157 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 158 const SDValue *Parts, unsigned NumParts, 159 MVT PartVT, EVT ValueVT, const Value *V, 160 SDValue InChain, 161 std::optional<CallingConv::ID> CC); 162 163 /// getCopyFromParts - Create a value that contains the specified legal parts 164 /// combined into the value they represent. If the parts combine to a type 165 /// larger than ValueVT then AssertOp can be used to specify whether the extra 166 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 167 /// (ISD::AssertSext). 168 static SDValue 169 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 170 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 171 SDValue InChain, 172 std::optional<CallingConv::ID> CC = std::nullopt, 173 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 174 // Let the target assemble the parts if it wants to 175 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 176 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 177 PartVT, ValueVT, CC)) 178 return Val; 179 180 if (ValueVT.isVector()) 181 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 182 InChain, CC); 183 184 assert(NumParts > 0 && "No parts to assemble!"); 185 SDValue Val = Parts[0]; 186 187 if (NumParts > 1) { 188 // Assemble the value from multiple parts. 189 if (ValueVT.isInteger()) { 190 unsigned PartBits = PartVT.getSizeInBits(); 191 unsigned ValueBits = ValueVT.getSizeInBits(); 192 193 // Assemble the power of 2 part. 194 unsigned RoundParts = llvm::bit_floor(NumParts); 195 unsigned RoundBits = PartBits * RoundParts; 196 EVT RoundVT = RoundBits == ValueBits ? 197 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 198 SDValue Lo, Hi; 199 200 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 201 202 if (RoundParts > 2) { 203 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V, 204 InChain); 205 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2, 206 PartVT, HalfVT, V, InChain); 207 } else { 208 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 209 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 210 } 211 212 if (DAG.getDataLayout().isBigEndian()) 213 std::swap(Lo, Hi); 214 215 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 216 217 if (RoundParts < NumParts) { 218 // Assemble the trailing non-power-of-2 part. 219 unsigned OddParts = NumParts - RoundParts; 220 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 221 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 222 OddVT, V, InChain, CC); 223 224 // Combine the round and odd parts. 225 Lo = Val; 226 if (DAG.getDataLayout().isBigEndian()) 227 std::swap(Lo, Hi); 228 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 229 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 230 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 231 DAG.getConstant(Lo.getValueSizeInBits(), DL, 232 TLI.getShiftAmountTy( 233 TotalVT, DAG.getDataLayout()))); 234 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 235 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 236 } 237 } else if (PartVT.isFloatingPoint()) { 238 // FP split into multiple FP parts (for ppcf128) 239 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 240 "Unexpected split"); 241 SDValue Lo, Hi; 242 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 243 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 244 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 245 std::swap(Lo, Hi); 246 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 247 } else { 248 // FP split into integer parts (soft fp) 249 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 250 !PartVT.isVector() && "Unexpected split"); 251 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 252 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, 253 InChain, CC); 254 } 255 } 256 257 // There is now one part, held in Val. Correct it to match ValueVT. 258 // PartEVT is the type of the register class that holds the value. 259 // ValueVT is the type of the inline asm operation. 260 EVT PartEVT = Val.getValueType(); 261 262 if (PartEVT == ValueVT) 263 return Val; 264 265 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 266 ValueVT.bitsLT(PartEVT)) { 267 // For an FP value in an integer part, we need to truncate to the right 268 // width first. 269 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 270 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 271 } 272 273 // Handle types that have the same size. 274 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 275 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 276 277 // Handle types with different sizes. 278 if (PartEVT.isInteger() && ValueVT.isInteger()) { 279 if (ValueVT.bitsLT(PartEVT)) { 280 // For a truncate, see if we have any information to 281 // indicate whether the truncated bits will always be 282 // zero or sign-extension. 283 if (AssertOp) 284 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 285 DAG.getValueType(ValueVT)); 286 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 287 } 288 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 289 } 290 291 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 292 // FP_ROUND's are always exact here. 293 if (ValueVT.bitsLT(Val.getValueType())) { 294 295 SDValue NoChange = 296 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 297 298 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr( 299 llvm::Attribute::StrictFP)) { 300 return DAG.getNode(ISD::STRICT_FP_ROUND, DL, 301 DAG.getVTList(ValueVT, MVT::Other), InChain, Val, 302 NoChange); 303 } 304 305 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange); 306 } 307 308 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 309 } 310 311 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 312 // then truncating. 313 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 314 ValueVT.bitsLT(PartEVT)) { 315 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 316 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 317 } 318 319 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 320 } 321 322 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 323 const Twine &ErrMsg) { 324 const Instruction *I = dyn_cast_or_null<Instruction>(V); 325 if (!V) 326 return Ctx.emitError(ErrMsg); 327 328 const char *AsmError = ", possible invalid constraint for vector type"; 329 if (const CallInst *CI = dyn_cast<CallInst>(I)) 330 if (CI->isInlineAsm()) 331 return Ctx.emitError(I, ErrMsg + AsmError); 332 333 return Ctx.emitError(I, ErrMsg); 334 } 335 336 /// getCopyFromPartsVector - Create a value that contains the specified legal 337 /// parts combined into the value they represent. If the parts combine to a 338 /// type larger than ValueVT then AssertOp can be used to specify whether the 339 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 340 /// ValueVT (ISD::AssertSext). 341 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 342 const SDValue *Parts, unsigned NumParts, 343 MVT PartVT, EVT ValueVT, const Value *V, 344 SDValue InChain, 345 std::optional<CallingConv::ID> CallConv) { 346 assert(ValueVT.isVector() && "Not a vector value"); 347 assert(NumParts > 0 && "No parts to assemble!"); 348 const bool IsABIRegCopy = CallConv.has_value(); 349 350 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 351 SDValue Val = Parts[0]; 352 353 // Handle a multi-element vector. 354 if (NumParts > 1) { 355 EVT IntermediateVT; 356 MVT RegisterVT; 357 unsigned NumIntermediates; 358 unsigned NumRegs; 359 360 if (IsABIRegCopy) { 361 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 362 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 363 NumIntermediates, RegisterVT); 364 } else { 365 NumRegs = 366 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 367 NumIntermediates, RegisterVT); 368 } 369 370 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 371 NumParts = NumRegs; // Silence a compiler warning. 372 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 373 assert(RegisterVT.getSizeInBits() == 374 Parts[0].getSimpleValueType().getSizeInBits() && 375 "Part type sizes don't match!"); 376 377 // Assemble the parts into intermediate operands. 378 SmallVector<SDValue, 8> Ops(NumIntermediates); 379 if (NumIntermediates == NumParts) { 380 // If the register was not expanded, truncate or copy the value, 381 // as appropriate. 382 for (unsigned i = 0; i != NumParts; ++i) 383 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT, 384 V, InChain, CallConv); 385 } else if (NumParts > 0) { 386 // If the intermediate type was expanded, build the intermediate 387 // operands from the parts. 388 assert(NumParts % NumIntermediates == 0 && 389 "Must expand into a divisible number of parts!"); 390 unsigned Factor = NumParts / NumIntermediates; 391 for (unsigned i = 0; i != NumIntermediates; ++i) 392 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT, 393 IntermediateVT, V, InChain, CallConv); 394 } 395 396 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 397 // intermediate operands. 398 EVT BuiltVectorTy = 399 IntermediateVT.isVector() 400 ? EVT::getVectorVT( 401 *DAG.getContext(), IntermediateVT.getScalarType(), 402 IntermediateVT.getVectorElementCount() * NumParts) 403 : EVT::getVectorVT(*DAG.getContext(), 404 IntermediateVT.getScalarType(), 405 NumIntermediates); 406 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 407 : ISD::BUILD_VECTOR, 408 DL, BuiltVectorTy, Ops); 409 } 410 411 // There is now one part, held in Val. Correct it to match ValueVT. 412 EVT PartEVT = Val.getValueType(); 413 414 if (PartEVT == ValueVT) 415 return Val; 416 417 if (PartEVT.isVector()) { 418 // Vector/Vector bitcast. 419 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 420 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 421 422 // If the parts vector has more elements than the value vector, then we 423 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 424 // Extract the elements we want. 425 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 426 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 427 ValueVT.getVectorElementCount().getKnownMinValue()) && 428 (PartEVT.getVectorElementCount().isScalable() == 429 ValueVT.getVectorElementCount().isScalable()) && 430 "Cannot narrow, it would be a lossy transformation"); 431 PartEVT = 432 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 433 ValueVT.getVectorElementCount()); 434 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 435 DAG.getVectorIdxConstant(0, DL)); 436 if (PartEVT == ValueVT) 437 return Val; 438 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 439 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 440 441 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 442 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 443 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 444 } 445 446 // Promoted vector extract 447 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 448 } 449 450 // Trivial bitcast if the types are the same size and the destination 451 // vector type is legal. 452 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 453 TLI.isTypeLegal(ValueVT)) 454 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 455 456 if (ValueVT.getVectorNumElements() != 1) { 457 // Certain ABIs require that vectors are passed as integers. For vectors 458 // are the same size, this is an obvious bitcast. 459 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 460 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 461 } else if (ValueVT.bitsLT(PartEVT)) { 462 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 463 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 464 // Drop the extra bits. 465 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 466 return DAG.getBitcast(ValueVT, Val); 467 } 468 469 diagnosePossiblyInvalidConstraint( 470 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 471 return DAG.getUNDEF(ValueVT); 472 } 473 474 // Handle cases such as i8 -> <1 x i1> 475 EVT ValueSVT = ValueVT.getVectorElementType(); 476 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 477 unsigned ValueSize = ValueSVT.getSizeInBits(); 478 if (ValueSize == PartEVT.getSizeInBits()) { 479 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 480 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 481 // It's possible a scalar floating point type gets softened to integer and 482 // then promoted to a larger integer. If PartEVT is the larger integer 483 // we need to truncate it and then bitcast to the FP type. 484 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 485 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 486 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 487 Val = DAG.getBitcast(ValueSVT, Val); 488 } else { 489 Val = ValueVT.isFloatingPoint() 490 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 491 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 492 } 493 } 494 495 return DAG.getBuildVector(ValueVT, DL, Val); 496 } 497 498 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 499 SDValue Val, SDValue *Parts, unsigned NumParts, 500 MVT PartVT, const Value *V, 501 std::optional<CallingConv::ID> CallConv); 502 503 /// getCopyToParts - Create a series of nodes that contain the specified value 504 /// split into legal parts. If the parts contain more bits than Val, then, for 505 /// integers, ExtendKind can be used to specify how to generate the extra bits. 506 static void 507 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 508 unsigned NumParts, MVT PartVT, const Value *V, 509 std::optional<CallingConv::ID> CallConv = std::nullopt, 510 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 511 // Let the target split the parts if it wants to 512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 513 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 514 CallConv)) 515 return; 516 EVT ValueVT = Val.getValueType(); 517 518 // Handle the vector case separately. 519 if (ValueVT.isVector()) 520 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 521 CallConv); 522 523 unsigned OrigNumParts = NumParts; 524 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 525 "Copying to an illegal type!"); 526 527 if (NumParts == 0) 528 return; 529 530 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 531 EVT PartEVT = PartVT; 532 if (PartEVT == ValueVT) { 533 assert(NumParts == 1 && "No-op copy with multiple parts!"); 534 Parts[0] = Val; 535 return; 536 } 537 538 unsigned PartBits = PartVT.getSizeInBits(); 539 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 540 // If the parts cover more bits than the value has, promote the value. 541 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 542 assert(NumParts == 1 && "Do not know what to promote to!"); 543 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 544 } else { 545 if (ValueVT.isFloatingPoint()) { 546 // FP values need to be bitcast, then extended if they are being put 547 // into a larger container. 548 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 549 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 550 } 551 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 552 ValueVT.isInteger() && 553 "Unknown mismatch!"); 554 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 555 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 556 if (PartVT == MVT::x86mmx) 557 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 558 } 559 } else if (PartBits == ValueVT.getSizeInBits()) { 560 // Different types of the same size. 561 assert(NumParts == 1 && PartEVT != ValueVT); 562 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 563 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 564 // If the parts cover less bits than value has, truncate the value. 565 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 566 ValueVT.isInteger() && 567 "Unknown mismatch!"); 568 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 569 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 570 if (PartVT == MVT::x86mmx) 571 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 572 } 573 574 // The value may have changed - recompute ValueVT. 575 ValueVT = Val.getValueType(); 576 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 577 "Failed to tile the value with PartVT!"); 578 579 if (NumParts == 1) { 580 if (PartEVT != ValueVT) { 581 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 582 "scalar-to-vector conversion failed"); 583 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 584 } 585 586 Parts[0] = Val; 587 return; 588 } 589 590 // Expand the value into multiple parts. 591 if (NumParts & (NumParts - 1)) { 592 // The number of parts is not a power of 2. Split off and copy the tail. 593 assert(PartVT.isInteger() && ValueVT.isInteger() && 594 "Do not know what to expand to!"); 595 unsigned RoundParts = llvm::bit_floor(NumParts); 596 unsigned RoundBits = RoundParts * PartBits; 597 unsigned OddParts = NumParts - RoundParts; 598 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 599 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 600 601 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 602 CallConv); 603 604 if (DAG.getDataLayout().isBigEndian()) 605 // The odd parts were reversed by getCopyToParts - unreverse them. 606 std::reverse(Parts + RoundParts, Parts + NumParts); 607 608 NumParts = RoundParts; 609 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 610 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 611 } 612 613 // The number of parts is a power of 2. Repeatedly bisect the value using 614 // EXTRACT_ELEMENT. 615 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 616 EVT::getIntegerVT(*DAG.getContext(), 617 ValueVT.getSizeInBits()), 618 Val); 619 620 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 621 for (unsigned i = 0; i < NumParts; i += StepSize) { 622 unsigned ThisBits = StepSize * PartBits / 2; 623 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 624 SDValue &Part0 = Parts[i]; 625 SDValue &Part1 = Parts[i+StepSize/2]; 626 627 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 628 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 629 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 630 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 631 632 if (ThisBits == PartBits && ThisVT != PartVT) { 633 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 634 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 635 } 636 } 637 } 638 639 if (DAG.getDataLayout().isBigEndian()) 640 std::reverse(Parts, Parts + OrigNumParts); 641 } 642 643 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 644 const SDLoc &DL, EVT PartVT) { 645 if (!PartVT.isVector()) 646 return SDValue(); 647 648 EVT ValueVT = Val.getValueType(); 649 EVT PartEVT = PartVT.getVectorElementType(); 650 EVT ValueEVT = ValueVT.getVectorElementType(); 651 ElementCount PartNumElts = PartVT.getVectorElementCount(); 652 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 653 654 // We only support widening vectors with equivalent element types and 655 // fixed/scalable properties. If a target needs to widen a fixed-length type 656 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 657 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 658 PartNumElts.isScalable() != ValueNumElts.isScalable()) 659 return SDValue(); 660 661 // Have a try for bf16 because some targets share its ABI with fp16. 662 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 663 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 664 "Cannot widen to illegal type"); 665 Val = DAG.getNode(ISD::BITCAST, DL, 666 ValueVT.changeVectorElementType(MVT::f16), Val); 667 } else if (PartEVT != ValueEVT) { 668 return SDValue(); 669 } 670 671 // Widening a scalable vector to another scalable vector is done by inserting 672 // the vector into a larger undef one. 673 if (PartNumElts.isScalable()) 674 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 675 Val, DAG.getVectorIdxConstant(0, DL)); 676 677 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 678 // undef elements. 679 SmallVector<SDValue, 16> Ops; 680 DAG.ExtractVectorElements(Val, Ops); 681 SDValue EltUndef = DAG.getUNDEF(PartEVT); 682 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 683 684 // FIXME: Use CONCAT for 2x -> 4x. 685 return DAG.getBuildVector(PartVT, DL, Ops); 686 } 687 688 /// getCopyToPartsVector - Create a series of nodes that contain the specified 689 /// value split into legal parts. 690 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 691 SDValue Val, SDValue *Parts, unsigned NumParts, 692 MVT PartVT, const Value *V, 693 std::optional<CallingConv::ID> CallConv) { 694 EVT ValueVT = Val.getValueType(); 695 assert(ValueVT.isVector() && "Not a vector"); 696 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 697 const bool IsABIRegCopy = CallConv.has_value(); 698 699 if (NumParts == 1) { 700 EVT PartEVT = PartVT; 701 if (PartEVT == ValueVT) { 702 // Nothing to do. 703 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 704 // Bitconvert vector->vector case. 705 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 706 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 707 Val = Widened; 708 } else if (PartVT.isVector() && 709 PartEVT.getVectorElementType().bitsGE( 710 ValueVT.getVectorElementType()) && 711 PartEVT.getVectorElementCount() == 712 ValueVT.getVectorElementCount()) { 713 714 // Promoted vector extract 715 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 716 } else if (PartEVT.isVector() && 717 PartEVT.getVectorElementType() != 718 ValueVT.getVectorElementType() && 719 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 720 TargetLowering::TypeWidenVector) { 721 // Combination of widening and promotion. 722 EVT WidenVT = 723 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 724 PartVT.getVectorElementCount()); 725 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 726 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 727 } else { 728 // Don't extract an integer from a float vector. This can happen if the 729 // FP type gets softened to integer and then promoted. The promotion 730 // prevents it from being picked up by the earlier bitcast case. 731 if (ValueVT.getVectorElementCount().isScalar() && 732 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 733 // If we reach this condition and PartVT is FP, this means that 734 // ValueVT is also FP and both have a different size, otherwise we 735 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here 736 // would be invalid since that would mean the smaller FP type has to 737 // be extended to the larger one. 738 if (PartVT.isFloatingPoint()) { 739 Val = DAG.getBitcast(ValueVT.getScalarType(), Val); 740 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 741 } else 742 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 743 DAG.getVectorIdxConstant(0, DL)); 744 } else { 745 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 746 assert(PartVT.getFixedSizeInBits() > ValueSize && 747 "lossy conversion of vector to scalar type"); 748 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 749 Val = DAG.getBitcast(IntermediateType, Val); 750 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 751 } 752 } 753 754 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 755 Parts[0] = Val; 756 return; 757 } 758 759 // Handle a multi-element vector. 760 EVT IntermediateVT; 761 MVT RegisterVT; 762 unsigned NumIntermediates; 763 unsigned NumRegs; 764 if (IsABIRegCopy) { 765 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 766 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 767 RegisterVT); 768 } else { 769 NumRegs = 770 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 771 NumIntermediates, RegisterVT); 772 } 773 774 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 775 NumParts = NumRegs; // Silence a compiler warning. 776 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 777 778 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 779 "Mixing scalable and fixed vectors when copying in parts"); 780 781 std::optional<ElementCount> DestEltCnt; 782 783 if (IntermediateVT.isVector()) 784 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 785 else 786 DestEltCnt = ElementCount::getFixed(NumIntermediates); 787 788 EVT BuiltVectorTy = EVT::getVectorVT( 789 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 790 791 if (ValueVT == BuiltVectorTy) { 792 // Nothing to do. 793 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 794 // Bitconvert vector->vector case. 795 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 796 } else { 797 if (BuiltVectorTy.getVectorElementType().bitsGT( 798 ValueVT.getVectorElementType())) { 799 // Integer promotion. 800 ValueVT = EVT::getVectorVT(*DAG.getContext(), 801 BuiltVectorTy.getVectorElementType(), 802 ValueVT.getVectorElementCount()); 803 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 804 } 805 806 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 807 Val = Widened; 808 } 809 } 810 811 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 812 813 // Split the vector into intermediate operands. 814 SmallVector<SDValue, 8> Ops(NumIntermediates); 815 for (unsigned i = 0; i != NumIntermediates; ++i) { 816 if (IntermediateVT.isVector()) { 817 // This does something sensible for scalable vectors - see the 818 // definition of EXTRACT_SUBVECTOR for further details. 819 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 820 Ops[i] = 821 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 822 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 823 } else { 824 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 825 DAG.getVectorIdxConstant(i, DL)); 826 } 827 } 828 829 // Split the intermediate operands into legal parts. 830 if (NumParts == NumIntermediates) { 831 // If the register was not expanded, promote or copy the value, 832 // as appropriate. 833 for (unsigned i = 0; i != NumParts; ++i) 834 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 835 } else if (NumParts > 0) { 836 // If the intermediate type was expanded, split each the value into 837 // legal parts. 838 assert(NumIntermediates != 0 && "division by zero"); 839 assert(NumParts % NumIntermediates == 0 && 840 "Must expand into a divisible number of parts!"); 841 unsigned Factor = NumParts / NumIntermediates; 842 for (unsigned i = 0; i != NumIntermediates; ++i) 843 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 844 CallConv); 845 } 846 } 847 848 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 849 EVT valuevt, std::optional<CallingConv::ID> CC) 850 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 851 RegCount(1, regs.size()), CallConv(CC) {} 852 853 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 854 const DataLayout &DL, unsigned Reg, Type *Ty, 855 std::optional<CallingConv::ID> CC) { 856 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 857 858 CallConv = CC; 859 860 for (EVT ValueVT : ValueVTs) { 861 unsigned NumRegs = 862 isABIMangled() 863 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 864 : TLI.getNumRegisters(Context, ValueVT); 865 MVT RegisterVT = 866 isABIMangled() 867 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 868 : TLI.getRegisterType(Context, ValueVT); 869 for (unsigned i = 0; i != NumRegs; ++i) 870 Regs.push_back(Reg + i); 871 RegVTs.push_back(RegisterVT); 872 RegCount.push_back(NumRegs); 873 Reg += NumRegs; 874 } 875 } 876 877 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 878 FunctionLoweringInfo &FuncInfo, 879 const SDLoc &dl, SDValue &Chain, 880 SDValue *Glue, const Value *V) const { 881 // A Value with type {} or [0 x %t] needs no registers. 882 if (ValueVTs.empty()) 883 return SDValue(); 884 885 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 886 887 // Assemble the legal parts into the final values. 888 SmallVector<SDValue, 4> Values(ValueVTs.size()); 889 SmallVector<SDValue, 8> Parts; 890 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 891 // Copy the legal parts from the registers. 892 EVT ValueVT = ValueVTs[Value]; 893 unsigned NumRegs = RegCount[Value]; 894 MVT RegisterVT = isABIMangled() 895 ? TLI.getRegisterTypeForCallingConv( 896 *DAG.getContext(), *CallConv, RegVTs[Value]) 897 : RegVTs[Value]; 898 899 Parts.resize(NumRegs); 900 for (unsigned i = 0; i != NumRegs; ++i) { 901 SDValue P; 902 if (!Glue) { 903 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 904 } else { 905 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 906 *Glue = P.getValue(2); 907 } 908 909 Chain = P.getValue(1); 910 Parts[i] = P; 911 912 // If the source register was virtual and if we know something about it, 913 // add an assert node. 914 if (!Register::isVirtualRegister(Regs[Part + i]) || 915 !RegisterVT.isInteger()) 916 continue; 917 918 const FunctionLoweringInfo::LiveOutInfo *LOI = 919 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 920 if (!LOI) 921 continue; 922 923 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 924 unsigned NumSignBits = LOI->NumSignBits; 925 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 926 927 if (NumZeroBits == RegSize) { 928 // The current value is a zero. 929 // Explicitly express that as it would be easier for 930 // optimizations to kick in. 931 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 932 continue; 933 } 934 935 // FIXME: We capture more information than the dag can represent. For 936 // now, just use the tightest assertzext/assertsext possible. 937 bool isSExt; 938 EVT FromVT(MVT::Other); 939 if (NumZeroBits) { 940 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 941 isSExt = false; 942 } else if (NumSignBits > 1) { 943 FromVT = 944 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 945 isSExt = true; 946 } else { 947 continue; 948 } 949 // Add an assertion node. 950 assert(FromVT != MVT::Other); 951 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 952 RegisterVT, P, DAG.getValueType(FromVT)); 953 } 954 955 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 956 RegisterVT, ValueVT, V, Chain, CallConv); 957 Part += NumRegs; 958 Parts.clear(); 959 } 960 961 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 962 } 963 964 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 965 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 966 const Value *V, 967 ISD::NodeType PreferredExtendType) const { 968 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 969 ISD::NodeType ExtendKind = PreferredExtendType; 970 971 // Get the list of the values's legal parts. 972 unsigned NumRegs = Regs.size(); 973 SmallVector<SDValue, 8> Parts(NumRegs); 974 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 975 unsigned NumParts = RegCount[Value]; 976 977 MVT RegisterVT = isABIMangled() 978 ? TLI.getRegisterTypeForCallingConv( 979 *DAG.getContext(), *CallConv, RegVTs[Value]) 980 : RegVTs[Value]; 981 982 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 983 ExtendKind = ISD::ZERO_EXTEND; 984 985 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 986 NumParts, RegisterVT, V, CallConv, ExtendKind); 987 Part += NumParts; 988 } 989 990 // Copy the parts into the registers. 991 SmallVector<SDValue, 8> Chains(NumRegs); 992 for (unsigned i = 0; i != NumRegs; ++i) { 993 SDValue Part; 994 if (!Glue) { 995 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 996 } else { 997 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 998 *Glue = Part.getValue(1); 999 } 1000 1001 Chains[i] = Part.getValue(0); 1002 } 1003 1004 if (NumRegs == 1 || Glue) 1005 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 1006 // flagged to it. That is the CopyToReg nodes and the user are considered 1007 // a single scheduling unit. If we create a TokenFactor and return it as 1008 // chain, then the TokenFactor is both a predecessor (operand) of the 1009 // user as well as a successor (the TF operands are flagged to the user). 1010 // c1, f1 = CopyToReg 1011 // c2, f2 = CopyToReg 1012 // c3 = TokenFactor c1, c2 1013 // ... 1014 // = op c3, ..., f2 1015 Chain = Chains[NumRegs-1]; 1016 else 1017 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 1018 } 1019 1020 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 1021 unsigned MatchingIdx, const SDLoc &dl, 1022 SelectionDAG &DAG, 1023 std::vector<SDValue> &Ops) const { 1024 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1025 1026 InlineAsm::Flag Flag(Code, Regs.size()); 1027 if (HasMatching) 1028 Flag.setMatchingOp(MatchingIdx); 1029 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1030 // Put the register class of the virtual registers in the flag word. That 1031 // way, later passes can recompute register class constraints for inline 1032 // assembly as well as normal instructions. 1033 // Don't do this for tied operands that can use the regclass information 1034 // from the def. 1035 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1036 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1037 Flag.setRegClass(RC->getID()); 1038 } 1039 1040 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1041 Ops.push_back(Res); 1042 1043 if (Code == InlineAsm::Kind::Clobber) { 1044 // Clobbers should always have a 1:1 mapping with registers, and may 1045 // reference registers that have illegal (e.g. vector) types. Hence, we 1046 // shouldn't try to apply any sort of splitting logic to them. 1047 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1048 "No 1:1 mapping from clobbers to regs?"); 1049 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1050 (void)SP; 1051 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1052 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1053 assert( 1054 (Regs[I] != SP || 1055 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1056 "If we clobbered the stack pointer, MFI should know about it."); 1057 } 1058 return; 1059 } 1060 1061 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1062 MVT RegisterVT = RegVTs[Value]; 1063 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1064 RegisterVT); 1065 for (unsigned i = 0; i != NumRegs; ++i) { 1066 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1067 unsigned TheReg = Regs[Reg++]; 1068 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1069 } 1070 } 1071 } 1072 1073 SmallVector<std::pair<unsigned, TypeSize>, 4> 1074 RegsForValue::getRegsAndSizes() const { 1075 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1076 unsigned I = 0; 1077 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1078 unsigned RegCount = std::get<0>(CountAndVT); 1079 MVT RegisterVT = std::get<1>(CountAndVT); 1080 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1081 for (unsigned E = I + RegCount; I != E; ++I) 1082 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1083 } 1084 return OutVec; 1085 } 1086 1087 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1088 AssumptionCache *ac, 1089 const TargetLibraryInfo *li) { 1090 AA = aa; 1091 AC = ac; 1092 GFI = gfi; 1093 LibInfo = li; 1094 Context = DAG.getContext(); 1095 LPadToCallSiteMap.clear(); 1096 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1097 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1098 *DAG.getMachineFunction().getFunction().getParent()); 1099 } 1100 1101 void SelectionDAGBuilder::clear() { 1102 NodeMap.clear(); 1103 UnusedArgNodeMap.clear(); 1104 PendingLoads.clear(); 1105 PendingExports.clear(); 1106 PendingConstrainedFP.clear(); 1107 PendingConstrainedFPStrict.clear(); 1108 CurInst = nullptr; 1109 HasTailCall = false; 1110 SDNodeOrder = LowestSDNodeOrder; 1111 StatepointLowering.clear(); 1112 } 1113 1114 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1115 DanglingDebugInfoMap.clear(); 1116 } 1117 1118 // Update DAG root to include dependencies on Pending chains. 1119 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1120 SDValue Root = DAG.getRoot(); 1121 1122 if (Pending.empty()) 1123 return Root; 1124 1125 // Add current root to PendingChains, unless we already indirectly 1126 // depend on it. 1127 if (Root.getOpcode() != ISD::EntryToken) { 1128 unsigned i = 0, e = Pending.size(); 1129 for (; i != e; ++i) { 1130 assert(Pending[i].getNode()->getNumOperands() > 1); 1131 if (Pending[i].getNode()->getOperand(0) == Root) 1132 break; // Don't add the root if we already indirectly depend on it. 1133 } 1134 1135 if (i == e) 1136 Pending.push_back(Root); 1137 } 1138 1139 if (Pending.size() == 1) 1140 Root = Pending[0]; 1141 else 1142 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1143 1144 DAG.setRoot(Root); 1145 Pending.clear(); 1146 return Root; 1147 } 1148 1149 SDValue SelectionDAGBuilder::getMemoryRoot() { 1150 return updateRoot(PendingLoads); 1151 } 1152 1153 SDValue SelectionDAGBuilder::getRoot() { 1154 // Chain up all pending constrained intrinsics together with all 1155 // pending loads, by simply appending them to PendingLoads and 1156 // then calling getMemoryRoot(). 1157 PendingLoads.reserve(PendingLoads.size() + 1158 PendingConstrainedFP.size() + 1159 PendingConstrainedFPStrict.size()); 1160 PendingLoads.append(PendingConstrainedFP.begin(), 1161 PendingConstrainedFP.end()); 1162 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1163 PendingConstrainedFPStrict.end()); 1164 PendingConstrainedFP.clear(); 1165 PendingConstrainedFPStrict.clear(); 1166 return getMemoryRoot(); 1167 } 1168 1169 SDValue SelectionDAGBuilder::getControlRoot() { 1170 // We need to emit pending fpexcept.strict constrained intrinsics, 1171 // so append them to the PendingExports list. 1172 PendingExports.append(PendingConstrainedFPStrict.begin(), 1173 PendingConstrainedFPStrict.end()); 1174 PendingConstrainedFPStrict.clear(); 1175 return updateRoot(PendingExports); 1176 } 1177 1178 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1179 DILocalVariable *Variable, 1180 DIExpression *Expression, 1181 DebugLoc DL) { 1182 assert(Variable && "Missing variable"); 1183 1184 // Check if address has undef value. 1185 if (!Address || isa<UndefValue>(Address) || 1186 (Address->use_empty() && !isa<Argument>(Address))) { 1187 LLVM_DEBUG( 1188 dbgs() 1189 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1190 return; 1191 } 1192 1193 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1194 1195 SDValue &N = NodeMap[Address]; 1196 if (!N.getNode() && isa<Argument>(Address)) 1197 // Check unused arguments map. 1198 N = UnusedArgNodeMap[Address]; 1199 SDDbgValue *SDV; 1200 if (N.getNode()) { 1201 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1202 Address = BCI->getOperand(0); 1203 // Parameters are handled specially. 1204 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1205 if (IsParameter && FINode) { 1206 // Byval parameter. We have a frame index at this point. 1207 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1208 /*IsIndirect*/ true, DL, SDNodeOrder); 1209 } else if (isa<Argument>(Address)) { 1210 // Address is an argument, so try to emit its dbg value using 1211 // virtual register info from the FuncInfo.ValueMap. 1212 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1213 FuncArgumentDbgValueKind::Declare, N); 1214 return; 1215 } else { 1216 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1217 true, DL, SDNodeOrder); 1218 } 1219 DAG.AddDbgValue(SDV, IsParameter); 1220 } else { 1221 // If Address is an argument then try to emit its dbg value using 1222 // virtual register info from the FuncInfo.ValueMap. 1223 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1224 FuncArgumentDbgValueKind::Declare, N)) { 1225 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1226 << " (could not emit func-arg dbg_value)\n"); 1227 } 1228 } 1229 return; 1230 } 1231 1232 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1233 // Add SDDbgValue nodes for any var locs here. Do so before updating 1234 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1235 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1236 // Add SDDbgValue nodes for any var locs here. Do so before updating 1237 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1238 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1239 It != End; ++It) { 1240 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1241 dropDanglingDebugInfo(Var, It->Expr); 1242 if (It->Values.isKillLocation(It->Expr)) { 1243 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1244 continue; 1245 } 1246 SmallVector<Value *> Values(It->Values.location_ops()); 1247 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1248 It->Values.hasArgList())) { 1249 SmallVector<Value *, 4> Vals(It->Values.location_ops()); 1250 addDanglingDebugInfo(Vals, 1251 FnVarLocs->getDILocalVariable(It->VariableID), 1252 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1253 } 1254 } 1255 } 1256 1257 // We must skip DbgVariableRecords if they've already been processed above as 1258 // we have just emitted the debug values resulting from assignment tracking 1259 // analysis, making any existing DbgVariableRecords redundant (and probably 1260 // less correct). We still need to process DbgLabelRecords. This does sink 1261 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't 1262 // be important as it does so deterministcally and ordering between 1263 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR 1264 // printing). 1265 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs(); 1266 // Is there is any debug-info attached to this instruction, in the form of 1267 // DbgRecord non-instruction debug-info records. 1268 for (DbgRecord &DR : I.getDbgRecordRange()) { 1269 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 1270 assert(DLR->getLabel() && "Missing label"); 1271 SDDbgLabel *SDV = 1272 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder); 1273 DAG.AddDbgLabel(SDV); 1274 continue; 1275 } 1276 1277 if (SkipDbgVariableRecords) 1278 continue; 1279 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 1280 DILocalVariable *Variable = DVR.getVariable(); 1281 DIExpression *Expression = DVR.getExpression(); 1282 dropDanglingDebugInfo(Variable, Expression); 1283 1284 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) { 1285 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR)) 1286 continue; 1287 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR 1288 << "\n"); 1289 handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression, 1290 DVR.getDebugLoc()); 1291 continue; 1292 } 1293 1294 // A DbgVariableRecord with no locations is a kill location. 1295 SmallVector<Value *, 4> Values(DVR.location_ops()); 1296 if (Values.empty()) { 1297 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1298 SDNodeOrder); 1299 continue; 1300 } 1301 1302 // A DbgVariableRecord with an undef or absent location is also a kill 1303 // location. 1304 if (llvm::any_of(Values, 1305 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1306 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1307 SDNodeOrder); 1308 continue; 1309 } 1310 1311 bool IsVariadic = DVR.hasArgList(); 1312 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(), 1313 SDNodeOrder, IsVariadic)) { 1314 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1315 DVR.getDebugLoc(), SDNodeOrder); 1316 } 1317 } 1318 } 1319 1320 void SelectionDAGBuilder::visit(const Instruction &I) { 1321 visitDbgInfo(I); 1322 1323 // Set up outgoing PHI node register values before emitting the terminator. 1324 if (I.isTerminator()) { 1325 HandlePHINodesInSuccessorBlocks(I.getParent()); 1326 } 1327 1328 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1329 if (!isa<DbgInfoIntrinsic>(I)) 1330 ++SDNodeOrder; 1331 1332 CurInst = &I; 1333 1334 // Set inserted listener only if required. 1335 bool NodeInserted = false; 1336 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1337 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1338 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra); 1339 if (PCSectionsMD || MMRA) { 1340 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1341 DAG, [&](SDNode *) { NodeInserted = true; }); 1342 } 1343 1344 visit(I.getOpcode(), I); 1345 1346 if (!I.isTerminator() && !HasTailCall && 1347 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1348 CopyToExportRegsIfNeeded(&I); 1349 1350 // Handle metadata. 1351 if (PCSectionsMD || MMRA) { 1352 auto It = NodeMap.find(&I); 1353 if (It != NodeMap.end()) { 1354 if (PCSectionsMD) 1355 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1356 if (MMRA) 1357 DAG.addMMRAMetadata(It->second.getNode(), MMRA); 1358 } else if (NodeInserted) { 1359 // This should not happen; if it does, don't let it go unnoticed so we can 1360 // fix it. Relevant visit*() function is probably missing a setValue(). 1361 errs() << "warning: loosing !pcsections and/or !mmra metadata [" 1362 << I.getModule()->getName() << "]\n"; 1363 LLVM_DEBUG(I.dump()); 1364 assert(false); 1365 } 1366 } 1367 1368 CurInst = nullptr; 1369 } 1370 1371 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1372 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1373 } 1374 1375 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1376 // Note: this doesn't use InstVisitor, because it has to work with 1377 // ConstantExpr's in addition to instructions. 1378 switch (Opcode) { 1379 default: llvm_unreachable("Unknown instruction type encountered!"); 1380 // Build the switch statement using the Instruction.def file. 1381 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1382 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1383 #include "llvm/IR/Instruction.def" 1384 } 1385 } 1386 1387 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1388 DILocalVariable *Variable, 1389 DebugLoc DL, unsigned Order, 1390 SmallVectorImpl<Value *> &Values, 1391 DIExpression *Expression) { 1392 // For variadic dbg_values we will now insert an undef. 1393 // FIXME: We can potentially recover these! 1394 SmallVector<SDDbgOperand, 2> Locs; 1395 for (const Value *V : Values) { 1396 auto *Undef = UndefValue::get(V->getType()); 1397 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1398 } 1399 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1400 /*IsIndirect=*/false, DL, Order, 1401 /*IsVariadic=*/true); 1402 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1403 return true; 1404 } 1405 1406 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1407 DILocalVariable *Var, 1408 DIExpression *Expr, 1409 bool IsVariadic, DebugLoc DL, 1410 unsigned Order) { 1411 if (IsVariadic) { 1412 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1413 return; 1414 } 1415 // TODO: Dangling debug info will eventually either be resolved or produce 1416 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1417 // between the original dbg.value location and its resolved DBG_VALUE, 1418 // which we should ideally fill with an extra Undef DBG_VALUE. 1419 assert(Values.size() == 1); 1420 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1421 } 1422 1423 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1424 const DIExpression *Expr) { 1425 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1426 DIVariable *DanglingVariable = DDI.getVariable(); 1427 DIExpression *DanglingExpr = DDI.getExpression(); 1428 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1429 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1430 << printDDI(nullptr, DDI) << "\n"); 1431 return true; 1432 } 1433 return false; 1434 }; 1435 1436 for (auto &DDIMI : DanglingDebugInfoMap) { 1437 DanglingDebugInfoVector &DDIV = DDIMI.second; 1438 1439 // If debug info is to be dropped, run it through final checks to see 1440 // whether it can be salvaged. 1441 for (auto &DDI : DDIV) 1442 if (isMatchingDbgValue(DDI)) 1443 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1444 1445 erase_if(DDIV, isMatchingDbgValue); 1446 } 1447 } 1448 1449 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1450 // generate the debug data structures now that we've seen its definition. 1451 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1452 SDValue Val) { 1453 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1454 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1455 return; 1456 1457 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1458 for (auto &DDI : DDIV) { 1459 DebugLoc DL = DDI.getDebugLoc(); 1460 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1461 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1462 DILocalVariable *Variable = DDI.getVariable(); 1463 DIExpression *Expr = DDI.getExpression(); 1464 assert(Variable->isValidLocationForIntrinsic(DL) && 1465 "Expected inlined-at fields to agree"); 1466 SDDbgValue *SDV; 1467 if (Val.getNode()) { 1468 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1469 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1470 // we couldn't resolve it directly when examining the DbgValue intrinsic 1471 // in the first place we should not be more successful here). Unless we 1472 // have some test case that prove this to be correct we should avoid 1473 // calling EmitFuncArgumentDbgValue here. 1474 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1475 FuncArgumentDbgValueKind::Value, Val)) { 1476 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1477 << printDDI(V, DDI) << "\n"); 1478 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1479 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1480 // inserted after the definition of Val when emitting the instructions 1481 // after ISel. An alternative could be to teach 1482 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1483 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1484 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1485 << ValSDNodeOrder << "\n"); 1486 SDV = getDbgValue(Val, Variable, Expr, DL, 1487 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1488 DAG.AddDbgValue(SDV, false); 1489 } else 1490 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1491 << printDDI(V, DDI) 1492 << " in EmitFuncArgumentDbgValue\n"); 1493 } else { 1494 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1495 << "\n"); 1496 auto Undef = UndefValue::get(V->getType()); 1497 auto SDV = 1498 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1499 DAG.AddDbgValue(SDV, false); 1500 } 1501 } 1502 DDIV.clear(); 1503 } 1504 1505 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1506 DanglingDebugInfo &DDI) { 1507 // TODO: For the variadic implementation, instead of only checking the fail 1508 // state of `handleDebugValue`, we need know specifically which values were 1509 // invalid, so that we attempt to salvage only those values when processing 1510 // a DIArgList. 1511 const Value *OrigV = V; 1512 DILocalVariable *Var = DDI.getVariable(); 1513 DIExpression *Expr = DDI.getExpression(); 1514 DebugLoc DL = DDI.getDebugLoc(); 1515 unsigned SDOrder = DDI.getSDNodeOrder(); 1516 1517 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1518 // that DW_OP_stack_value is desired. 1519 bool StackValue = true; 1520 1521 // Can this Value can be encoded without any further work? 1522 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1523 return; 1524 1525 // Attempt to salvage back through as many instructions as possible. Bail if 1526 // a non-instruction is seen, such as a constant expression or global 1527 // variable. FIXME: Further work could recover those too. 1528 while (isa<Instruction>(V)) { 1529 const Instruction &VAsInst = *cast<const Instruction>(V); 1530 // Temporary "0", awaiting real implementation. 1531 SmallVector<uint64_t, 16> Ops; 1532 SmallVector<Value *, 4> AdditionalValues; 1533 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1534 Expr->getNumLocationOperands(), Ops, 1535 AdditionalValues); 1536 // If we cannot salvage any further, and haven't yet found a suitable debug 1537 // expression, bail out. 1538 if (!V) 1539 break; 1540 1541 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1542 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1543 // here for variadic dbg_values, remove that condition. 1544 if (!AdditionalValues.empty()) 1545 break; 1546 1547 // New value and expr now represent this debuginfo. 1548 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1549 1550 // Some kind of simplification occurred: check whether the operand of the 1551 // salvaged debug expression can be encoded in this DAG. 1552 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1553 LLVM_DEBUG( 1554 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1555 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1556 return; 1557 } 1558 } 1559 1560 // This was the final opportunity to salvage this debug information, and it 1561 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1562 // any earlier variable location. 1563 assert(OrigV && "V shouldn't be null"); 1564 auto *Undef = UndefValue::get(OrigV->getType()); 1565 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1566 DAG.AddDbgValue(SDV, false); 1567 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1568 << printDDI(OrigV, DDI) << "\n"); 1569 } 1570 1571 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1572 DIExpression *Expr, 1573 DebugLoc DbgLoc, 1574 unsigned Order) { 1575 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1576 DIExpression *NewExpr = 1577 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1578 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1579 /*IsVariadic*/ false); 1580 } 1581 1582 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1583 DILocalVariable *Var, 1584 DIExpression *Expr, DebugLoc DbgLoc, 1585 unsigned Order, bool IsVariadic) { 1586 if (Values.empty()) 1587 return true; 1588 1589 // Filter EntryValue locations out early. 1590 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1591 return true; 1592 1593 SmallVector<SDDbgOperand> LocationOps; 1594 SmallVector<SDNode *> Dependencies; 1595 for (const Value *V : Values) { 1596 // Constant value. 1597 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1598 isa<ConstantPointerNull>(V)) { 1599 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1600 continue; 1601 } 1602 1603 // Look through IntToPtr constants. 1604 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1605 if (CE->getOpcode() == Instruction::IntToPtr) { 1606 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1607 continue; 1608 } 1609 1610 // If the Value is a frame index, we can create a FrameIndex debug value 1611 // without relying on the DAG at all. 1612 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1613 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1614 if (SI != FuncInfo.StaticAllocaMap.end()) { 1615 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1616 continue; 1617 } 1618 } 1619 1620 // Do not use getValue() in here; we don't want to generate code at 1621 // this point if it hasn't been done yet. 1622 SDValue N = NodeMap[V]; 1623 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1624 N = UnusedArgNodeMap[V]; 1625 if (N.getNode()) { 1626 // Only emit func arg dbg value for non-variadic dbg.values for now. 1627 if (!IsVariadic && 1628 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1629 FuncArgumentDbgValueKind::Value, N)) 1630 return true; 1631 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1632 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1633 // describe stack slot locations. 1634 // 1635 // Consider "int x = 0; int *px = &x;". There are two kinds of 1636 // interesting debug values here after optimization: 1637 // 1638 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1639 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1640 // 1641 // Both describe the direct values of their associated variables. 1642 Dependencies.push_back(N.getNode()); 1643 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1644 continue; 1645 } 1646 LocationOps.emplace_back( 1647 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1648 continue; 1649 } 1650 1651 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1652 // Special rules apply for the first dbg.values of parameter variables in a 1653 // function. Identify them by the fact they reference Argument Values, that 1654 // they're parameters, and they are parameters of the current function. We 1655 // need to let them dangle until they get an SDNode. 1656 bool IsParamOfFunc = 1657 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1658 if (IsParamOfFunc) 1659 return false; 1660 1661 // The value is not used in this block yet (or it would have an SDNode). 1662 // We still want the value to appear for the user if possible -- if it has 1663 // an associated VReg, we can refer to that instead. 1664 auto VMI = FuncInfo.ValueMap.find(V); 1665 if (VMI != FuncInfo.ValueMap.end()) { 1666 unsigned Reg = VMI->second; 1667 // If this is a PHI node, it may be split up into several MI PHI nodes 1668 // (in FunctionLoweringInfo::set). 1669 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1670 V->getType(), std::nullopt); 1671 if (RFV.occupiesMultipleRegs()) { 1672 // FIXME: We could potentially support variadic dbg_values here. 1673 if (IsVariadic) 1674 return false; 1675 unsigned Offset = 0; 1676 unsigned BitsToDescribe = 0; 1677 if (auto VarSize = Var->getSizeInBits()) 1678 BitsToDescribe = *VarSize; 1679 if (auto Fragment = Expr->getFragmentInfo()) 1680 BitsToDescribe = Fragment->SizeInBits; 1681 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1682 // Bail out if all bits are described already. 1683 if (Offset >= BitsToDescribe) 1684 break; 1685 // TODO: handle scalable vectors. 1686 unsigned RegisterSize = RegAndSize.second; 1687 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1688 ? BitsToDescribe - Offset 1689 : RegisterSize; 1690 auto FragmentExpr = DIExpression::createFragmentExpression( 1691 Expr, Offset, FragmentSize); 1692 if (!FragmentExpr) 1693 continue; 1694 SDDbgValue *SDV = DAG.getVRegDbgValue( 1695 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order); 1696 DAG.AddDbgValue(SDV, false); 1697 Offset += RegisterSize; 1698 } 1699 return true; 1700 } 1701 // We can use simple vreg locations for variadic dbg_values as well. 1702 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1703 continue; 1704 } 1705 // We failed to create a SDDbgOperand for V. 1706 return false; 1707 } 1708 1709 // We have created a SDDbgOperand for each Value in Values. 1710 assert(!LocationOps.empty()); 1711 SDDbgValue *SDV = 1712 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1713 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic); 1714 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1715 return true; 1716 } 1717 1718 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1719 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1720 for (auto &Pair : DanglingDebugInfoMap) 1721 for (auto &DDI : Pair.second) 1722 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1723 clearDanglingDebugInfo(); 1724 } 1725 1726 /// getCopyFromRegs - If there was virtual register allocated for the value V 1727 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1728 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1729 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1730 SDValue Result; 1731 1732 if (It != FuncInfo.ValueMap.end()) { 1733 Register InReg = It->second; 1734 1735 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1736 DAG.getDataLayout(), InReg, Ty, 1737 std::nullopt); // This is not an ABI copy. 1738 SDValue Chain = DAG.getEntryNode(); 1739 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1740 V); 1741 resolveDanglingDebugInfo(V, Result); 1742 } 1743 1744 return Result; 1745 } 1746 1747 /// getValue - Return an SDValue for the given Value. 1748 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1749 // If we already have an SDValue for this value, use it. It's important 1750 // to do this first, so that we don't create a CopyFromReg if we already 1751 // have a regular SDValue. 1752 SDValue &N = NodeMap[V]; 1753 if (N.getNode()) return N; 1754 1755 // If there's a virtual register allocated and initialized for this 1756 // value, use it. 1757 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1758 return copyFromReg; 1759 1760 // Otherwise create a new SDValue and remember it. 1761 SDValue Val = getValueImpl(V); 1762 NodeMap[V] = Val; 1763 resolveDanglingDebugInfo(V, Val); 1764 return Val; 1765 } 1766 1767 /// getNonRegisterValue - Return an SDValue for the given Value, but 1768 /// don't look in FuncInfo.ValueMap for a virtual register. 1769 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1770 // If we already have an SDValue for this value, use it. 1771 SDValue &N = NodeMap[V]; 1772 if (N.getNode()) { 1773 if (isIntOrFPConstant(N)) { 1774 // Remove the debug location from the node as the node is about to be used 1775 // in a location which may differ from the original debug location. This 1776 // is relevant to Constant and ConstantFP nodes because they can appear 1777 // as constant expressions inside PHI nodes. 1778 N->setDebugLoc(DebugLoc()); 1779 } 1780 return N; 1781 } 1782 1783 // Otherwise create a new SDValue and remember it. 1784 SDValue Val = getValueImpl(V); 1785 NodeMap[V] = Val; 1786 resolveDanglingDebugInfo(V, Val); 1787 return Val; 1788 } 1789 1790 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1791 /// Create an SDValue for the given value. 1792 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1793 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1794 1795 if (const Constant *C = dyn_cast<Constant>(V)) { 1796 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1797 1798 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1799 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1800 1801 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1802 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1803 1804 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) { 1805 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT, 1806 getValue(CPA->getPointer()), getValue(CPA->getKey()), 1807 getValue(CPA->getAddrDiscriminator()), 1808 getValue(CPA->getDiscriminator())); 1809 } 1810 1811 if (isa<ConstantPointerNull>(C)) { 1812 unsigned AS = V->getType()->getPointerAddressSpace(); 1813 return DAG.getConstant(0, getCurSDLoc(), 1814 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1815 } 1816 1817 if (match(C, m_VScale())) 1818 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1819 1820 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1821 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1822 1823 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1824 return DAG.getUNDEF(VT); 1825 1826 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1827 visit(CE->getOpcode(), *CE); 1828 SDValue N1 = NodeMap[V]; 1829 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1830 return N1; 1831 } 1832 1833 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1834 SmallVector<SDValue, 4> Constants; 1835 for (const Use &U : C->operands()) { 1836 SDNode *Val = getValue(U).getNode(); 1837 // If the operand is an empty aggregate, there are no values. 1838 if (!Val) continue; 1839 // Add each leaf value from the operand to the Constants list 1840 // to form a flattened list of all the values. 1841 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1842 Constants.push_back(SDValue(Val, i)); 1843 } 1844 1845 return DAG.getMergeValues(Constants, getCurSDLoc()); 1846 } 1847 1848 if (const ConstantDataSequential *CDS = 1849 dyn_cast<ConstantDataSequential>(C)) { 1850 SmallVector<SDValue, 4> Ops; 1851 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1852 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1853 // Add each leaf value from the operand to the Constants list 1854 // to form a flattened list of all the values. 1855 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1856 Ops.push_back(SDValue(Val, i)); 1857 } 1858 1859 if (isa<ArrayType>(CDS->getType())) 1860 return DAG.getMergeValues(Ops, getCurSDLoc()); 1861 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1862 } 1863 1864 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1865 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1866 "Unknown struct or array constant!"); 1867 1868 SmallVector<EVT, 4> ValueVTs; 1869 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1870 unsigned NumElts = ValueVTs.size(); 1871 if (NumElts == 0) 1872 return SDValue(); // empty struct 1873 SmallVector<SDValue, 4> Constants(NumElts); 1874 for (unsigned i = 0; i != NumElts; ++i) { 1875 EVT EltVT = ValueVTs[i]; 1876 if (isa<UndefValue>(C)) 1877 Constants[i] = DAG.getUNDEF(EltVT); 1878 else if (EltVT.isFloatingPoint()) 1879 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1880 else 1881 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1882 } 1883 1884 return DAG.getMergeValues(Constants, getCurSDLoc()); 1885 } 1886 1887 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1888 return DAG.getBlockAddress(BA, VT); 1889 1890 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1891 return getValue(Equiv->getGlobalValue()); 1892 1893 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1894 return getValue(NC->getGlobalValue()); 1895 1896 if (VT == MVT::aarch64svcount) { 1897 assert(C->isNullValue() && "Can only zero this target type!"); 1898 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1899 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1900 } 1901 1902 VectorType *VecTy = cast<VectorType>(V->getType()); 1903 1904 // Now that we know the number and type of the elements, get that number of 1905 // elements into the Ops array based on what kind of constant it is. 1906 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1907 SmallVector<SDValue, 16> Ops; 1908 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1909 for (unsigned i = 0; i != NumElements; ++i) 1910 Ops.push_back(getValue(CV->getOperand(i))); 1911 1912 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1913 } 1914 1915 if (isa<ConstantAggregateZero>(C)) { 1916 EVT EltVT = 1917 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1918 1919 SDValue Op; 1920 if (EltVT.isFloatingPoint()) 1921 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1922 else 1923 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1924 1925 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1926 } 1927 1928 llvm_unreachable("Unknown vector constant"); 1929 } 1930 1931 // If this is a static alloca, generate it as the frameindex instead of 1932 // computation. 1933 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1934 DenseMap<const AllocaInst*, int>::iterator SI = 1935 FuncInfo.StaticAllocaMap.find(AI); 1936 if (SI != FuncInfo.StaticAllocaMap.end()) 1937 return DAG.getFrameIndex( 1938 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1939 } 1940 1941 // If this is an instruction which fast-isel has deferred, select it now. 1942 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1943 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1944 1945 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1946 Inst->getType(), std::nullopt); 1947 SDValue Chain = DAG.getEntryNode(); 1948 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1949 } 1950 1951 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1952 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1953 1954 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1955 return DAG.getBasicBlock(FuncInfo.getMBB(BB)); 1956 1957 llvm_unreachable("Can't get register for value!"); 1958 } 1959 1960 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1961 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1962 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1963 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1964 bool IsSEH = isAsynchronousEHPersonality(Pers); 1965 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1966 if (!IsSEH) 1967 CatchPadMBB->setIsEHScopeEntry(); 1968 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1969 if (IsMSVCCXX || IsCoreCLR) 1970 CatchPadMBB->setIsEHFuncletEntry(); 1971 } 1972 1973 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1974 // Update machine-CFG edge. 1975 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor()); 1976 FuncInfo.MBB->addSuccessor(TargetMBB); 1977 TargetMBB->setIsEHCatchretTarget(true); 1978 DAG.getMachineFunction().setHasEHCatchret(true); 1979 1980 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1981 bool IsSEH = isAsynchronousEHPersonality(Pers); 1982 if (IsSEH) { 1983 // If this is not a fall-through branch or optimizations are switched off, 1984 // emit the branch. 1985 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1986 TM.getOptLevel() == CodeGenOptLevel::None) 1987 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1988 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1989 return; 1990 } 1991 1992 // Figure out the funclet membership for the catchret's successor. 1993 // This will be used by the FuncletLayout pass to determine how to order the 1994 // BB's. 1995 // A 'catchret' returns to the outer scope's color. 1996 Value *ParentPad = I.getCatchSwitchParentPad(); 1997 const BasicBlock *SuccessorColor; 1998 if (isa<ConstantTokenNone>(ParentPad)) 1999 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 2000 else 2001 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 2002 assert(SuccessorColor && "No parent funclet for catchret!"); 2003 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor); 2004 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 2005 2006 // Create the terminator node. 2007 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 2008 getControlRoot(), DAG.getBasicBlock(TargetMBB), 2009 DAG.getBasicBlock(SuccessorColorMBB)); 2010 DAG.setRoot(Ret); 2011 } 2012 2013 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 2014 // Don't emit any special code for the cleanuppad instruction. It just marks 2015 // the start of an EH scope/funclet. 2016 FuncInfo.MBB->setIsEHScopeEntry(); 2017 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2018 if (Pers != EHPersonality::Wasm_CXX) { 2019 FuncInfo.MBB->setIsEHFuncletEntry(); 2020 FuncInfo.MBB->setIsCleanupFuncletEntry(); 2021 } 2022 } 2023 2024 // In wasm EH, even though a catchpad may not catch an exception if a tag does 2025 // not match, it is OK to add only the first unwind destination catchpad to the 2026 // successors, because there will be at least one invoke instruction within the 2027 // catch scope that points to the next unwind destination, if one exists, so 2028 // CFGSort cannot mess up with BB sorting order. 2029 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 2030 // call within them, and catchpads only consisting of 'catch (...)' have a 2031 // '__cxa_end_catch' call within them, both of which generate invokes in case 2032 // the next unwind destination exists, i.e., the next unwind destination is not 2033 // the caller.) 2034 // 2035 // Having at most one EH pad successor is also simpler and helps later 2036 // transformations. 2037 // 2038 // For example, 2039 // current: 2040 // invoke void @foo to ... unwind label %catch.dispatch 2041 // catch.dispatch: 2042 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2043 // catch.start: 2044 // ... 2045 // ... in this BB or some other child BB dominated by this BB there will be an 2046 // invoke that points to 'next' BB as an unwind destination 2047 // 2048 // next: ; We don't need to add this to 'current' BB's successor 2049 // ... 2050 static void findWasmUnwindDestinations( 2051 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2052 BranchProbability Prob, 2053 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2054 &UnwindDests) { 2055 while (EHPadBB) { 2056 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2057 if (isa<CleanupPadInst>(Pad)) { 2058 // Stop on cleanup pads. 2059 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2060 UnwindDests.back().first->setIsEHScopeEntry(); 2061 break; 2062 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2063 // Add the catchpad handlers to the possible destinations. We don't 2064 // continue to the unwind destination of the catchswitch for wasm. 2065 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2066 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob); 2067 UnwindDests.back().first->setIsEHScopeEntry(); 2068 } 2069 break; 2070 } else { 2071 continue; 2072 } 2073 } 2074 } 2075 2076 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2077 /// many places it could ultimately go. In the IR, we have a single unwind 2078 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2079 /// This function skips over imaginary basic blocks that hold catchswitch 2080 /// instructions, and finds all the "real" machine 2081 /// basic block destinations. As those destinations may not be successors of 2082 /// EHPadBB, here we also calculate the edge probability to those destinations. 2083 /// The passed-in Prob is the edge probability to EHPadBB. 2084 static void findUnwindDestinations( 2085 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2086 BranchProbability Prob, 2087 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2088 &UnwindDests) { 2089 EHPersonality Personality = 2090 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2091 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2092 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2093 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2094 bool IsSEH = isAsynchronousEHPersonality(Personality); 2095 2096 if (IsWasmCXX) { 2097 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2098 assert(UnwindDests.size() <= 1 && 2099 "There should be at most one unwind destination for wasm"); 2100 return; 2101 } 2102 2103 while (EHPadBB) { 2104 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2105 BasicBlock *NewEHPadBB = nullptr; 2106 if (isa<LandingPadInst>(Pad)) { 2107 // Stop on landingpads. They are not funclets. 2108 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2109 break; 2110 } else if (isa<CleanupPadInst>(Pad)) { 2111 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2112 // personalities. 2113 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2114 UnwindDests.back().first->setIsEHScopeEntry(); 2115 UnwindDests.back().first->setIsEHFuncletEntry(); 2116 break; 2117 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2118 // Add the catchpad handlers to the possible destinations. 2119 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2120 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob); 2121 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2122 if (IsMSVCCXX || IsCoreCLR) 2123 UnwindDests.back().first->setIsEHFuncletEntry(); 2124 if (!IsSEH) 2125 UnwindDests.back().first->setIsEHScopeEntry(); 2126 } 2127 NewEHPadBB = CatchSwitch->getUnwindDest(); 2128 } else { 2129 continue; 2130 } 2131 2132 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2133 if (BPI && NewEHPadBB) 2134 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2135 EHPadBB = NewEHPadBB; 2136 } 2137 } 2138 2139 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2140 // Update successor info. 2141 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2142 auto UnwindDest = I.getUnwindDest(); 2143 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2144 BranchProbability UnwindDestProb = 2145 (BPI && UnwindDest) 2146 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2147 : BranchProbability::getZero(); 2148 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2149 for (auto &UnwindDest : UnwindDests) { 2150 UnwindDest.first->setIsEHPad(); 2151 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2152 } 2153 FuncInfo.MBB->normalizeSuccProbs(); 2154 2155 // Create the terminator node. 2156 SDValue Ret = 2157 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2158 DAG.setRoot(Ret); 2159 } 2160 2161 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2162 report_fatal_error("visitCatchSwitch not yet implemented!"); 2163 } 2164 2165 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2166 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2167 auto &DL = DAG.getDataLayout(); 2168 SDValue Chain = getControlRoot(); 2169 SmallVector<ISD::OutputArg, 8> Outs; 2170 SmallVector<SDValue, 8> OutVals; 2171 2172 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2173 // lower 2174 // 2175 // %val = call <ty> @llvm.experimental.deoptimize() 2176 // ret <ty> %val 2177 // 2178 // differently. 2179 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2180 LowerDeoptimizingReturn(); 2181 return; 2182 } 2183 2184 if (!FuncInfo.CanLowerReturn) { 2185 unsigned DemoteReg = FuncInfo.DemoteRegister; 2186 const Function *F = I.getParent()->getParent(); 2187 2188 // Emit a store of the return value through the virtual register. 2189 // Leave Outs empty so that LowerReturn won't try to load return 2190 // registers the usual way. 2191 SmallVector<EVT, 1> PtrValueVTs; 2192 ComputeValueVTs(TLI, DL, 2193 PointerType::get(F->getContext(), 2194 DAG.getDataLayout().getAllocaAddrSpace()), 2195 PtrValueVTs); 2196 2197 SDValue RetPtr = 2198 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2199 SDValue RetOp = getValue(I.getOperand(0)); 2200 2201 SmallVector<EVT, 4> ValueVTs, MemVTs; 2202 SmallVector<uint64_t, 4> Offsets; 2203 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2204 &Offsets, 0); 2205 unsigned NumValues = ValueVTs.size(); 2206 2207 SmallVector<SDValue, 4> Chains(NumValues); 2208 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2209 for (unsigned i = 0; i != NumValues; ++i) { 2210 // An aggregate return value cannot wrap around the address space, so 2211 // offsets to its parts don't wrap either. 2212 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2213 TypeSize::getFixed(Offsets[i])); 2214 2215 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2216 if (MemVTs[i] != ValueVTs[i]) 2217 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2218 Chains[i] = DAG.getStore( 2219 Chain, getCurSDLoc(), Val, 2220 // FIXME: better loc info would be nice. 2221 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2222 commonAlignment(BaseAlign, Offsets[i])); 2223 } 2224 2225 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2226 MVT::Other, Chains); 2227 } else if (I.getNumOperands() != 0) { 2228 SmallVector<EVT, 4> ValueVTs; 2229 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2230 unsigned NumValues = ValueVTs.size(); 2231 if (NumValues) { 2232 SDValue RetOp = getValue(I.getOperand(0)); 2233 2234 const Function *F = I.getParent()->getParent(); 2235 2236 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2237 I.getOperand(0)->getType(), F->getCallingConv(), 2238 /*IsVarArg*/ false, DL); 2239 2240 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2241 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2242 ExtendKind = ISD::SIGN_EXTEND; 2243 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2244 ExtendKind = ISD::ZERO_EXTEND; 2245 2246 LLVMContext &Context = F->getContext(); 2247 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2248 2249 for (unsigned j = 0; j != NumValues; ++j) { 2250 EVT VT = ValueVTs[j]; 2251 2252 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2253 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2254 2255 CallingConv::ID CC = F->getCallingConv(); 2256 2257 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2258 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2259 SmallVector<SDValue, 4> Parts(NumParts); 2260 getCopyToParts(DAG, getCurSDLoc(), 2261 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2262 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2263 2264 // 'inreg' on function refers to return value 2265 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2266 if (RetInReg) 2267 Flags.setInReg(); 2268 2269 if (I.getOperand(0)->getType()->isPointerTy()) { 2270 Flags.setPointer(); 2271 Flags.setPointerAddrSpace( 2272 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2273 } 2274 2275 if (NeedsRegBlock) { 2276 Flags.setInConsecutiveRegs(); 2277 if (j == NumValues - 1) 2278 Flags.setInConsecutiveRegsLast(); 2279 } 2280 2281 // Propagate extension type if any 2282 if (ExtendKind == ISD::SIGN_EXTEND) 2283 Flags.setSExt(); 2284 else if (ExtendKind == ISD::ZERO_EXTEND) 2285 Flags.setZExt(); 2286 2287 for (unsigned i = 0; i < NumParts; ++i) { 2288 Outs.push_back(ISD::OutputArg(Flags, 2289 Parts[i].getValueType().getSimpleVT(), 2290 VT, /*isfixed=*/true, 0, 0)); 2291 OutVals.push_back(Parts[i]); 2292 } 2293 } 2294 } 2295 } 2296 2297 // Push in swifterror virtual register as the last element of Outs. This makes 2298 // sure swifterror virtual register will be returned in the swifterror 2299 // physical register. 2300 const Function *F = I.getParent()->getParent(); 2301 if (TLI.supportSwiftError() && 2302 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2303 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2304 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2305 Flags.setSwiftError(); 2306 Outs.push_back(ISD::OutputArg( 2307 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2308 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2309 // Create SDNode for the swifterror virtual register. 2310 OutVals.push_back( 2311 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2312 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2313 EVT(TLI.getPointerTy(DL)))); 2314 } 2315 2316 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2317 CallingConv::ID CallConv = 2318 DAG.getMachineFunction().getFunction().getCallingConv(); 2319 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2320 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2321 2322 // Verify that the target's LowerReturn behaved as expected. 2323 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2324 "LowerReturn didn't return a valid chain!"); 2325 2326 // Update the DAG with the new chain value resulting from return lowering. 2327 DAG.setRoot(Chain); 2328 } 2329 2330 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2331 /// created for it, emit nodes to copy the value into the virtual 2332 /// registers. 2333 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2334 // Skip empty types 2335 if (V->getType()->isEmptyTy()) 2336 return; 2337 2338 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2339 if (VMI != FuncInfo.ValueMap.end()) { 2340 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2341 "Unused value assigned virtual registers!"); 2342 CopyValueToVirtualRegister(V, VMI->second); 2343 } 2344 } 2345 2346 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2347 /// the current basic block, add it to ValueMap now so that we'll get a 2348 /// CopyTo/FromReg. 2349 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2350 // No need to export constants. 2351 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2352 2353 // Already exported? 2354 if (FuncInfo.isExportedInst(V)) return; 2355 2356 Register Reg = FuncInfo.InitializeRegForValue(V); 2357 CopyValueToVirtualRegister(V, Reg); 2358 } 2359 2360 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2361 const BasicBlock *FromBB) { 2362 // The operands of the setcc have to be in this block. We don't know 2363 // how to export them from some other block. 2364 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2365 // Can export from current BB. 2366 if (VI->getParent() == FromBB) 2367 return true; 2368 2369 // Is already exported, noop. 2370 return FuncInfo.isExportedInst(V); 2371 } 2372 2373 // If this is an argument, we can export it if the BB is the entry block or 2374 // if it is already exported. 2375 if (isa<Argument>(V)) { 2376 if (FromBB->isEntryBlock()) 2377 return true; 2378 2379 // Otherwise, can only export this if it is already exported. 2380 return FuncInfo.isExportedInst(V); 2381 } 2382 2383 // Otherwise, constants can always be exported. 2384 return true; 2385 } 2386 2387 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2388 BranchProbability 2389 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2390 const MachineBasicBlock *Dst) const { 2391 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2392 const BasicBlock *SrcBB = Src->getBasicBlock(); 2393 const BasicBlock *DstBB = Dst->getBasicBlock(); 2394 if (!BPI) { 2395 // If BPI is not available, set the default probability as 1 / N, where N is 2396 // the number of successors. 2397 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2398 return BranchProbability(1, SuccSize); 2399 } 2400 return BPI->getEdgeProbability(SrcBB, DstBB); 2401 } 2402 2403 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2404 MachineBasicBlock *Dst, 2405 BranchProbability Prob) { 2406 if (!FuncInfo.BPI) 2407 Src->addSuccessorWithoutProb(Dst); 2408 else { 2409 if (Prob.isUnknown()) 2410 Prob = getEdgeProbability(Src, Dst); 2411 Src->addSuccessor(Dst, Prob); 2412 } 2413 } 2414 2415 static bool InBlock(const Value *V, const BasicBlock *BB) { 2416 if (const Instruction *I = dyn_cast<Instruction>(V)) 2417 return I->getParent() == BB; 2418 return true; 2419 } 2420 2421 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2422 /// This function emits a branch and is used at the leaves of an OR or an 2423 /// AND operator tree. 2424 void 2425 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2426 MachineBasicBlock *TBB, 2427 MachineBasicBlock *FBB, 2428 MachineBasicBlock *CurBB, 2429 MachineBasicBlock *SwitchBB, 2430 BranchProbability TProb, 2431 BranchProbability FProb, 2432 bool InvertCond) { 2433 const BasicBlock *BB = CurBB->getBasicBlock(); 2434 2435 // If the leaf of the tree is a comparison, merge the condition into 2436 // the caseblock. 2437 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2438 // The operands of the cmp have to be in this block. We don't know 2439 // how to export them from some other block. If this is the first block 2440 // of the sequence, no exporting is needed. 2441 if (CurBB == SwitchBB || 2442 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2443 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2444 ISD::CondCode Condition; 2445 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2446 ICmpInst::Predicate Pred = 2447 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2448 Condition = getICmpCondCode(Pred); 2449 } else { 2450 const FCmpInst *FC = cast<FCmpInst>(Cond); 2451 FCmpInst::Predicate Pred = 2452 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2453 Condition = getFCmpCondCode(Pred); 2454 if (TM.Options.NoNaNsFPMath) 2455 Condition = getFCmpCodeWithoutNaN(Condition); 2456 } 2457 2458 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2459 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2460 SL->SwitchCases.push_back(CB); 2461 return; 2462 } 2463 } 2464 2465 // Create a CaseBlock record representing this branch. 2466 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2467 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2468 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2469 SL->SwitchCases.push_back(CB); 2470 } 2471 2472 // Collect dependencies on V recursively. This is used for the cost analysis in 2473 // `shouldKeepJumpConditionsTogether`. 2474 static bool collectInstructionDeps( 2475 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V, 2476 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr, 2477 unsigned Depth = 0) { 2478 // Return false if we have an incomplete count. 2479 if (Depth >= SelectionDAG::MaxRecursionDepth) 2480 return false; 2481 2482 auto *I = dyn_cast<Instruction>(V); 2483 if (I == nullptr) 2484 return true; 2485 2486 if (Necessary != nullptr) { 2487 // This instruction is necessary for the other side of the condition so 2488 // don't count it. 2489 if (Necessary->contains(I)) 2490 return true; 2491 } 2492 2493 // Already added this dep. 2494 if (!Deps->try_emplace(I, false).second) 2495 return true; 2496 2497 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx) 2498 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary, 2499 Depth + 1)) 2500 return false; 2501 return true; 2502 } 2503 2504 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether( 2505 const FunctionLoweringInfo &FuncInfo, const BranchInst &I, 2506 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, 2507 TargetLoweringBase::CondMergingParams Params) const { 2508 if (I.getNumSuccessors() != 2) 2509 return false; 2510 2511 if (!I.isConditional()) 2512 return false; 2513 2514 if (Params.BaseCost < 0) 2515 return false; 2516 2517 // Baseline cost. 2518 InstructionCost CostThresh = Params.BaseCost; 2519 2520 BranchProbabilityInfo *BPI = nullptr; 2521 if (Params.LikelyBias || Params.UnlikelyBias) 2522 BPI = FuncInfo.BPI; 2523 if (BPI != nullptr) { 2524 // See if we are either likely to get an early out or compute both lhs/rhs 2525 // of the condition. 2526 BasicBlock *IfFalse = I.getSuccessor(0); 2527 BasicBlock *IfTrue = I.getSuccessor(1); 2528 2529 std::optional<bool> Likely; 2530 if (BPI->isEdgeHot(I.getParent(), IfTrue)) 2531 Likely = true; 2532 else if (BPI->isEdgeHot(I.getParent(), IfFalse)) 2533 Likely = false; 2534 2535 if (Likely) { 2536 if (Opc == (*Likely ? Instruction::And : Instruction::Or)) 2537 // Its likely we will have to compute both lhs and rhs of condition 2538 CostThresh += Params.LikelyBias; 2539 else { 2540 if (Params.UnlikelyBias < 0) 2541 return false; 2542 // Its likely we will get an early out. 2543 CostThresh -= Params.UnlikelyBias; 2544 } 2545 } 2546 } 2547 2548 if (CostThresh <= 0) 2549 return false; 2550 2551 // Collect "all" instructions that lhs condition is dependent on. 2552 // Use map for stable iteration (to avoid non-determanism of iteration of 2553 // SmallPtrSet). The `bool` value is just a dummy. 2554 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps; 2555 collectInstructionDeps(&LhsDeps, Lhs); 2556 // Collect "all" instructions that rhs condition is dependent on AND are 2557 // dependencies of lhs. This gives us an estimate on which instructions we 2558 // stand to save by splitting the condition. 2559 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps)) 2560 return false; 2561 // Add the compare instruction itself unless its a dependency on the LHS. 2562 if (const auto *RhsI = dyn_cast<Instruction>(Rhs)) 2563 if (!LhsDeps.contains(RhsI)) 2564 RhsDeps.try_emplace(RhsI, false); 2565 2566 const auto &TLI = DAG.getTargetLoweringInfo(); 2567 const auto &TTI = 2568 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 2569 2570 InstructionCost CostOfIncluding = 0; 2571 // See if this instruction will need to computed independently of whether RHS 2572 // is. 2573 Value *BrCond = I.getCondition(); 2574 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) { 2575 for (const auto *U : Ins->users()) { 2576 // If user is independent of RHS calculation we don't need to count it. 2577 if (auto *UIns = dyn_cast<Instruction>(U)) 2578 if (UIns != BrCond && !RhsDeps.contains(UIns)) 2579 return false; 2580 } 2581 return true; 2582 }; 2583 2584 // Prune instructions from RHS Deps that are dependencies of unrelated 2585 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly 2586 // arbitrary and just meant to cap the how much time we spend in the pruning 2587 // loop. Its highly unlikely to come into affect. 2588 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth; 2589 // Stop after a certain point. No incorrectness from including too many 2590 // instructions. 2591 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) { 2592 const Instruction *ToDrop = nullptr; 2593 for (const auto &InsPair : RhsDeps) { 2594 if (!ShouldCountInsn(InsPair.first)) { 2595 ToDrop = InsPair.first; 2596 break; 2597 } 2598 } 2599 if (ToDrop == nullptr) 2600 break; 2601 RhsDeps.erase(ToDrop); 2602 } 2603 2604 for (const auto &InsPair : RhsDeps) { 2605 // Finally accumulate latency that we can only attribute to computing the 2606 // RHS condition. Use latency because we are essentially trying to calculate 2607 // the cost of the dependency chain. 2608 // Possible TODO: We could try to estimate ILP and make this more precise. 2609 CostOfIncluding += 2610 TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency); 2611 2612 if (CostOfIncluding > CostThresh) 2613 return false; 2614 } 2615 return true; 2616 } 2617 2618 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2619 MachineBasicBlock *TBB, 2620 MachineBasicBlock *FBB, 2621 MachineBasicBlock *CurBB, 2622 MachineBasicBlock *SwitchBB, 2623 Instruction::BinaryOps Opc, 2624 BranchProbability TProb, 2625 BranchProbability FProb, 2626 bool InvertCond) { 2627 // Skip over not part of the tree and remember to invert op and operands at 2628 // next level. 2629 Value *NotCond; 2630 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2631 InBlock(NotCond, CurBB->getBasicBlock())) { 2632 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2633 !InvertCond); 2634 return; 2635 } 2636 2637 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2638 const Value *BOpOp0, *BOpOp1; 2639 // Compute the effective opcode for Cond, taking into account whether it needs 2640 // to be inverted, e.g. 2641 // and (not (or A, B)), C 2642 // gets lowered as 2643 // and (and (not A, not B), C) 2644 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2645 if (BOp) { 2646 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2647 ? Instruction::And 2648 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2649 ? Instruction::Or 2650 : (Instruction::BinaryOps)0); 2651 if (InvertCond) { 2652 if (BOpc == Instruction::And) 2653 BOpc = Instruction::Or; 2654 else if (BOpc == Instruction::Or) 2655 BOpc = Instruction::And; 2656 } 2657 } 2658 2659 // If this node is not part of the or/and tree, emit it as a branch. 2660 // Note that all nodes in the tree should have same opcode. 2661 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2662 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2663 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2664 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2665 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2666 TProb, FProb, InvertCond); 2667 return; 2668 } 2669 2670 // Create TmpBB after CurBB. 2671 MachineFunction::iterator BBI(CurBB); 2672 MachineFunction &MF = DAG.getMachineFunction(); 2673 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2674 CurBB->getParent()->insert(++BBI, TmpBB); 2675 2676 if (Opc == Instruction::Or) { 2677 // Codegen X | Y as: 2678 // BB1: 2679 // jmp_if_X TBB 2680 // jmp TmpBB 2681 // TmpBB: 2682 // jmp_if_Y TBB 2683 // jmp FBB 2684 // 2685 2686 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2687 // The requirement is that 2688 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2689 // = TrueProb for original BB. 2690 // Assuming the original probabilities are A and B, one choice is to set 2691 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2692 // A/(1+B) and 2B/(1+B). This choice assumes that 2693 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2694 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2695 // TmpBB, but the math is more complicated. 2696 2697 auto NewTrueProb = TProb / 2; 2698 auto NewFalseProb = TProb / 2 + FProb; 2699 // Emit the LHS condition. 2700 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2701 NewFalseProb, InvertCond); 2702 2703 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2704 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2705 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2706 // Emit the RHS condition into TmpBB. 2707 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2708 Probs[1], InvertCond); 2709 } else { 2710 assert(Opc == Instruction::And && "Unknown merge op!"); 2711 // Codegen X & Y as: 2712 // BB1: 2713 // jmp_if_X TmpBB 2714 // jmp FBB 2715 // TmpBB: 2716 // jmp_if_Y TBB 2717 // jmp FBB 2718 // 2719 // This requires creation of TmpBB after CurBB. 2720 2721 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2722 // The requirement is that 2723 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2724 // = FalseProb for original BB. 2725 // Assuming the original probabilities are A and B, one choice is to set 2726 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2727 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2728 // TrueProb for BB1 * FalseProb for TmpBB. 2729 2730 auto NewTrueProb = TProb + FProb / 2; 2731 auto NewFalseProb = FProb / 2; 2732 // Emit the LHS condition. 2733 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2734 NewFalseProb, InvertCond); 2735 2736 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2737 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2738 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2739 // Emit the RHS condition into TmpBB. 2740 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2741 Probs[1], InvertCond); 2742 } 2743 } 2744 2745 /// If the set of cases should be emitted as a series of branches, return true. 2746 /// If we should emit this as a bunch of and/or'd together conditions, return 2747 /// false. 2748 bool 2749 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2750 if (Cases.size() != 2) return true; 2751 2752 // If this is two comparisons of the same values or'd or and'd together, they 2753 // will get folded into a single comparison, so don't emit two blocks. 2754 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2755 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2756 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2757 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2758 return false; 2759 } 2760 2761 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2762 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2763 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2764 Cases[0].CC == Cases[1].CC && 2765 isa<Constant>(Cases[0].CmpRHS) && 2766 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2767 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2768 return false; 2769 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2770 return false; 2771 } 2772 2773 return true; 2774 } 2775 2776 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2777 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2778 2779 // Update machine-CFG edges. 2780 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0)); 2781 2782 if (I.isUnconditional()) { 2783 // Update machine-CFG edges. 2784 BrMBB->addSuccessor(Succ0MBB); 2785 2786 // If this is not a fall-through branch or optimizations are switched off, 2787 // emit the branch. 2788 if (Succ0MBB != NextBlock(BrMBB) || 2789 TM.getOptLevel() == CodeGenOptLevel::None) { 2790 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2791 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2792 setValue(&I, Br); 2793 DAG.setRoot(Br); 2794 } 2795 2796 return; 2797 } 2798 2799 // If this condition is one of the special cases we handle, do special stuff 2800 // now. 2801 const Value *CondVal = I.getCondition(); 2802 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1)); 2803 2804 // If this is a series of conditions that are or'd or and'd together, emit 2805 // this as a sequence of branches instead of setcc's with and/or operations. 2806 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2807 // unpredictable branches, and vector extracts because those jumps are likely 2808 // expensive for any target), this should improve performance. 2809 // For example, instead of something like: 2810 // cmp A, B 2811 // C = seteq 2812 // cmp D, E 2813 // F = setle 2814 // or C, F 2815 // jnz foo 2816 // Emit: 2817 // cmp A, B 2818 // je foo 2819 // cmp D, E 2820 // jle foo 2821 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2822 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2823 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2824 Value *Vec; 2825 const Value *BOp0, *BOp1; 2826 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2827 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2828 Opcode = Instruction::And; 2829 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2830 Opcode = Instruction::Or; 2831 2832 if (Opcode && 2833 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2834 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) && 2835 !shouldKeepJumpConditionsTogether( 2836 FuncInfo, I, Opcode, BOp0, BOp1, 2837 DAG.getTargetLoweringInfo().getJumpConditionMergingParams( 2838 Opcode, BOp0, BOp1))) { 2839 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2840 getEdgeProbability(BrMBB, Succ0MBB), 2841 getEdgeProbability(BrMBB, Succ1MBB), 2842 /*InvertCond=*/false); 2843 // If the compares in later blocks need to use values not currently 2844 // exported from this block, export them now. This block should always 2845 // be the first entry. 2846 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2847 2848 // Allow some cases to be rejected. 2849 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2850 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2851 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2852 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2853 } 2854 2855 // Emit the branch for this block. 2856 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2857 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2858 return; 2859 } 2860 2861 // Okay, we decided not to do this, remove any inserted MBB's and clear 2862 // SwitchCases. 2863 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2864 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2865 2866 SL->SwitchCases.clear(); 2867 } 2868 } 2869 2870 // Create a CaseBlock record representing this branch. 2871 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2872 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2873 2874 // Use visitSwitchCase to actually insert the fast branch sequence for this 2875 // cond branch. 2876 visitSwitchCase(CB, BrMBB); 2877 } 2878 2879 /// visitSwitchCase - Emits the necessary code to represent a single node in 2880 /// the binary search tree resulting from lowering a switch instruction. 2881 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2882 MachineBasicBlock *SwitchBB) { 2883 SDValue Cond; 2884 SDValue CondLHS = getValue(CB.CmpLHS); 2885 SDLoc dl = CB.DL; 2886 2887 if (CB.CC == ISD::SETTRUE) { 2888 // Branch or fall through to TrueBB. 2889 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2890 SwitchBB->normalizeSuccProbs(); 2891 if (CB.TrueBB != NextBlock(SwitchBB)) { 2892 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2893 DAG.getBasicBlock(CB.TrueBB))); 2894 } 2895 return; 2896 } 2897 2898 auto &TLI = DAG.getTargetLoweringInfo(); 2899 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2900 2901 // Build the setcc now. 2902 if (!CB.CmpMHS) { 2903 // Fold "(X == true)" to X and "(X == false)" to !X to 2904 // handle common cases produced by branch lowering. 2905 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2906 CB.CC == ISD::SETEQ) 2907 Cond = CondLHS; 2908 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2909 CB.CC == ISD::SETEQ) { 2910 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2911 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2912 } else { 2913 SDValue CondRHS = getValue(CB.CmpRHS); 2914 2915 // If a pointer's DAG type is larger than its memory type then the DAG 2916 // values are zero-extended. This breaks signed comparisons so truncate 2917 // back to the underlying type before doing the compare. 2918 if (CondLHS.getValueType() != MemVT) { 2919 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2920 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2921 } 2922 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2923 } 2924 } else { 2925 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2926 2927 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2928 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2929 2930 SDValue CmpOp = getValue(CB.CmpMHS); 2931 EVT VT = CmpOp.getValueType(); 2932 2933 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2934 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2935 ISD::SETLE); 2936 } else { 2937 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2938 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2939 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2940 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2941 } 2942 } 2943 2944 // Update successor info 2945 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2946 // TrueBB and FalseBB are always different unless the incoming IR is 2947 // degenerate. This only happens when running llc on weird IR. 2948 if (CB.TrueBB != CB.FalseBB) 2949 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2950 SwitchBB->normalizeSuccProbs(); 2951 2952 // If the lhs block is the next block, invert the condition so that we can 2953 // fall through to the lhs instead of the rhs block. 2954 if (CB.TrueBB == NextBlock(SwitchBB)) { 2955 std::swap(CB.TrueBB, CB.FalseBB); 2956 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2957 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2958 } 2959 2960 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2961 MVT::Other, getControlRoot(), Cond, 2962 DAG.getBasicBlock(CB.TrueBB)); 2963 2964 setValue(CurInst, BrCond); 2965 2966 // Insert the false branch. Do this even if it's a fall through branch, 2967 // this makes it easier to do DAG optimizations which require inverting 2968 // the branch condition. 2969 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2970 DAG.getBasicBlock(CB.FalseBB)); 2971 2972 DAG.setRoot(BrCond); 2973 } 2974 2975 /// visitJumpTable - Emit JumpTable node in the current MBB 2976 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2977 // Emit the code for the jump table 2978 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2979 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2980 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout()); 2981 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2982 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2983 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2984 Index.getValue(1), Table, Index); 2985 DAG.setRoot(BrJumpTable); 2986 } 2987 2988 /// visitJumpTableHeader - This function emits necessary code to produce index 2989 /// in the JumpTable from switch case. 2990 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2991 JumpTableHeader &JTH, 2992 MachineBasicBlock *SwitchBB) { 2993 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2994 const SDLoc &dl = *JT.SL; 2995 2996 // Subtract the lowest switch case value from the value being switched on. 2997 SDValue SwitchOp = getValue(JTH.SValue); 2998 EVT VT = SwitchOp.getValueType(); 2999 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 3000 DAG.getConstant(JTH.First, dl, VT)); 3001 3002 // The SDNode we just created, which holds the value being switched on minus 3003 // the smallest case value, needs to be copied to a virtual register so it 3004 // can be used as an index into the jump table in a subsequent basic block. 3005 // This value may be smaller or larger than the target's pointer type, and 3006 // therefore require extension or truncating. 3007 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3008 SwitchOp = 3009 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout())); 3010 3011 unsigned JumpTableReg = 3012 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout())); 3013 SDValue CopyTo = 3014 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp); 3015 JT.Reg = JumpTableReg; 3016 3017 if (!JTH.FallthroughUnreachable) { 3018 // Emit the range check for the jump table, and branch to the default block 3019 // for the switch statement if the value being switched on exceeds the 3020 // largest case in the switch. 3021 SDValue CMP = DAG.getSetCC( 3022 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3023 Sub.getValueType()), 3024 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 3025 3026 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3027 MVT::Other, CopyTo, CMP, 3028 DAG.getBasicBlock(JT.Default)); 3029 3030 // Avoid emitting unnecessary branches to the next block. 3031 if (JT.MBB != NextBlock(SwitchBB)) 3032 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 3033 DAG.getBasicBlock(JT.MBB)); 3034 3035 DAG.setRoot(BrCond); 3036 } else { 3037 // Avoid emitting unnecessary branches to the next block. 3038 if (JT.MBB != NextBlock(SwitchBB)) 3039 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 3040 DAG.getBasicBlock(JT.MBB))); 3041 else 3042 DAG.setRoot(CopyTo); 3043 } 3044 } 3045 3046 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 3047 /// variable if there exists one. 3048 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 3049 SDValue &Chain) { 3050 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3051 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3052 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3053 MachineFunction &MF = DAG.getMachineFunction(); 3054 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 3055 MachineSDNode *Node = 3056 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 3057 if (Global) { 3058 MachinePointerInfo MPInfo(Global); 3059 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 3060 MachineMemOperand::MODereferenceable; 3061 MachineMemOperand *MemRef = MF.getMachineMemOperand( 3062 MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8), 3063 DAG.getEVTAlign(PtrTy)); 3064 DAG.setNodeMemRefs(Node, {MemRef}); 3065 } 3066 if (PtrTy != PtrMemTy) 3067 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 3068 return SDValue(Node, 0); 3069 } 3070 3071 /// Codegen a new tail for a stack protector check ParentMBB which has had its 3072 /// tail spliced into a stack protector check success bb. 3073 /// 3074 /// For a high level explanation of how this fits into the stack protector 3075 /// generation see the comment on the declaration of class 3076 /// StackProtectorDescriptor. 3077 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 3078 MachineBasicBlock *ParentBB) { 3079 3080 // First create the loads to the guard/stack slot for the comparison. 3081 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3082 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3083 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3084 3085 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 3086 int FI = MFI.getStackProtectorIndex(); 3087 3088 SDValue Guard; 3089 SDLoc dl = getCurSDLoc(); 3090 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 3091 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 3092 Align Align = 3093 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 3094 3095 // Generate code to load the content of the guard slot. 3096 SDValue GuardVal = DAG.getLoad( 3097 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 3098 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 3099 MachineMemOperand::MOVolatile); 3100 3101 if (TLI.useStackGuardXorFP()) 3102 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 3103 3104 // Retrieve guard check function, nullptr if instrumentation is inlined. 3105 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 3106 // The target provides a guard check function to validate the guard value. 3107 // Generate a call to that function with the content of the guard slot as 3108 // argument. 3109 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 3110 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 3111 3112 TargetLowering::ArgListTy Args; 3113 TargetLowering::ArgListEntry Entry; 3114 Entry.Node = GuardVal; 3115 Entry.Ty = FnTy->getParamType(0); 3116 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 3117 Entry.IsInReg = true; 3118 Args.push_back(Entry); 3119 3120 TargetLowering::CallLoweringInfo CLI(DAG); 3121 CLI.setDebugLoc(getCurSDLoc()) 3122 .setChain(DAG.getEntryNode()) 3123 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 3124 getValue(GuardCheckFn), std::move(Args)); 3125 3126 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 3127 DAG.setRoot(Result.second); 3128 return; 3129 } 3130 3131 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 3132 // Otherwise, emit a volatile load to retrieve the stack guard value. 3133 SDValue Chain = DAG.getEntryNode(); 3134 if (TLI.useLoadStackGuardNode()) { 3135 Guard = getLoadStackGuard(DAG, dl, Chain); 3136 } else { 3137 const Value *IRGuard = TLI.getSDagStackGuard(M); 3138 SDValue GuardPtr = getValue(IRGuard); 3139 3140 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 3141 MachinePointerInfo(IRGuard, 0), Align, 3142 MachineMemOperand::MOVolatile); 3143 } 3144 3145 // Perform the comparison via a getsetcc. 3146 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 3147 *DAG.getContext(), 3148 Guard.getValueType()), 3149 Guard, GuardVal, ISD::SETNE); 3150 3151 // If the guard/stackslot do not equal, branch to failure MBB. 3152 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3153 MVT::Other, GuardVal.getOperand(0), 3154 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 3155 // Otherwise branch to success MBB. 3156 SDValue Br = DAG.getNode(ISD::BR, dl, 3157 MVT::Other, BrCond, 3158 DAG.getBasicBlock(SPD.getSuccessMBB())); 3159 3160 DAG.setRoot(Br); 3161 } 3162 3163 /// Codegen the failure basic block for a stack protector check. 3164 /// 3165 /// A failure stack protector machine basic block consists simply of a call to 3166 /// __stack_chk_fail(). 3167 /// 3168 /// For a high level explanation of how this fits into the stack protector 3169 /// generation see the comment on the declaration of class 3170 /// StackProtectorDescriptor. 3171 void 3172 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 3173 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3174 TargetLowering::MakeLibCallOptions CallOptions; 3175 CallOptions.setDiscardResult(true); 3176 SDValue Chain = 3177 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 3178 std::nullopt, CallOptions, getCurSDLoc()) 3179 .second; 3180 // On PS4/PS5, the "return address" must still be within the calling 3181 // function, even if it's at the very end, so emit an explicit TRAP here. 3182 // Passing 'true' for doesNotReturn above won't generate the trap for us. 3183 if (TM.getTargetTriple().isPS()) 3184 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3185 // WebAssembly needs an unreachable instruction after a non-returning call, 3186 // because the function return type can be different from __stack_chk_fail's 3187 // return type (void). 3188 if (TM.getTargetTriple().isWasm()) 3189 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3190 3191 DAG.setRoot(Chain); 3192 } 3193 3194 /// visitBitTestHeader - This function emits necessary code to produce value 3195 /// suitable for "bit tests" 3196 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3197 MachineBasicBlock *SwitchBB) { 3198 SDLoc dl = getCurSDLoc(); 3199 3200 // Subtract the minimum value. 3201 SDValue SwitchOp = getValue(B.SValue); 3202 EVT VT = SwitchOp.getValueType(); 3203 SDValue RangeSub = 3204 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3205 3206 // Determine the type of the test operands. 3207 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3208 bool UsePtrType = false; 3209 if (!TLI.isTypeLegal(VT)) { 3210 UsePtrType = true; 3211 } else { 3212 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3213 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3214 // Switch table case range are encoded into series of masks. 3215 // Just use pointer type, it's guaranteed to fit. 3216 UsePtrType = true; 3217 break; 3218 } 3219 } 3220 SDValue Sub = RangeSub; 3221 if (UsePtrType) { 3222 VT = TLI.getPointerTy(DAG.getDataLayout()); 3223 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3224 } 3225 3226 B.RegVT = VT.getSimpleVT(); 3227 B.Reg = FuncInfo.CreateReg(B.RegVT); 3228 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3229 3230 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3231 3232 if (!B.FallthroughUnreachable) 3233 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3234 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3235 SwitchBB->normalizeSuccProbs(); 3236 3237 SDValue Root = CopyTo; 3238 if (!B.FallthroughUnreachable) { 3239 // Conditional branch to the default block. 3240 SDValue RangeCmp = DAG.getSetCC(dl, 3241 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3242 RangeSub.getValueType()), 3243 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3244 ISD::SETUGT); 3245 3246 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3247 DAG.getBasicBlock(B.Default)); 3248 } 3249 3250 // Avoid emitting unnecessary branches to the next block. 3251 if (MBB != NextBlock(SwitchBB)) 3252 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3253 3254 DAG.setRoot(Root); 3255 } 3256 3257 /// visitBitTestCase - this function produces one "bit test" 3258 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3259 MachineBasicBlock* NextMBB, 3260 BranchProbability BranchProbToNext, 3261 unsigned Reg, 3262 BitTestCase &B, 3263 MachineBasicBlock *SwitchBB) { 3264 SDLoc dl = getCurSDLoc(); 3265 MVT VT = BB.RegVT; 3266 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3267 SDValue Cmp; 3268 unsigned PopCount = llvm::popcount(B.Mask); 3269 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3270 if (PopCount == 1) { 3271 // Testing for a single bit; just compare the shift count with what it 3272 // would need to be to shift a 1 bit in that position. 3273 Cmp = DAG.getSetCC( 3274 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3275 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3276 ISD::SETEQ); 3277 } else if (PopCount == BB.Range) { 3278 // There is only one zero bit in the range, test for it directly. 3279 Cmp = DAG.getSetCC( 3280 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3281 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3282 } else { 3283 // Make desired shift 3284 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3285 DAG.getConstant(1, dl, VT), ShiftOp); 3286 3287 // Emit bit tests and jumps 3288 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3289 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3290 Cmp = DAG.getSetCC( 3291 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3292 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3293 } 3294 3295 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3296 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3297 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3298 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3299 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3300 // one as they are relative probabilities (and thus work more like weights), 3301 // and hence we need to normalize them to let the sum of them become one. 3302 SwitchBB->normalizeSuccProbs(); 3303 3304 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3305 MVT::Other, getControlRoot(), 3306 Cmp, DAG.getBasicBlock(B.TargetBB)); 3307 3308 // Avoid emitting unnecessary branches to the next block. 3309 if (NextMBB != NextBlock(SwitchBB)) 3310 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3311 DAG.getBasicBlock(NextMBB)); 3312 3313 DAG.setRoot(BrAnd); 3314 } 3315 3316 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3317 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3318 3319 // Retrieve successors. Look through artificial IR level blocks like 3320 // catchswitch for successors. 3321 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0)); 3322 const BasicBlock *EHPadBB = I.getSuccessor(1); 3323 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB); 3324 3325 // Deopt and ptrauth bundles are lowered in helper functions, and we don't 3326 // have to do anything here to lower funclet bundles. 3327 assert(!I.hasOperandBundlesOtherThan( 3328 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3329 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3330 LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth, 3331 LLVMContext::OB_clang_arc_attachedcall}) && 3332 "Cannot lower invokes with arbitrary operand bundles yet!"); 3333 3334 const Value *Callee(I.getCalledOperand()); 3335 const Function *Fn = dyn_cast<Function>(Callee); 3336 if (isa<InlineAsm>(Callee)) 3337 visitInlineAsm(I, EHPadBB); 3338 else if (Fn && Fn->isIntrinsic()) { 3339 switch (Fn->getIntrinsicID()) { 3340 default: 3341 llvm_unreachable("Cannot invoke this intrinsic"); 3342 case Intrinsic::donothing: 3343 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3344 case Intrinsic::seh_try_begin: 3345 case Intrinsic::seh_scope_begin: 3346 case Intrinsic::seh_try_end: 3347 case Intrinsic::seh_scope_end: 3348 if (EHPadMBB) 3349 // a block referenced by EH table 3350 // so dtor-funclet not removed by opts 3351 EHPadMBB->setMachineBlockAddressTaken(); 3352 break; 3353 case Intrinsic::experimental_patchpoint_void: 3354 case Intrinsic::experimental_patchpoint: 3355 visitPatchpoint(I, EHPadBB); 3356 break; 3357 case Intrinsic::experimental_gc_statepoint: 3358 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3359 break; 3360 case Intrinsic::wasm_rethrow: { 3361 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3362 // special because it can be invoked, so we manually lower it to a DAG 3363 // node here. 3364 SmallVector<SDValue, 8> Ops; 3365 Ops.push_back(getControlRoot()); // inchain for the terminator node 3366 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3367 Ops.push_back( 3368 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3369 TLI.getPointerTy(DAG.getDataLayout()))); 3370 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3371 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3372 break; 3373 } 3374 } 3375 } else if (I.hasDeoptState()) { 3376 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3377 // Eventually we will support lowering the @llvm.experimental.deoptimize 3378 // intrinsic, and right now there are no plans to support other intrinsics 3379 // with deopt state. 3380 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3381 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 3382 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB); 3383 } else { 3384 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3385 } 3386 3387 // If the value of the invoke is used outside of its defining block, make it 3388 // available as a virtual register. 3389 // We already took care of the exported value for the statepoint instruction 3390 // during call to the LowerStatepoint. 3391 if (!isa<GCStatepointInst>(I)) { 3392 CopyToExportRegsIfNeeded(&I); 3393 } 3394 3395 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3396 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3397 BranchProbability EHPadBBProb = 3398 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3399 : BranchProbability::getZero(); 3400 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3401 3402 // Update successor info. 3403 addSuccessorWithProb(InvokeMBB, Return); 3404 for (auto &UnwindDest : UnwindDests) { 3405 UnwindDest.first->setIsEHPad(); 3406 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3407 } 3408 InvokeMBB->normalizeSuccProbs(); 3409 3410 // Drop into normal successor. 3411 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3412 DAG.getBasicBlock(Return))); 3413 } 3414 3415 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3416 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3417 3418 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3419 // have to do anything here to lower funclet bundles. 3420 assert(!I.hasOperandBundlesOtherThan( 3421 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3422 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3423 3424 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3425 visitInlineAsm(I); 3426 CopyToExportRegsIfNeeded(&I); 3427 3428 // Retrieve successors. 3429 SmallPtrSet<BasicBlock *, 8> Dests; 3430 Dests.insert(I.getDefaultDest()); 3431 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest()); 3432 3433 // Update successor info. 3434 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3435 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3436 BasicBlock *Dest = I.getIndirectDest(i); 3437 MachineBasicBlock *Target = FuncInfo.getMBB(Dest); 3438 Target->setIsInlineAsmBrIndirectTarget(); 3439 Target->setMachineBlockAddressTaken(); 3440 Target->setLabelMustBeEmitted(); 3441 // Don't add duplicate machine successors. 3442 if (Dests.insert(Dest).second) 3443 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3444 } 3445 CallBrMBB->normalizeSuccProbs(); 3446 3447 // Drop into default successor. 3448 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3449 MVT::Other, getControlRoot(), 3450 DAG.getBasicBlock(Return))); 3451 } 3452 3453 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3454 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3455 } 3456 3457 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3458 assert(FuncInfo.MBB->isEHPad() && 3459 "Call to landingpad not in landing pad!"); 3460 3461 // If there aren't registers to copy the values into (e.g., during SjLj 3462 // exceptions), then don't bother to create these DAG nodes. 3463 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3464 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3465 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3466 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3467 return; 3468 3469 // If landingpad's return type is token type, we don't create DAG nodes 3470 // for its exception pointer and selector value. The extraction of exception 3471 // pointer or selector value from token type landingpads is not currently 3472 // supported. 3473 if (LP.getType()->isTokenTy()) 3474 return; 3475 3476 SmallVector<EVT, 2> ValueVTs; 3477 SDLoc dl = getCurSDLoc(); 3478 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3479 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3480 3481 // Get the two live-in registers as SDValues. The physregs have already been 3482 // copied into virtual registers. 3483 SDValue Ops[2]; 3484 if (FuncInfo.ExceptionPointerVirtReg) { 3485 Ops[0] = DAG.getZExtOrTrunc( 3486 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3487 FuncInfo.ExceptionPointerVirtReg, 3488 TLI.getPointerTy(DAG.getDataLayout())), 3489 dl, ValueVTs[0]); 3490 } else { 3491 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3492 } 3493 Ops[1] = DAG.getZExtOrTrunc( 3494 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3495 FuncInfo.ExceptionSelectorVirtReg, 3496 TLI.getPointerTy(DAG.getDataLayout())), 3497 dl, ValueVTs[1]); 3498 3499 // Merge into one. 3500 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3501 DAG.getVTList(ValueVTs), Ops); 3502 setValue(&LP, Res); 3503 } 3504 3505 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3506 MachineBasicBlock *Last) { 3507 // Update JTCases. 3508 for (JumpTableBlock &JTB : SL->JTCases) 3509 if (JTB.first.HeaderBB == First) 3510 JTB.first.HeaderBB = Last; 3511 3512 // Update BitTestCases. 3513 for (BitTestBlock &BTB : SL->BitTestCases) 3514 if (BTB.Parent == First) 3515 BTB.Parent = Last; 3516 } 3517 3518 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3519 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3520 3521 // Update machine-CFG edges with unique successors. 3522 SmallSet<BasicBlock*, 32> Done; 3523 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3524 BasicBlock *BB = I.getSuccessor(i); 3525 bool Inserted = Done.insert(BB).second; 3526 if (!Inserted) 3527 continue; 3528 3529 MachineBasicBlock *Succ = FuncInfo.getMBB(BB); 3530 addSuccessorWithProb(IndirectBrMBB, Succ); 3531 } 3532 IndirectBrMBB->normalizeSuccProbs(); 3533 3534 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3535 MVT::Other, getControlRoot(), 3536 getValue(I.getAddress()))); 3537 } 3538 3539 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3540 if (!DAG.getTarget().Options.TrapUnreachable) 3541 return; 3542 3543 // We may be able to ignore unreachable behind a noreturn call. 3544 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode()); 3545 Call && Call->doesNotReturn()) { 3546 if (DAG.getTarget().Options.NoTrapAfterNoreturn) 3547 return; 3548 // Do not emit an additional trap instruction. 3549 if (Call->isNonContinuableTrap()) 3550 return; 3551 } 3552 3553 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3554 } 3555 3556 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3557 SDNodeFlags Flags; 3558 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3559 Flags.copyFMF(*FPOp); 3560 3561 SDValue Op = getValue(I.getOperand(0)); 3562 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3563 Op, Flags); 3564 setValue(&I, UnNodeValue); 3565 } 3566 3567 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3568 SDNodeFlags Flags; 3569 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3570 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3571 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3572 } 3573 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3574 Flags.setExact(ExactOp->isExact()); 3575 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3576 Flags.setDisjoint(DisjointOp->isDisjoint()); 3577 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3578 Flags.copyFMF(*FPOp); 3579 3580 SDValue Op1 = getValue(I.getOperand(0)); 3581 SDValue Op2 = getValue(I.getOperand(1)); 3582 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3583 Op1, Op2, Flags); 3584 setValue(&I, BinNodeValue); 3585 } 3586 3587 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3588 SDValue Op1 = getValue(I.getOperand(0)); 3589 SDValue Op2 = getValue(I.getOperand(1)); 3590 3591 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3592 Op1.getValueType(), DAG.getDataLayout()); 3593 3594 // Coerce the shift amount to the right type if we can. This exposes the 3595 // truncate or zext to optimization early. 3596 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3597 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3598 "Unexpected shift type"); 3599 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3600 } 3601 3602 bool nuw = false; 3603 bool nsw = false; 3604 bool exact = false; 3605 3606 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3607 3608 if (const OverflowingBinaryOperator *OFBinOp = 3609 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3610 nuw = OFBinOp->hasNoUnsignedWrap(); 3611 nsw = OFBinOp->hasNoSignedWrap(); 3612 } 3613 if (const PossiblyExactOperator *ExactOp = 3614 dyn_cast<const PossiblyExactOperator>(&I)) 3615 exact = ExactOp->isExact(); 3616 } 3617 SDNodeFlags Flags; 3618 Flags.setExact(exact); 3619 Flags.setNoSignedWrap(nsw); 3620 Flags.setNoUnsignedWrap(nuw); 3621 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3622 Flags); 3623 setValue(&I, Res); 3624 } 3625 3626 void SelectionDAGBuilder::visitSDiv(const User &I) { 3627 SDValue Op1 = getValue(I.getOperand(0)); 3628 SDValue Op2 = getValue(I.getOperand(1)); 3629 3630 SDNodeFlags Flags; 3631 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3632 cast<PossiblyExactOperator>(&I)->isExact()); 3633 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3634 Op2, Flags)); 3635 } 3636 3637 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) { 3638 ICmpInst::Predicate predicate = I.getPredicate(); 3639 SDValue Op1 = getValue(I.getOperand(0)); 3640 SDValue Op2 = getValue(I.getOperand(1)); 3641 ISD::CondCode Opcode = getICmpCondCode(predicate); 3642 3643 auto &TLI = DAG.getTargetLoweringInfo(); 3644 EVT MemVT = 3645 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3646 3647 // If a pointer's DAG type is larger than its memory type then the DAG values 3648 // are zero-extended. This breaks signed comparisons so truncate back to the 3649 // underlying type before doing the compare. 3650 if (Op1.getValueType() != MemVT) { 3651 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3652 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3653 } 3654 3655 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3656 I.getType()); 3657 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3658 } 3659 3660 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) { 3661 FCmpInst::Predicate predicate = I.getPredicate(); 3662 SDValue Op1 = getValue(I.getOperand(0)); 3663 SDValue Op2 = getValue(I.getOperand(1)); 3664 3665 ISD::CondCode Condition = getFCmpCondCode(predicate); 3666 auto *FPMO = cast<FPMathOperator>(&I); 3667 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3668 Condition = getFCmpCodeWithoutNaN(Condition); 3669 3670 SDNodeFlags Flags; 3671 Flags.copyFMF(*FPMO); 3672 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3673 3674 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3675 I.getType()); 3676 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3677 } 3678 3679 // Check if the condition of the select has one use or two users that are both 3680 // selects with the same condition. 3681 static bool hasOnlySelectUsers(const Value *Cond) { 3682 return llvm::all_of(Cond->users(), [](const Value *V) { 3683 return isa<SelectInst>(V); 3684 }); 3685 } 3686 3687 void SelectionDAGBuilder::visitSelect(const User &I) { 3688 SmallVector<EVT, 4> ValueVTs; 3689 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3690 ValueVTs); 3691 unsigned NumValues = ValueVTs.size(); 3692 if (NumValues == 0) return; 3693 3694 SmallVector<SDValue, 4> Values(NumValues); 3695 SDValue Cond = getValue(I.getOperand(0)); 3696 SDValue LHSVal = getValue(I.getOperand(1)); 3697 SDValue RHSVal = getValue(I.getOperand(2)); 3698 SmallVector<SDValue, 1> BaseOps(1, Cond); 3699 ISD::NodeType OpCode = 3700 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3701 3702 bool IsUnaryAbs = false; 3703 bool Negate = false; 3704 3705 SDNodeFlags Flags; 3706 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3707 Flags.copyFMF(*FPOp); 3708 3709 Flags.setUnpredictable( 3710 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3711 3712 // Min/max matching is only viable if all output VTs are the same. 3713 if (all_equal(ValueVTs)) { 3714 EVT VT = ValueVTs[0]; 3715 LLVMContext &Ctx = *DAG.getContext(); 3716 auto &TLI = DAG.getTargetLoweringInfo(); 3717 3718 // We care about the legality of the operation after it has been type 3719 // legalized. 3720 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3721 VT = TLI.getTypeToTransformTo(Ctx, VT); 3722 3723 // If the vselect is legal, assume we want to leave this as a vector setcc + 3724 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3725 // min/max is legal on the scalar type. 3726 bool UseScalarMinMax = VT.isVector() && 3727 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3728 3729 // ValueTracking's select pattern matching does not account for -0.0, 3730 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3731 // -0.0 is less than +0.0. 3732 const Value *LHS, *RHS; 3733 auto SPR = matchSelectPattern(&I, LHS, RHS); 3734 ISD::NodeType Opc = ISD::DELETED_NODE; 3735 switch (SPR.Flavor) { 3736 case SPF_UMAX: Opc = ISD::UMAX; break; 3737 case SPF_UMIN: Opc = ISD::UMIN; break; 3738 case SPF_SMAX: Opc = ISD::SMAX; break; 3739 case SPF_SMIN: Opc = ISD::SMIN; break; 3740 case SPF_FMINNUM: 3741 switch (SPR.NaNBehavior) { 3742 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3743 case SPNB_RETURNS_NAN: break; 3744 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3745 case SPNB_RETURNS_ANY: 3746 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3747 (UseScalarMinMax && 3748 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3749 Opc = ISD::FMINNUM; 3750 break; 3751 } 3752 break; 3753 case SPF_FMAXNUM: 3754 switch (SPR.NaNBehavior) { 3755 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3756 case SPNB_RETURNS_NAN: break; 3757 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3758 case SPNB_RETURNS_ANY: 3759 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3760 (UseScalarMinMax && 3761 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3762 Opc = ISD::FMAXNUM; 3763 break; 3764 } 3765 break; 3766 case SPF_NABS: 3767 Negate = true; 3768 [[fallthrough]]; 3769 case SPF_ABS: 3770 IsUnaryAbs = true; 3771 Opc = ISD::ABS; 3772 break; 3773 default: break; 3774 } 3775 3776 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3777 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3778 (UseScalarMinMax && 3779 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3780 // If the underlying comparison instruction is used by any other 3781 // instruction, the consumed instructions won't be destroyed, so it is 3782 // not profitable to convert to a min/max. 3783 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3784 OpCode = Opc; 3785 LHSVal = getValue(LHS); 3786 RHSVal = getValue(RHS); 3787 BaseOps.clear(); 3788 } 3789 3790 if (IsUnaryAbs) { 3791 OpCode = Opc; 3792 LHSVal = getValue(LHS); 3793 BaseOps.clear(); 3794 } 3795 } 3796 3797 if (IsUnaryAbs) { 3798 for (unsigned i = 0; i != NumValues; ++i) { 3799 SDLoc dl = getCurSDLoc(); 3800 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3801 Values[i] = 3802 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3803 if (Negate) 3804 Values[i] = DAG.getNegative(Values[i], dl, VT); 3805 } 3806 } else { 3807 for (unsigned i = 0; i != NumValues; ++i) { 3808 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3809 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3810 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3811 Values[i] = DAG.getNode( 3812 OpCode, getCurSDLoc(), 3813 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3814 } 3815 } 3816 3817 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3818 DAG.getVTList(ValueVTs), Values)); 3819 } 3820 3821 void SelectionDAGBuilder::visitTrunc(const User &I) { 3822 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3823 SDValue N = getValue(I.getOperand(0)); 3824 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3825 I.getType()); 3826 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3827 } 3828 3829 void SelectionDAGBuilder::visitZExt(const User &I) { 3830 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3831 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3832 SDValue N = getValue(I.getOperand(0)); 3833 auto &TLI = DAG.getTargetLoweringInfo(); 3834 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3835 3836 SDNodeFlags Flags; 3837 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3838 Flags.setNonNeg(PNI->hasNonNeg()); 3839 3840 // Eagerly use nonneg information to canonicalize towards sign_extend if 3841 // that is the target's preference. 3842 // TODO: Let the target do this later. 3843 if (Flags.hasNonNeg() && 3844 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3845 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3846 return; 3847 } 3848 3849 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3850 } 3851 3852 void SelectionDAGBuilder::visitSExt(const User &I) { 3853 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3854 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3855 SDValue N = getValue(I.getOperand(0)); 3856 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3857 I.getType()); 3858 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3859 } 3860 3861 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3862 // FPTrunc is never a no-op cast, no need to check 3863 SDValue N = getValue(I.getOperand(0)); 3864 SDLoc dl = getCurSDLoc(); 3865 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3866 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3867 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3868 DAG.getTargetConstant( 3869 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3870 } 3871 3872 void SelectionDAGBuilder::visitFPExt(const User &I) { 3873 // FPExt is never a no-op cast, no need to check 3874 SDValue N = getValue(I.getOperand(0)); 3875 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3876 I.getType()); 3877 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3878 } 3879 3880 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3881 // FPToUI 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_TO_UINT, getCurSDLoc(), DestVT, N)); 3886 } 3887 3888 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3889 // FPToSI 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_SINT, getCurSDLoc(), DestVT, N)); 3894 } 3895 3896 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3897 // UIToFP 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 SDNodeFlags Flags; 3902 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3903 Flags.setNonNeg(PNI->hasNonNeg()); 3904 3905 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags)); 3906 } 3907 3908 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3909 // SIToFP is never a no-op cast, no need to check 3910 SDValue N = getValue(I.getOperand(0)); 3911 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3912 I.getType()); 3913 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3914 } 3915 3916 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3917 // What to do depends on the size of the integer and the size of the pointer. 3918 // We can either truncate, zero extend, or no-op, accordingly. 3919 SDValue N = getValue(I.getOperand(0)); 3920 auto &TLI = DAG.getTargetLoweringInfo(); 3921 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3922 I.getType()); 3923 EVT PtrMemVT = 3924 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3925 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3926 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3927 setValue(&I, N); 3928 } 3929 3930 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3931 // What to do depends on the size of the integer and the size of the pointer. 3932 // We can either truncate, zero extend, or no-op, accordingly. 3933 SDValue N = getValue(I.getOperand(0)); 3934 auto &TLI = DAG.getTargetLoweringInfo(); 3935 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3936 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3937 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3938 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3939 setValue(&I, N); 3940 } 3941 3942 void SelectionDAGBuilder::visitBitCast(const User &I) { 3943 SDValue N = getValue(I.getOperand(0)); 3944 SDLoc dl = getCurSDLoc(); 3945 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3946 I.getType()); 3947 3948 // BitCast assures us that source and destination are the same size so this is 3949 // either a BITCAST or a no-op. 3950 if (DestVT != N.getValueType()) 3951 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3952 DestVT, N)); // convert types. 3953 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3954 // might fold any kind of constant expression to an integer constant and that 3955 // is not what we are looking for. Only recognize a bitcast of a genuine 3956 // constant integer as an opaque constant. 3957 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3958 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3959 /*isOpaque*/true)); 3960 else 3961 setValue(&I, N); // noop cast. 3962 } 3963 3964 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3965 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3966 const Value *SV = I.getOperand(0); 3967 SDValue N = getValue(SV); 3968 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3969 3970 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3971 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3972 3973 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3974 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3975 3976 setValue(&I, N); 3977 } 3978 3979 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3980 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3981 SDValue InVec = getValue(I.getOperand(0)); 3982 SDValue InVal = getValue(I.getOperand(1)); 3983 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3984 TLI.getVectorIdxTy(DAG.getDataLayout())); 3985 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3986 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3987 InVec, InVal, InIdx)); 3988 } 3989 3990 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3991 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3992 SDValue InVec = getValue(I.getOperand(0)); 3993 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3994 TLI.getVectorIdxTy(DAG.getDataLayout())); 3995 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3996 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3997 InVec, InIdx)); 3998 } 3999 4000 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 4001 SDValue Src1 = getValue(I.getOperand(0)); 4002 SDValue Src2 = getValue(I.getOperand(1)); 4003 ArrayRef<int> Mask; 4004 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 4005 Mask = SVI->getShuffleMask(); 4006 else 4007 Mask = cast<ConstantExpr>(I).getShuffleMask(); 4008 SDLoc DL = getCurSDLoc(); 4009 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4010 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4011 EVT SrcVT = Src1.getValueType(); 4012 4013 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 4014 VT.isScalableVector()) { 4015 // Canonical splat form of first element of first input vector. 4016 SDValue FirstElt = 4017 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 4018 DAG.getVectorIdxConstant(0, DL)); 4019 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 4020 return; 4021 } 4022 4023 // For now, we only handle splats for scalable vectors. 4024 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 4025 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 4026 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 4027 4028 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 4029 unsigned MaskNumElts = Mask.size(); 4030 4031 if (SrcNumElts == MaskNumElts) { 4032 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 4033 return; 4034 } 4035 4036 // Normalize the shuffle vector since mask and vector length don't match. 4037 if (SrcNumElts < MaskNumElts) { 4038 // Mask is longer than the source vectors. We can use concatenate vector to 4039 // make the mask and vectors lengths match. 4040 4041 if (MaskNumElts % SrcNumElts == 0) { 4042 // Mask length is a multiple of the source vector length. 4043 // Check if the shuffle is some kind of concatenation of the input 4044 // vectors. 4045 unsigned NumConcat = MaskNumElts / SrcNumElts; 4046 bool IsConcat = true; 4047 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 4048 for (unsigned i = 0; i != MaskNumElts; ++i) { 4049 int Idx = Mask[i]; 4050 if (Idx < 0) 4051 continue; 4052 // Ensure the indices in each SrcVT sized piece are sequential and that 4053 // the same source is used for the whole piece. 4054 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 4055 (ConcatSrcs[i / SrcNumElts] >= 0 && 4056 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 4057 IsConcat = false; 4058 break; 4059 } 4060 // Remember which source this index came from. 4061 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 4062 } 4063 4064 // The shuffle is concatenating multiple vectors together. Just emit 4065 // a CONCAT_VECTORS operation. 4066 if (IsConcat) { 4067 SmallVector<SDValue, 8> ConcatOps; 4068 for (auto Src : ConcatSrcs) { 4069 if (Src < 0) 4070 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 4071 else if (Src == 0) 4072 ConcatOps.push_back(Src1); 4073 else 4074 ConcatOps.push_back(Src2); 4075 } 4076 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 4077 return; 4078 } 4079 } 4080 4081 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 4082 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 4083 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 4084 PaddedMaskNumElts); 4085 4086 // Pad both vectors with undefs to make them the same length as the mask. 4087 SDValue UndefVal = DAG.getUNDEF(SrcVT); 4088 4089 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 4090 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 4091 MOps1[0] = Src1; 4092 MOps2[0] = Src2; 4093 4094 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 4095 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 4096 4097 // Readjust mask for new input vector length. 4098 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 4099 for (unsigned i = 0; i != MaskNumElts; ++i) { 4100 int Idx = Mask[i]; 4101 if (Idx >= (int)SrcNumElts) 4102 Idx -= SrcNumElts - PaddedMaskNumElts; 4103 MappedOps[i] = Idx; 4104 } 4105 4106 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 4107 4108 // If the concatenated vector was padded, extract a subvector with the 4109 // correct number of elements. 4110 if (MaskNumElts != PaddedMaskNumElts) 4111 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 4112 DAG.getVectorIdxConstant(0, DL)); 4113 4114 setValue(&I, Result); 4115 return; 4116 } 4117 4118 if (SrcNumElts > MaskNumElts) { 4119 // Analyze the access pattern of the vector to see if we can extract 4120 // two subvectors and do the shuffle. 4121 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 4122 bool CanExtract = true; 4123 for (int Idx : Mask) { 4124 unsigned Input = 0; 4125 if (Idx < 0) 4126 continue; 4127 4128 if (Idx >= (int)SrcNumElts) { 4129 Input = 1; 4130 Idx -= SrcNumElts; 4131 } 4132 4133 // If all the indices come from the same MaskNumElts sized portion of 4134 // the sources we can use extract. Also make sure the extract wouldn't 4135 // extract past the end of the source. 4136 int NewStartIdx = alignDown(Idx, MaskNumElts); 4137 if (NewStartIdx + MaskNumElts > SrcNumElts || 4138 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 4139 CanExtract = false; 4140 // Make sure we always update StartIdx as we use it to track if all 4141 // elements are undef. 4142 StartIdx[Input] = NewStartIdx; 4143 } 4144 4145 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 4146 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 4147 return; 4148 } 4149 if (CanExtract) { 4150 // Extract appropriate subvector and generate a vector shuffle 4151 for (unsigned Input = 0; Input < 2; ++Input) { 4152 SDValue &Src = Input == 0 ? Src1 : Src2; 4153 if (StartIdx[Input] < 0) 4154 Src = DAG.getUNDEF(VT); 4155 else { 4156 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 4157 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 4158 } 4159 } 4160 4161 // Calculate new mask. 4162 SmallVector<int, 8> MappedOps(Mask); 4163 for (int &Idx : MappedOps) { 4164 if (Idx >= (int)SrcNumElts) 4165 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 4166 else if (Idx >= 0) 4167 Idx -= StartIdx[0]; 4168 } 4169 4170 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 4171 return; 4172 } 4173 } 4174 4175 // We can't use either concat vectors or extract subvectors so fall back to 4176 // replacing the shuffle with extract and build vector. 4177 // to insert and build vector. 4178 EVT EltVT = VT.getVectorElementType(); 4179 SmallVector<SDValue,8> Ops; 4180 for (int Idx : Mask) { 4181 SDValue Res; 4182 4183 if (Idx < 0) { 4184 Res = DAG.getUNDEF(EltVT); 4185 } else { 4186 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 4187 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 4188 4189 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4190 DAG.getVectorIdxConstant(Idx, DL)); 4191 } 4192 4193 Ops.push_back(Res); 4194 } 4195 4196 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4197 } 4198 4199 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4200 ArrayRef<unsigned> Indices = I.getIndices(); 4201 const Value *Op0 = I.getOperand(0); 4202 const Value *Op1 = I.getOperand(1); 4203 Type *AggTy = I.getType(); 4204 Type *ValTy = Op1->getType(); 4205 bool IntoUndef = isa<UndefValue>(Op0); 4206 bool FromUndef = isa<UndefValue>(Op1); 4207 4208 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4209 4210 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4211 SmallVector<EVT, 4> AggValueVTs; 4212 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4213 SmallVector<EVT, 4> ValValueVTs; 4214 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4215 4216 unsigned NumAggValues = AggValueVTs.size(); 4217 unsigned NumValValues = ValValueVTs.size(); 4218 SmallVector<SDValue, 4> Values(NumAggValues); 4219 4220 // Ignore an insertvalue that produces an empty object 4221 if (!NumAggValues) { 4222 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4223 return; 4224 } 4225 4226 SDValue Agg = getValue(Op0); 4227 unsigned i = 0; 4228 // Copy the beginning value(s) from the original aggregate. 4229 for (; i != LinearIndex; ++i) 4230 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4231 SDValue(Agg.getNode(), Agg.getResNo() + i); 4232 // Copy values from the inserted value(s). 4233 if (NumValValues) { 4234 SDValue Val = getValue(Op1); 4235 for (; i != LinearIndex + NumValValues; ++i) 4236 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4237 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4238 } 4239 // Copy remaining value(s) from the original aggregate. 4240 for (; i != NumAggValues; ++i) 4241 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4242 SDValue(Agg.getNode(), Agg.getResNo() + i); 4243 4244 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4245 DAG.getVTList(AggValueVTs), Values)); 4246 } 4247 4248 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4249 ArrayRef<unsigned> Indices = I.getIndices(); 4250 const Value *Op0 = I.getOperand(0); 4251 Type *AggTy = Op0->getType(); 4252 Type *ValTy = I.getType(); 4253 bool OutOfUndef = isa<UndefValue>(Op0); 4254 4255 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4256 4257 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4258 SmallVector<EVT, 4> ValValueVTs; 4259 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4260 4261 unsigned NumValValues = ValValueVTs.size(); 4262 4263 // Ignore a extractvalue that produces an empty object 4264 if (!NumValValues) { 4265 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4266 return; 4267 } 4268 4269 SmallVector<SDValue, 4> Values(NumValValues); 4270 4271 SDValue Agg = getValue(Op0); 4272 // Copy out the selected value(s). 4273 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4274 Values[i - LinearIndex] = 4275 OutOfUndef ? 4276 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4277 SDValue(Agg.getNode(), Agg.getResNo() + i); 4278 4279 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4280 DAG.getVTList(ValValueVTs), Values)); 4281 } 4282 4283 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4284 Value *Op0 = I.getOperand(0); 4285 // Note that the pointer operand may be a vector of pointers. Take the scalar 4286 // element which holds a pointer. 4287 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4288 SDValue N = getValue(Op0); 4289 SDLoc dl = getCurSDLoc(); 4290 auto &TLI = DAG.getTargetLoweringInfo(); 4291 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags(); 4292 4293 // Normalize Vector GEP - all scalar operands should be converted to the 4294 // splat vector. 4295 bool IsVectorGEP = I.getType()->isVectorTy(); 4296 ElementCount VectorElementCount = 4297 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4298 : ElementCount::getFixed(0); 4299 4300 if (IsVectorGEP && !N.getValueType().isVector()) { 4301 LLVMContext &Context = *DAG.getContext(); 4302 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4303 N = DAG.getSplat(VT, dl, N); 4304 } 4305 4306 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4307 GTI != E; ++GTI) { 4308 const Value *Idx = GTI.getOperand(); 4309 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4310 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4311 if (Field) { 4312 // N = N + Offset 4313 uint64_t Offset = 4314 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4315 4316 // In an inbounds GEP with an offset that is nonnegative even when 4317 // interpreted as signed, assume there is no unsigned overflow. 4318 SDNodeFlags Flags; 4319 if (NW.hasNoUnsignedWrap() || 4320 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap())) 4321 Flags.setNoUnsignedWrap(true); 4322 4323 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4324 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4325 } 4326 } else { 4327 // IdxSize is the width of the arithmetic according to IR semantics. 4328 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4329 // (and fix up the result later). 4330 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4331 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4332 TypeSize ElementSize = 4333 GTI.getSequentialElementStride(DAG.getDataLayout()); 4334 // We intentionally mask away the high bits here; ElementSize may not 4335 // fit in IdxTy. 4336 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4337 bool ElementScalable = ElementSize.isScalable(); 4338 4339 // If this is a scalar constant or a splat vector of constants, 4340 // handle it quickly. 4341 const auto *C = dyn_cast<Constant>(Idx); 4342 if (C && isa<VectorType>(C->getType())) 4343 C = C->getSplatValue(); 4344 4345 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4346 if (CI && CI->isZero()) 4347 continue; 4348 if (CI && !ElementScalable) { 4349 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4350 LLVMContext &Context = *DAG.getContext(); 4351 SDValue OffsVal; 4352 if (IsVectorGEP) 4353 OffsVal = DAG.getConstant( 4354 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4355 else 4356 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4357 4358 // In an inbounds GEP with an offset that is nonnegative even when 4359 // interpreted as signed, assume there is no unsigned overflow. 4360 SDNodeFlags Flags; 4361 if (NW.hasNoUnsignedWrap() || 4362 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap())) 4363 Flags.setNoUnsignedWrap(true); 4364 4365 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4366 4367 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4368 continue; 4369 } 4370 4371 // N = N + Idx * ElementMul; 4372 SDValue IdxN = getValue(Idx); 4373 4374 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4375 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4376 VectorElementCount); 4377 IdxN = DAG.getSplat(VT, dl, IdxN); 4378 } 4379 4380 // If the index is smaller or larger than intptr_t, truncate or extend 4381 // it. 4382 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4383 4384 if (ElementScalable) { 4385 EVT VScaleTy = N.getValueType().getScalarType(); 4386 SDValue VScale = DAG.getNode( 4387 ISD::VSCALE, dl, VScaleTy, 4388 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4389 if (IsVectorGEP) 4390 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4391 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4392 } else { 4393 // If this is a multiply by a power of two, turn it into a shl 4394 // immediately. This is a very common case. 4395 if (ElementMul != 1) { 4396 if (ElementMul.isPowerOf2()) { 4397 unsigned Amt = ElementMul.logBase2(); 4398 IdxN = DAG.getNode(ISD::SHL, dl, 4399 N.getValueType(), IdxN, 4400 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4401 } else { 4402 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4403 IdxN.getValueType()); 4404 IdxN = DAG.getNode(ISD::MUL, dl, 4405 N.getValueType(), IdxN, Scale); 4406 } 4407 } 4408 } 4409 4410 N = DAG.getNode(ISD::ADD, dl, 4411 N.getValueType(), N, IdxN); 4412 } 4413 } 4414 4415 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4416 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4417 if (IsVectorGEP) { 4418 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4419 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4420 } 4421 4422 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4423 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4424 4425 setValue(&I, N); 4426 } 4427 4428 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4429 // If this is a fixed sized alloca in the entry block of the function, 4430 // allocate it statically on the stack. 4431 if (FuncInfo.StaticAllocaMap.count(&I)) 4432 return; // getValue will auto-populate this. 4433 4434 SDLoc dl = getCurSDLoc(); 4435 Type *Ty = I.getAllocatedType(); 4436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4437 auto &DL = DAG.getDataLayout(); 4438 TypeSize TySize = DL.getTypeAllocSize(Ty); 4439 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4440 4441 SDValue AllocSize = getValue(I.getArraySize()); 4442 4443 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4444 if (AllocSize.getValueType() != IntPtr) 4445 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4446 4447 if (TySize.isScalable()) 4448 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4449 DAG.getVScale(dl, IntPtr, 4450 APInt(IntPtr.getScalarSizeInBits(), 4451 TySize.getKnownMinValue()))); 4452 else { 4453 SDValue TySizeValue = 4454 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4455 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4456 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4457 } 4458 4459 // Handle alignment. If the requested alignment is less than or equal to 4460 // the stack alignment, ignore it. If the size is greater than or equal to 4461 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4462 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4463 if (*Alignment <= StackAlign) 4464 Alignment = std::nullopt; 4465 4466 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4467 // Round the size of the allocation up to the stack alignment size 4468 // by add SA-1 to the size. This doesn't overflow because we're computing 4469 // an address inside an alloca. 4470 SDNodeFlags Flags; 4471 Flags.setNoUnsignedWrap(true); 4472 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4473 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4474 4475 // Mask out the low bits for alignment purposes. 4476 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4477 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr)); 4478 4479 SDValue Ops[] = { 4480 getRoot(), AllocSize, 4481 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4482 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4483 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4484 setValue(&I, DSA); 4485 DAG.setRoot(DSA.getValue(1)); 4486 4487 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4488 } 4489 4490 static const MDNode *getRangeMetadata(const Instruction &I) { 4491 // If !noundef is not present, then !range violation results in a poison 4492 // value rather than immediate undefined behavior. In theory, transferring 4493 // these annotations to SDAG is fine, but in practice there are key SDAG 4494 // transforms that are known not to be poison-safe, such as folding logical 4495 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4496 // also present. 4497 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4498 return nullptr; 4499 return I.getMetadata(LLVMContext::MD_range); 4500 } 4501 4502 static std::optional<ConstantRange> getRange(const Instruction &I) { 4503 if (const auto *CB = dyn_cast<CallBase>(&I)) { 4504 // see comment in getRangeMetadata about this check 4505 if (CB->hasRetAttr(Attribute::NoUndef)) 4506 return CB->getRange(); 4507 } 4508 if (const MDNode *Range = getRangeMetadata(I)) 4509 return getConstantRangeFromMetadata(*Range); 4510 return std::nullopt; 4511 } 4512 4513 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4514 if (I.isAtomic()) 4515 return visitAtomicLoad(I); 4516 4517 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4518 const Value *SV = I.getOperand(0); 4519 if (TLI.supportSwiftError()) { 4520 // Swifterror values can come from either a function parameter with 4521 // swifterror attribute or an alloca with swifterror attribute. 4522 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4523 if (Arg->hasSwiftErrorAttr()) 4524 return visitLoadFromSwiftError(I); 4525 } 4526 4527 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4528 if (Alloca->isSwiftError()) 4529 return visitLoadFromSwiftError(I); 4530 } 4531 } 4532 4533 SDValue Ptr = getValue(SV); 4534 4535 Type *Ty = I.getType(); 4536 SmallVector<EVT, 4> ValueVTs, MemVTs; 4537 SmallVector<TypeSize, 4> Offsets; 4538 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4539 unsigned NumValues = ValueVTs.size(); 4540 if (NumValues == 0) 4541 return; 4542 4543 Align Alignment = I.getAlign(); 4544 AAMDNodes AAInfo = I.getAAMetadata(); 4545 const MDNode *Ranges = getRangeMetadata(I); 4546 bool isVolatile = I.isVolatile(); 4547 MachineMemOperand::Flags MMOFlags = 4548 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4549 4550 SDValue Root; 4551 bool ConstantMemory = false; 4552 if (isVolatile) 4553 // Serialize volatile loads with other side effects. 4554 Root = getRoot(); 4555 else if (NumValues > MaxParallelChains) 4556 Root = getMemoryRoot(); 4557 else if (AA && 4558 AA->pointsToConstantMemory(MemoryLocation( 4559 SV, 4560 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4561 AAInfo))) { 4562 // Do not serialize (non-volatile) loads of constant memory with anything. 4563 Root = DAG.getEntryNode(); 4564 ConstantMemory = true; 4565 MMOFlags |= MachineMemOperand::MOInvariant; 4566 } else { 4567 // Do not serialize non-volatile loads against each other. 4568 Root = DAG.getRoot(); 4569 } 4570 4571 SDLoc dl = getCurSDLoc(); 4572 4573 if (isVolatile) 4574 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4575 4576 SmallVector<SDValue, 4> Values(NumValues); 4577 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4578 4579 unsigned ChainI = 0; 4580 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4581 // Serializing loads here may result in excessive register pressure, and 4582 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4583 // could recover a bit by hoisting nodes upward in the chain by recognizing 4584 // they are side-effect free or do not alias. The optimizer should really 4585 // avoid this case by converting large object/array copies to llvm.memcpy 4586 // (MaxParallelChains should always remain as failsafe). 4587 if (ChainI == MaxParallelChains) { 4588 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4589 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4590 ArrayRef(Chains.data(), ChainI)); 4591 Root = Chain; 4592 ChainI = 0; 4593 } 4594 4595 // TODO: MachinePointerInfo only supports a fixed length offset. 4596 MachinePointerInfo PtrInfo = 4597 !Offsets[i].isScalable() || Offsets[i].isZero() 4598 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4599 : MachinePointerInfo(); 4600 4601 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4602 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4603 MMOFlags, AAInfo, Ranges); 4604 Chains[ChainI] = L.getValue(1); 4605 4606 if (MemVTs[i] != ValueVTs[i]) 4607 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4608 4609 Values[i] = L; 4610 } 4611 4612 if (!ConstantMemory) { 4613 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4614 ArrayRef(Chains.data(), ChainI)); 4615 if (isVolatile) 4616 DAG.setRoot(Chain); 4617 else 4618 PendingLoads.push_back(Chain); 4619 } 4620 4621 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4622 DAG.getVTList(ValueVTs), Values)); 4623 } 4624 4625 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4626 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4627 "call visitStoreToSwiftError when backend supports swifterror"); 4628 4629 SmallVector<EVT, 4> ValueVTs; 4630 SmallVector<uint64_t, 4> Offsets; 4631 const Value *SrcV = I.getOperand(0); 4632 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4633 SrcV->getType(), ValueVTs, &Offsets, 0); 4634 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4635 "expect a single EVT for swifterror"); 4636 4637 SDValue Src = getValue(SrcV); 4638 // Create a virtual register, then update the virtual register. 4639 Register VReg = 4640 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4641 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4642 // Chain can be getRoot or getControlRoot. 4643 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4644 SDValue(Src.getNode(), Src.getResNo())); 4645 DAG.setRoot(CopyNode); 4646 } 4647 4648 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4649 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4650 "call visitLoadFromSwiftError when backend supports swifterror"); 4651 4652 assert(!I.isVolatile() && 4653 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4654 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4655 "Support volatile, non temporal, invariant for load_from_swift_error"); 4656 4657 const Value *SV = I.getOperand(0); 4658 Type *Ty = I.getType(); 4659 assert( 4660 (!AA || 4661 !AA->pointsToConstantMemory(MemoryLocation( 4662 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4663 I.getAAMetadata()))) && 4664 "load_from_swift_error should not be constant memory"); 4665 4666 SmallVector<EVT, 4> ValueVTs; 4667 SmallVector<uint64_t, 4> Offsets; 4668 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4669 ValueVTs, &Offsets, 0); 4670 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4671 "expect a single EVT for swifterror"); 4672 4673 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4674 SDValue L = DAG.getCopyFromReg( 4675 getRoot(), getCurSDLoc(), 4676 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4677 4678 setValue(&I, L); 4679 } 4680 4681 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4682 if (I.isAtomic()) 4683 return visitAtomicStore(I); 4684 4685 const Value *SrcV = I.getOperand(0); 4686 const Value *PtrV = I.getOperand(1); 4687 4688 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4689 if (TLI.supportSwiftError()) { 4690 // Swifterror values can come from either a function parameter with 4691 // swifterror attribute or an alloca with swifterror attribute. 4692 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4693 if (Arg->hasSwiftErrorAttr()) 4694 return visitStoreToSwiftError(I); 4695 } 4696 4697 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4698 if (Alloca->isSwiftError()) 4699 return visitStoreToSwiftError(I); 4700 } 4701 } 4702 4703 SmallVector<EVT, 4> ValueVTs, MemVTs; 4704 SmallVector<TypeSize, 4> Offsets; 4705 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4706 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4707 unsigned NumValues = ValueVTs.size(); 4708 if (NumValues == 0) 4709 return; 4710 4711 // Get the lowered operands. Note that we do this after 4712 // checking if NumResults is zero, because with zero results 4713 // the operands won't have values in the map. 4714 SDValue Src = getValue(SrcV); 4715 SDValue Ptr = getValue(PtrV); 4716 4717 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4718 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4719 SDLoc dl = getCurSDLoc(); 4720 Align Alignment = I.getAlign(); 4721 AAMDNodes AAInfo = I.getAAMetadata(); 4722 4723 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4724 4725 unsigned ChainI = 0; 4726 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4727 // See visitLoad comments. 4728 if (ChainI == MaxParallelChains) { 4729 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4730 ArrayRef(Chains.data(), ChainI)); 4731 Root = Chain; 4732 ChainI = 0; 4733 } 4734 4735 // TODO: MachinePointerInfo only supports a fixed length offset. 4736 MachinePointerInfo PtrInfo = 4737 !Offsets[i].isScalable() || Offsets[i].isZero() 4738 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4739 : MachinePointerInfo(); 4740 4741 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4742 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4743 if (MemVTs[i] != ValueVTs[i]) 4744 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4745 SDValue St = 4746 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4747 Chains[ChainI] = St; 4748 } 4749 4750 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4751 ArrayRef(Chains.data(), ChainI)); 4752 setValue(&I, StoreNode); 4753 DAG.setRoot(StoreNode); 4754 } 4755 4756 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4757 bool IsCompressing) { 4758 SDLoc sdl = getCurSDLoc(); 4759 4760 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4761 Align &Alignment) { 4762 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4763 Src0 = I.getArgOperand(0); 4764 Ptr = I.getArgOperand(1); 4765 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue(); 4766 Mask = I.getArgOperand(3); 4767 }; 4768 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4769 Align &Alignment) { 4770 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4771 Src0 = I.getArgOperand(0); 4772 Ptr = I.getArgOperand(1); 4773 Mask = I.getArgOperand(2); 4774 Alignment = I.getParamAlign(1).valueOrOne(); 4775 }; 4776 4777 Value *PtrOperand, *MaskOperand, *Src0Operand; 4778 Align Alignment; 4779 if (IsCompressing) 4780 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4781 else 4782 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4783 4784 SDValue Ptr = getValue(PtrOperand); 4785 SDValue Src0 = getValue(Src0Operand); 4786 SDValue Mask = getValue(MaskOperand); 4787 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4788 4789 EVT VT = Src0.getValueType(); 4790 4791 auto MMOFlags = MachineMemOperand::MOStore; 4792 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4793 MMOFlags |= MachineMemOperand::MONonTemporal; 4794 4795 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4796 MachinePointerInfo(PtrOperand), MMOFlags, 4797 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4798 4799 const auto &TLI = DAG.getTargetLoweringInfo(); 4800 const auto &TTI = 4801 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 4802 SDValue StoreNode = 4803 !IsCompressing && 4804 TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType()) 4805 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0, 4806 Mask) 4807 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, 4808 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false, 4809 IsCompressing); 4810 DAG.setRoot(StoreNode); 4811 setValue(&I, StoreNode); 4812 } 4813 4814 // Get a uniform base for the Gather/Scatter intrinsic. 4815 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4816 // We try to represent it as a base pointer + vector of indices. 4817 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4818 // The first operand of the GEP may be a single pointer or a vector of pointers 4819 // Example: 4820 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4821 // or 4822 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4823 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4824 // 4825 // When the first GEP operand is a single pointer - it is the uniform base we 4826 // are looking for. If first operand of the GEP is a splat vector - we 4827 // extract the splat value and use it as a uniform base. 4828 // In all other cases the function returns 'false'. 4829 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4830 ISD::MemIndexType &IndexType, SDValue &Scale, 4831 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4832 uint64_t ElemSize) { 4833 SelectionDAG& DAG = SDB->DAG; 4834 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4835 const DataLayout &DL = DAG.getDataLayout(); 4836 4837 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4838 4839 // Handle splat constant pointer. 4840 if (auto *C = dyn_cast<Constant>(Ptr)) { 4841 C = C->getSplatValue(); 4842 if (!C) 4843 return false; 4844 4845 Base = SDB->getValue(C); 4846 4847 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4848 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4849 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4850 IndexType = ISD::SIGNED_SCALED; 4851 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4852 return true; 4853 } 4854 4855 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4856 if (!GEP || GEP->getParent() != CurBB) 4857 return false; 4858 4859 if (GEP->getNumOperands() != 2) 4860 return false; 4861 4862 const Value *BasePtr = GEP->getPointerOperand(); 4863 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4864 4865 // Make sure the base is scalar and the index is a vector. 4866 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4867 return false; 4868 4869 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4870 if (ScaleVal.isScalable()) 4871 return false; 4872 4873 // Target may not support the required addressing mode. 4874 if (ScaleVal != 1 && 4875 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4876 return false; 4877 4878 Base = SDB->getValue(BasePtr); 4879 Index = SDB->getValue(IndexVal); 4880 IndexType = ISD::SIGNED_SCALED; 4881 4882 Scale = 4883 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4884 return true; 4885 } 4886 4887 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4888 SDLoc sdl = getCurSDLoc(); 4889 4890 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4891 const Value *Ptr = I.getArgOperand(1); 4892 SDValue Src0 = getValue(I.getArgOperand(0)); 4893 SDValue Mask = getValue(I.getArgOperand(3)); 4894 EVT VT = Src0.getValueType(); 4895 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4896 ->getMaybeAlignValue() 4897 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4898 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4899 4900 SDValue Base; 4901 SDValue Index; 4902 ISD::MemIndexType IndexType; 4903 SDValue Scale; 4904 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4905 I.getParent(), VT.getScalarStoreSize()); 4906 4907 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4908 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4909 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4910 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4911 if (!UniformBase) { 4912 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4913 Index = getValue(Ptr); 4914 IndexType = ISD::SIGNED_SCALED; 4915 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4916 } 4917 4918 EVT IdxVT = Index.getValueType(); 4919 EVT EltTy = IdxVT.getVectorElementType(); 4920 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4921 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4922 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4923 } 4924 4925 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4926 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4927 Ops, MMO, IndexType, false); 4928 DAG.setRoot(Scatter); 4929 setValue(&I, Scatter); 4930 } 4931 4932 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4933 SDLoc sdl = getCurSDLoc(); 4934 4935 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4936 Align &Alignment) { 4937 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4938 Ptr = I.getArgOperand(0); 4939 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue(); 4940 Mask = I.getArgOperand(2); 4941 Src0 = I.getArgOperand(3); 4942 }; 4943 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4944 Align &Alignment) { 4945 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4946 Ptr = I.getArgOperand(0); 4947 Alignment = I.getParamAlign(0).valueOrOne(); 4948 Mask = I.getArgOperand(1); 4949 Src0 = I.getArgOperand(2); 4950 }; 4951 4952 Value *PtrOperand, *MaskOperand, *Src0Operand; 4953 Align Alignment; 4954 if (IsExpanding) 4955 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4956 else 4957 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4958 4959 SDValue Ptr = getValue(PtrOperand); 4960 SDValue Src0 = getValue(Src0Operand); 4961 SDValue Mask = getValue(MaskOperand); 4962 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4963 4964 EVT VT = Src0.getValueType(); 4965 AAMDNodes AAInfo = I.getAAMetadata(); 4966 const MDNode *Ranges = getRangeMetadata(I); 4967 4968 // Do not serialize masked loads of constant memory with anything. 4969 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4970 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4971 4972 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4973 4974 auto MMOFlags = MachineMemOperand::MOLoad; 4975 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4976 MMOFlags |= MachineMemOperand::MONonTemporal; 4977 4978 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4979 MachinePointerInfo(PtrOperand), MMOFlags, 4980 LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges); 4981 4982 const auto &TLI = DAG.getTargetLoweringInfo(); 4983 const auto &TTI = 4984 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 4985 // The Load/Res may point to different values and both of them are output 4986 // variables. 4987 SDValue Load; 4988 SDValue Res; 4989 if (!IsExpanding && 4990 TTI.hasConditionalLoadStoreForType(Src0Operand->getType())) 4991 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask); 4992 else 4993 Res = Load = 4994 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4995 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4996 if (AddToChain) 4997 PendingLoads.push_back(Load.getValue(1)); 4998 setValue(&I, Res); 4999 } 5000 5001 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 5002 SDLoc sdl = getCurSDLoc(); 5003 5004 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 5005 const Value *Ptr = I.getArgOperand(0); 5006 SDValue Src0 = getValue(I.getArgOperand(3)); 5007 SDValue Mask = getValue(I.getArgOperand(2)); 5008 5009 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5010 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5011 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 5012 ->getMaybeAlignValue() 5013 .value_or(DAG.getEVTAlign(VT.getScalarType())); 5014 5015 const MDNode *Ranges = getRangeMetadata(I); 5016 5017 SDValue Root = DAG.getRoot(); 5018 SDValue Base; 5019 SDValue Index; 5020 ISD::MemIndexType IndexType; 5021 SDValue Scale; 5022 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 5023 I.getParent(), VT.getScalarStoreSize()); 5024 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 5025 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5026 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 5027 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(), 5028 Ranges); 5029 5030 if (!UniformBase) { 5031 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 5032 Index = getValue(Ptr); 5033 IndexType = ISD::SIGNED_SCALED; 5034 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 5035 } 5036 5037 EVT IdxVT = Index.getValueType(); 5038 EVT EltTy = IdxVT.getVectorElementType(); 5039 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 5040 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 5041 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 5042 } 5043 5044 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 5045 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 5046 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 5047 5048 PendingLoads.push_back(Gather.getValue(1)); 5049 setValue(&I, Gather); 5050 } 5051 5052 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 5053 SDLoc dl = getCurSDLoc(); 5054 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 5055 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 5056 SyncScope::ID SSID = I.getSyncScopeID(); 5057 5058 SDValue InChain = getRoot(); 5059 5060 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 5061 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 5062 5063 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5064 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5065 5066 MachineFunction &MF = DAG.getMachineFunction(); 5067 MachineMemOperand *MMO = MF.getMachineMemOperand( 5068 MachinePointerInfo(I.getPointerOperand()), Flags, 5069 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5070 AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering); 5071 5072 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 5073 dl, MemVT, VTs, InChain, 5074 getValue(I.getPointerOperand()), 5075 getValue(I.getCompareOperand()), 5076 getValue(I.getNewValOperand()), MMO); 5077 5078 SDValue OutChain = L.getValue(2); 5079 5080 setValue(&I, L); 5081 DAG.setRoot(OutChain); 5082 } 5083 5084 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 5085 SDLoc dl = getCurSDLoc(); 5086 ISD::NodeType NT; 5087 switch (I.getOperation()) { 5088 default: llvm_unreachable("Unknown atomicrmw operation"); 5089 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 5090 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 5091 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 5092 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 5093 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 5094 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 5095 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 5096 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 5097 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 5098 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 5099 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 5100 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 5101 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 5102 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 5103 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 5104 case AtomicRMWInst::UIncWrap: 5105 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 5106 break; 5107 case AtomicRMWInst::UDecWrap: 5108 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 5109 break; 5110 } 5111 AtomicOrdering Ordering = I.getOrdering(); 5112 SyncScope::ID SSID = I.getSyncScopeID(); 5113 5114 SDValue InChain = getRoot(); 5115 5116 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 5117 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5118 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5119 5120 MachineFunction &MF = DAG.getMachineFunction(); 5121 MachineMemOperand *MMO = MF.getMachineMemOperand( 5122 MachinePointerInfo(I.getPointerOperand()), Flags, 5123 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5124 AAMDNodes(), nullptr, SSID, Ordering); 5125 5126 SDValue L = 5127 DAG.getAtomic(NT, dl, MemVT, InChain, 5128 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 5129 MMO); 5130 5131 SDValue OutChain = L.getValue(1); 5132 5133 setValue(&I, L); 5134 DAG.setRoot(OutChain); 5135 } 5136 5137 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 5138 SDLoc dl = getCurSDLoc(); 5139 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5140 SDValue Ops[3]; 5141 Ops[0] = getRoot(); 5142 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 5143 TLI.getFenceOperandTy(DAG.getDataLayout())); 5144 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 5145 TLI.getFenceOperandTy(DAG.getDataLayout())); 5146 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 5147 setValue(&I, N); 5148 DAG.setRoot(N); 5149 } 5150 5151 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 5152 SDLoc dl = getCurSDLoc(); 5153 AtomicOrdering Order = I.getOrdering(); 5154 SyncScope::ID SSID = I.getSyncScopeID(); 5155 5156 SDValue InChain = getRoot(); 5157 5158 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5159 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5160 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 5161 5162 if (!TLI.supportsUnalignedAtomics() && 5163 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5164 report_fatal_error("Cannot generate unaligned atomic load"); 5165 5166 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 5167 5168 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5169 MachinePointerInfo(I.getPointerOperand()), Flags, 5170 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5171 nullptr, SSID, Order); 5172 5173 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 5174 5175 SDValue Ptr = getValue(I.getPointerOperand()); 5176 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 5177 Ptr, MMO); 5178 5179 SDValue OutChain = L.getValue(1); 5180 if (MemVT != VT) 5181 L = DAG.getPtrExtOrTrunc(L, dl, VT); 5182 5183 setValue(&I, L); 5184 DAG.setRoot(OutChain); 5185 } 5186 5187 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 5188 SDLoc dl = getCurSDLoc(); 5189 5190 AtomicOrdering Ordering = I.getOrdering(); 5191 SyncScope::ID SSID = I.getSyncScopeID(); 5192 5193 SDValue InChain = getRoot(); 5194 5195 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5196 EVT MemVT = 5197 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 5198 5199 if (!TLI.supportsUnalignedAtomics() && 5200 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5201 report_fatal_error("Cannot generate unaligned atomic store"); 5202 5203 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 5204 5205 MachineFunction &MF = DAG.getMachineFunction(); 5206 MachineMemOperand *MMO = MF.getMachineMemOperand( 5207 MachinePointerInfo(I.getPointerOperand()), Flags, 5208 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5209 nullptr, SSID, Ordering); 5210 5211 SDValue Val = getValue(I.getValueOperand()); 5212 if (Val.getValueType() != MemVT) 5213 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 5214 SDValue Ptr = getValue(I.getPointerOperand()); 5215 5216 SDValue OutChain = 5217 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 5218 5219 setValue(&I, OutChain); 5220 DAG.setRoot(OutChain); 5221 } 5222 5223 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 5224 /// node. 5225 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5226 unsigned Intrinsic) { 5227 // Ignore the callsite's attributes. A specific call site may be marked with 5228 // readnone, but the lowering code will expect the chain based on the 5229 // definition. 5230 const Function *F = I.getCalledFunction(); 5231 bool HasChain = !F->doesNotAccessMemory(); 5232 bool OnlyLoad = 5233 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow(); 5234 5235 // Build the operand list. 5236 SmallVector<SDValue, 8> Ops; 5237 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5238 if (OnlyLoad) { 5239 // We don't need to serialize loads against other loads. 5240 Ops.push_back(DAG.getRoot()); 5241 } else { 5242 Ops.push_back(getRoot()); 5243 } 5244 } 5245 5246 // Info is set by getTgtMemIntrinsic 5247 TargetLowering::IntrinsicInfo Info; 5248 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5249 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5250 DAG.getMachineFunction(), 5251 Intrinsic); 5252 5253 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5254 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5255 Info.opc == ISD::INTRINSIC_W_CHAIN) 5256 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5257 TLI.getPointerTy(DAG.getDataLayout()))); 5258 5259 // Add all operands of the call to the operand list. 5260 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5261 const Value *Arg = I.getArgOperand(i); 5262 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5263 Ops.push_back(getValue(Arg)); 5264 continue; 5265 } 5266 5267 // Use TargetConstant instead of a regular constant for immarg. 5268 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5269 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5270 assert(CI->getBitWidth() <= 64 && 5271 "large intrinsic immediates not handled"); 5272 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5273 } else { 5274 Ops.push_back( 5275 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5276 } 5277 } 5278 5279 SmallVector<EVT, 4> ValueVTs; 5280 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5281 5282 if (HasChain) 5283 ValueVTs.push_back(MVT::Other); 5284 5285 SDVTList VTs = DAG.getVTList(ValueVTs); 5286 5287 // Propagate fast-math-flags from IR to node(s). 5288 SDNodeFlags Flags; 5289 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5290 Flags.copyFMF(*FPMO); 5291 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5292 5293 // Create the node. 5294 SDValue Result; 5295 5296 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) { 5297 auto *Token = Bundle->Inputs[0].get(); 5298 SDValue ConvControlToken = getValue(Token); 5299 assert(Ops.back().getValueType() != MVT::Glue && 5300 "Did not expected another glue node here."); 5301 ConvControlToken = 5302 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken); 5303 Ops.push_back(ConvControlToken); 5304 } 5305 5306 // In some cases, custom collection of operands from CallInst I may be needed. 5307 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5308 if (IsTgtIntrinsic) { 5309 // This is target intrinsic that touches memory 5310 // 5311 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5312 // didn't yield anything useful. 5313 MachinePointerInfo MPI; 5314 if (Info.ptrVal) 5315 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5316 else if (Info.fallbackAddressSpace) 5317 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5318 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5319 Info.memVT, MPI, Info.align, Info.flags, 5320 Info.size, I.getAAMetadata()); 5321 } else if (!HasChain) { 5322 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5323 } else if (!I.getType()->isVoidTy()) { 5324 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5325 } else { 5326 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5327 } 5328 5329 if (HasChain) { 5330 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5331 if (OnlyLoad) 5332 PendingLoads.push_back(Chain); 5333 else 5334 DAG.setRoot(Chain); 5335 } 5336 5337 if (!I.getType()->isVoidTy()) { 5338 if (!isa<VectorType>(I.getType())) 5339 Result = lowerRangeToAssertZExt(DAG, I, Result); 5340 5341 MaybeAlign Alignment = I.getRetAlign(); 5342 5343 // Insert `assertalign` node if there's an alignment. 5344 if (InsertAssertAlign && Alignment) { 5345 Result = 5346 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5347 } 5348 } 5349 5350 setValue(&I, Result); 5351 } 5352 5353 /// GetSignificand - Get the significand and build it into a floating-point 5354 /// number with exponent of 1: 5355 /// 5356 /// Op = (Op & 0x007fffff) | 0x3f800000; 5357 /// 5358 /// where Op is the hexadecimal representation of floating point value. 5359 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5360 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5361 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5362 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5363 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5364 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5365 } 5366 5367 /// GetExponent - Get the exponent: 5368 /// 5369 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5370 /// 5371 /// where Op is the hexadecimal representation of floating point value. 5372 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5373 const TargetLowering &TLI, const SDLoc &dl) { 5374 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5375 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5376 SDValue t1 = DAG.getNode( 5377 ISD::SRL, dl, MVT::i32, t0, 5378 DAG.getConstant(23, dl, 5379 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5380 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5381 DAG.getConstant(127, dl, MVT::i32)); 5382 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5383 } 5384 5385 /// getF32Constant - Get 32-bit floating point constant. 5386 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5387 const SDLoc &dl) { 5388 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5389 MVT::f32); 5390 } 5391 5392 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5393 SelectionDAG &DAG) { 5394 // TODO: What fast-math-flags should be set on the floating-point nodes? 5395 5396 // IntegerPartOfX = ((int32_t)(t0); 5397 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5398 5399 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5400 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5401 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5402 5403 // IntegerPartOfX <<= 23; 5404 IntegerPartOfX = 5405 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5406 DAG.getConstant(23, dl, 5407 DAG.getTargetLoweringInfo().getShiftAmountTy( 5408 MVT::i32, DAG.getDataLayout()))); 5409 5410 SDValue TwoToFractionalPartOfX; 5411 if (LimitFloatPrecision <= 6) { 5412 // For floating-point precision of 6: 5413 // 5414 // TwoToFractionalPartOfX = 5415 // 0.997535578f + 5416 // (0.735607626f + 0.252464424f * x) * x; 5417 // 5418 // error 0.0144103317, which is 6 bits 5419 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5420 getF32Constant(DAG, 0x3e814304, dl)); 5421 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5422 getF32Constant(DAG, 0x3f3c50c8, dl)); 5423 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5424 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5425 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5426 } else if (LimitFloatPrecision <= 12) { 5427 // For floating-point precision of 12: 5428 // 5429 // TwoToFractionalPartOfX = 5430 // 0.999892986f + 5431 // (0.696457318f + 5432 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5433 // 5434 // error 0.000107046256, which is 13 to 14 bits 5435 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5436 getF32Constant(DAG, 0x3da235e3, dl)); 5437 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5438 getF32Constant(DAG, 0x3e65b8f3, dl)); 5439 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5440 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5441 getF32Constant(DAG, 0x3f324b07, dl)); 5442 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5443 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5444 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5445 } else { // LimitFloatPrecision <= 18 5446 // For floating-point precision of 18: 5447 // 5448 // TwoToFractionalPartOfX = 5449 // 0.999999982f + 5450 // (0.693148872f + 5451 // (0.240227044f + 5452 // (0.554906021e-1f + 5453 // (0.961591928e-2f + 5454 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5455 // error 2.47208000*10^(-7), which is better than 18 bits 5456 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5457 getF32Constant(DAG, 0x3924b03e, dl)); 5458 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5459 getF32Constant(DAG, 0x3ab24b87, dl)); 5460 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5461 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5462 getF32Constant(DAG, 0x3c1d8c17, dl)); 5463 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5464 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5465 getF32Constant(DAG, 0x3d634a1d, dl)); 5466 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5467 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5468 getF32Constant(DAG, 0x3e75fe14, dl)); 5469 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5470 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5471 getF32Constant(DAG, 0x3f317234, dl)); 5472 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5473 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5474 getF32Constant(DAG, 0x3f800000, dl)); 5475 } 5476 5477 // Add the exponent into the result in integer domain. 5478 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5479 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5480 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5481 } 5482 5483 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5484 /// limited-precision mode. 5485 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5486 const TargetLowering &TLI, SDNodeFlags Flags) { 5487 if (Op.getValueType() == MVT::f32 && 5488 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5489 5490 // Put the exponent in the right bit position for later addition to the 5491 // final result: 5492 // 5493 // t0 = Op * log2(e) 5494 5495 // TODO: What fast-math-flags should be set here? 5496 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5497 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5498 return getLimitedPrecisionExp2(t0, dl, DAG); 5499 } 5500 5501 // No special expansion. 5502 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5503 } 5504 5505 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5506 /// limited-precision mode. 5507 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5508 const TargetLowering &TLI, SDNodeFlags Flags) { 5509 // TODO: What fast-math-flags should be set on the floating-point nodes? 5510 5511 if (Op.getValueType() == MVT::f32 && 5512 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5513 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5514 5515 // Scale the exponent by log(2). 5516 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5517 SDValue LogOfExponent = 5518 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5519 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5520 5521 // Get the significand and build it into a floating-point number with 5522 // exponent of 1. 5523 SDValue X = GetSignificand(DAG, Op1, dl); 5524 5525 SDValue LogOfMantissa; 5526 if (LimitFloatPrecision <= 6) { 5527 // For floating-point precision of 6: 5528 // 5529 // LogofMantissa = 5530 // -1.1609546f + 5531 // (1.4034025f - 0.23903021f * x) * x; 5532 // 5533 // error 0.0034276066, which is better than 8 bits 5534 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5535 getF32Constant(DAG, 0xbe74c456, dl)); 5536 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5537 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5538 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5539 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5540 getF32Constant(DAG, 0x3f949a29, dl)); 5541 } else if (LimitFloatPrecision <= 12) { 5542 // For floating-point precision of 12: 5543 // 5544 // LogOfMantissa = 5545 // -1.7417939f + 5546 // (2.8212026f + 5547 // (-1.4699568f + 5548 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5549 // 5550 // error 0.000061011436, which is 14 bits 5551 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5552 getF32Constant(DAG, 0xbd67b6d6, dl)); 5553 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5554 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5555 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5556 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5557 getF32Constant(DAG, 0x3fbc278b, dl)); 5558 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5559 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5560 getF32Constant(DAG, 0x40348e95, dl)); 5561 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5562 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5563 getF32Constant(DAG, 0x3fdef31a, dl)); 5564 } else { // LimitFloatPrecision <= 18 5565 // For floating-point precision of 18: 5566 // 5567 // LogOfMantissa = 5568 // -2.1072184f + 5569 // (4.2372794f + 5570 // (-3.7029485f + 5571 // (2.2781945f + 5572 // (-0.87823314f + 5573 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5574 // 5575 // error 0.0000023660568, which is better than 18 bits 5576 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5577 getF32Constant(DAG, 0xbc91e5ac, dl)); 5578 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5579 getF32Constant(DAG, 0x3e4350aa, dl)); 5580 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5581 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5582 getF32Constant(DAG, 0x3f60d3e3, dl)); 5583 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5584 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5585 getF32Constant(DAG, 0x4011cdf0, dl)); 5586 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5587 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5588 getF32Constant(DAG, 0x406cfd1c, dl)); 5589 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5590 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5591 getF32Constant(DAG, 0x408797cb, dl)); 5592 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5593 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5594 getF32Constant(DAG, 0x4006dcab, dl)); 5595 } 5596 5597 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5598 } 5599 5600 // No special expansion. 5601 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5602 } 5603 5604 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5605 /// limited-precision mode. 5606 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5607 const TargetLowering &TLI, SDNodeFlags Flags) { 5608 // TODO: What fast-math-flags should be set on the floating-point nodes? 5609 5610 if (Op.getValueType() == MVT::f32 && 5611 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5612 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5613 5614 // Get the exponent. 5615 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5616 5617 // Get the significand and build it into a floating-point number with 5618 // exponent of 1. 5619 SDValue X = GetSignificand(DAG, Op1, dl); 5620 5621 // Different possible minimax approximations of significand in 5622 // floating-point for various degrees of accuracy over [1,2]. 5623 SDValue Log2ofMantissa; 5624 if (LimitFloatPrecision <= 6) { 5625 // For floating-point precision of 6: 5626 // 5627 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5628 // 5629 // error 0.0049451742, which is more than 7 bits 5630 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5631 getF32Constant(DAG, 0xbeb08fe0, dl)); 5632 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5633 getF32Constant(DAG, 0x40019463, dl)); 5634 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5635 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5636 getF32Constant(DAG, 0x3fd6633d, dl)); 5637 } else if (LimitFloatPrecision <= 12) { 5638 // For floating-point precision of 12: 5639 // 5640 // Log2ofMantissa = 5641 // -2.51285454f + 5642 // (4.07009056f + 5643 // (-2.12067489f + 5644 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5645 // 5646 // error 0.0000876136000, which is better than 13 bits 5647 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5648 getF32Constant(DAG, 0xbda7262e, dl)); 5649 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5650 getF32Constant(DAG, 0x3f25280b, dl)); 5651 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5652 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5653 getF32Constant(DAG, 0x4007b923, dl)); 5654 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5655 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5656 getF32Constant(DAG, 0x40823e2f, dl)); 5657 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5658 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5659 getF32Constant(DAG, 0x4020d29c, dl)); 5660 } else { // LimitFloatPrecision <= 18 5661 // For floating-point precision of 18: 5662 // 5663 // Log2ofMantissa = 5664 // -3.0400495f + 5665 // (6.1129976f + 5666 // (-5.3420409f + 5667 // (3.2865683f + 5668 // (-1.2669343f + 5669 // (0.27515199f - 5670 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5671 // 5672 // error 0.0000018516, which is better than 18 bits 5673 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5674 getF32Constant(DAG, 0xbcd2769e, dl)); 5675 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5676 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5677 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5678 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5679 getF32Constant(DAG, 0x3fa22ae7, dl)); 5680 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5681 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5682 getF32Constant(DAG, 0x40525723, dl)); 5683 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5684 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5685 getF32Constant(DAG, 0x40aaf200, dl)); 5686 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5687 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5688 getF32Constant(DAG, 0x40c39dad, dl)); 5689 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5690 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5691 getF32Constant(DAG, 0x4042902c, dl)); 5692 } 5693 5694 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5695 } 5696 5697 // No special expansion. 5698 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5699 } 5700 5701 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5702 /// limited-precision mode. 5703 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5704 const TargetLowering &TLI, SDNodeFlags Flags) { 5705 // TODO: What fast-math-flags should be set on the floating-point nodes? 5706 5707 if (Op.getValueType() == MVT::f32 && 5708 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5709 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5710 5711 // Scale the exponent by log10(2) [0.30102999f]. 5712 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5713 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5714 getF32Constant(DAG, 0x3e9a209a, dl)); 5715 5716 // Get the significand and build it into a floating-point number with 5717 // exponent of 1. 5718 SDValue X = GetSignificand(DAG, Op1, dl); 5719 5720 SDValue Log10ofMantissa; 5721 if (LimitFloatPrecision <= 6) { 5722 // For floating-point precision of 6: 5723 // 5724 // Log10ofMantissa = 5725 // -0.50419619f + 5726 // (0.60948995f - 0.10380950f * x) * x; 5727 // 5728 // error 0.0014886165, which is 6 bits 5729 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5730 getF32Constant(DAG, 0xbdd49a13, dl)); 5731 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5732 getF32Constant(DAG, 0x3f1c0789, dl)); 5733 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5734 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5735 getF32Constant(DAG, 0x3f011300, dl)); 5736 } else if (LimitFloatPrecision <= 12) { 5737 // For floating-point precision of 12: 5738 // 5739 // Log10ofMantissa = 5740 // -0.64831180f + 5741 // (0.91751397f + 5742 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5743 // 5744 // error 0.00019228036, which is better than 12 bits 5745 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5746 getF32Constant(DAG, 0x3d431f31, dl)); 5747 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5748 getF32Constant(DAG, 0x3ea21fb2, dl)); 5749 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5750 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5751 getF32Constant(DAG, 0x3f6ae232, dl)); 5752 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5753 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5754 getF32Constant(DAG, 0x3f25f7c3, dl)); 5755 } else { // LimitFloatPrecision <= 18 5756 // For floating-point precision of 18: 5757 // 5758 // Log10ofMantissa = 5759 // -0.84299375f + 5760 // (1.5327582f + 5761 // (-1.0688956f + 5762 // (0.49102474f + 5763 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5764 // 5765 // error 0.0000037995730, which is better than 18 bits 5766 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5767 getF32Constant(DAG, 0x3c5d51ce, dl)); 5768 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5769 getF32Constant(DAG, 0x3e00685a, dl)); 5770 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5771 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5772 getF32Constant(DAG, 0x3efb6798, dl)); 5773 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5774 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5775 getF32Constant(DAG, 0x3f88d192, dl)); 5776 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5777 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5778 getF32Constant(DAG, 0x3fc4316c, dl)); 5779 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5780 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5781 getF32Constant(DAG, 0x3f57ce70, dl)); 5782 } 5783 5784 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5785 } 5786 5787 // No special expansion. 5788 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5789 } 5790 5791 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5792 /// limited-precision mode. 5793 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5794 const TargetLowering &TLI, SDNodeFlags Flags) { 5795 if (Op.getValueType() == MVT::f32 && 5796 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5797 return getLimitedPrecisionExp2(Op, dl, DAG); 5798 5799 // No special expansion. 5800 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5801 } 5802 5803 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5804 /// limited-precision mode with x == 10.0f. 5805 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5806 SelectionDAG &DAG, const TargetLowering &TLI, 5807 SDNodeFlags Flags) { 5808 bool IsExp10 = false; 5809 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5810 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5811 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5812 APFloat Ten(10.0f); 5813 IsExp10 = LHSC->isExactlyValue(Ten); 5814 } 5815 } 5816 5817 // TODO: What fast-math-flags should be set on the FMUL node? 5818 if (IsExp10) { 5819 // Put the exponent in the right bit position for later addition to the 5820 // final result: 5821 // 5822 // #define LOG2OF10 3.3219281f 5823 // t0 = Op * LOG2OF10; 5824 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5825 getF32Constant(DAG, 0x40549a78, dl)); 5826 return getLimitedPrecisionExp2(t0, dl, DAG); 5827 } 5828 5829 // No special expansion. 5830 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5831 } 5832 5833 /// ExpandPowI - Expand a llvm.powi intrinsic. 5834 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5835 SelectionDAG &DAG) { 5836 // If RHS is a constant, we can expand this out to a multiplication tree if 5837 // it's beneficial on the target, otherwise we end up lowering to a call to 5838 // __powidf2 (for example). 5839 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5840 unsigned Val = RHSC->getSExtValue(); 5841 5842 // powi(x, 0) -> 1.0 5843 if (Val == 0) 5844 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5845 5846 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5847 Val, DAG.shouldOptForSize())) { 5848 // Get the exponent as a positive value. 5849 if ((int)Val < 0) 5850 Val = -Val; 5851 // We use the simple binary decomposition method to generate the multiply 5852 // sequence. There are more optimal ways to do this (for example, 5853 // powi(x,15) generates one more multiply than it should), but this has 5854 // the benefit of being both really simple and much better than a libcall. 5855 SDValue Res; // Logically starts equal to 1.0 5856 SDValue CurSquare = LHS; 5857 // TODO: Intrinsics should have fast-math-flags that propagate to these 5858 // nodes. 5859 while (Val) { 5860 if (Val & 1) { 5861 if (Res.getNode()) 5862 Res = 5863 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5864 else 5865 Res = CurSquare; // 1.0*CurSquare. 5866 } 5867 5868 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5869 CurSquare, CurSquare); 5870 Val >>= 1; 5871 } 5872 5873 // If the original was negative, invert the result, producing 1/(x*x*x). 5874 if (RHSC->getSExtValue() < 0) 5875 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5876 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5877 return Res; 5878 } 5879 } 5880 5881 // Otherwise, expand to a libcall. 5882 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5883 } 5884 5885 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5886 SDValue LHS, SDValue RHS, SDValue Scale, 5887 SelectionDAG &DAG, const TargetLowering &TLI) { 5888 EVT VT = LHS.getValueType(); 5889 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5890 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5891 LLVMContext &Ctx = *DAG.getContext(); 5892 5893 // If the type is legal but the operation isn't, this node might survive all 5894 // the way to operation legalization. If we end up there and we do not have 5895 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5896 // node. 5897 5898 // Coax the legalizer into expanding the node during type legalization instead 5899 // by bumping the size by one bit. This will force it to Promote, enabling the 5900 // early expansion and avoiding the need to expand later. 5901 5902 // We don't have to do this if Scale is 0; that can always be expanded, unless 5903 // it's a saturating signed operation. Those can experience true integer 5904 // division overflow, a case which we must avoid. 5905 5906 // FIXME: We wouldn't have to do this (or any of the early 5907 // expansion/promotion) if it was possible to expand a libcall of an 5908 // illegal type during operation legalization. But it's not, so things 5909 // get a bit hacky. 5910 unsigned ScaleInt = Scale->getAsZExtVal(); 5911 if ((ScaleInt > 0 || (Saturating && Signed)) && 5912 (TLI.isTypeLegal(VT) || 5913 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5914 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5915 Opcode, VT, ScaleInt); 5916 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5917 EVT PromVT; 5918 if (VT.isScalarInteger()) 5919 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5920 else if (VT.isVector()) { 5921 PromVT = VT.getVectorElementType(); 5922 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5923 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5924 } else 5925 llvm_unreachable("Wrong VT for DIVFIX?"); 5926 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5927 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5928 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5929 // For saturating operations, we need to shift up the LHS to get the 5930 // proper saturation width, and then shift down again afterwards. 5931 if (Saturating) 5932 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5933 DAG.getConstant(1, DL, ShiftTy)); 5934 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5935 if (Saturating) 5936 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5937 DAG.getConstant(1, DL, ShiftTy)); 5938 return DAG.getZExtOrTrunc(Res, DL, VT); 5939 } 5940 } 5941 5942 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5943 } 5944 5945 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5946 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5947 static void 5948 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5949 const SDValue &N) { 5950 switch (N.getOpcode()) { 5951 case ISD::CopyFromReg: { 5952 SDValue Op = N.getOperand(1); 5953 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5954 Op.getValueType().getSizeInBits()); 5955 return; 5956 } 5957 case ISD::BITCAST: 5958 case ISD::AssertZext: 5959 case ISD::AssertSext: 5960 case ISD::TRUNCATE: 5961 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5962 return; 5963 case ISD::BUILD_PAIR: 5964 case ISD::BUILD_VECTOR: 5965 case ISD::CONCAT_VECTORS: 5966 for (SDValue Op : N->op_values()) 5967 getUnderlyingArgRegs(Regs, Op); 5968 return; 5969 default: 5970 return; 5971 } 5972 } 5973 5974 /// If the DbgValueInst is a dbg_value of a function argument, create the 5975 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5976 /// instruction selection, they will be inserted to the entry BB. 5977 /// We don't currently support this for variadic dbg_values, as they shouldn't 5978 /// appear for function arguments or in the prologue. 5979 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5980 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5981 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5982 const Argument *Arg = dyn_cast<Argument>(V); 5983 if (!Arg) 5984 return false; 5985 5986 MachineFunction &MF = DAG.getMachineFunction(); 5987 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5988 5989 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5990 // we've been asked to pursue. 5991 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5992 bool Indirect) { 5993 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5994 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5995 // pointing at the VReg, which will be patched up later. 5996 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5997 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5998 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5999 /* isKill */ false, /* isDead */ false, 6000 /* isUndef */ false, /* isEarlyClobber */ false, 6001 /* SubReg */ 0, /* isDebug */ true)}); 6002 6003 auto *NewDIExpr = FragExpr; 6004 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 6005 // the DIExpression. 6006 if (Indirect) 6007 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 6008 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 6009 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 6010 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 6011 } else { 6012 // Create a completely standard DBG_VALUE. 6013 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 6014 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 6015 } 6016 }; 6017 6018 if (Kind == FuncArgumentDbgValueKind::Value) { 6019 // ArgDbgValues are hoisted to the beginning of the entry block. So we 6020 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 6021 // the entry block. 6022 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 6023 if (!IsInEntryBlock) 6024 return false; 6025 6026 // ArgDbgValues are hoisted to the beginning of the entry block. So we 6027 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 6028 // variable that also is a param. 6029 // 6030 // Although, if we are at the top of the entry block already, we can still 6031 // emit using ArgDbgValue. This might catch some situations when the 6032 // dbg.value refers to an argument that isn't used in the entry block, so 6033 // any CopyToReg node would be optimized out and the only way to express 6034 // this DBG_VALUE is by using the physical reg (or FI) as done in this 6035 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 6036 // we should only emit as ArgDbgValue if the Variable is an argument to the 6037 // current function, and the dbg.value intrinsic is found in the entry 6038 // block. 6039 bool VariableIsFunctionInputArg = Variable->isParameter() && 6040 !DL->getInlinedAt(); 6041 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 6042 if (!IsInPrologue && !VariableIsFunctionInputArg) 6043 return false; 6044 6045 // Here we assume that a function argument on IR level only can be used to 6046 // describe one input parameter on source level. If we for example have 6047 // source code like this 6048 // 6049 // struct A { long x, y; }; 6050 // void foo(struct A a, long b) { 6051 // ... 6052 // b = a.x; 6053 // ... 6054 // } 6055 // 6056 // and IR like this 6057 // 6058 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 6059 // entry: 6060 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 6061 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 6062 // call void @llvm.dbg.value(metadata i32 %b, "b", 6063 // ... 6064 // call void @llvm.dbg.value(metadata i32 %a1, "b" 6065 // ... 6066 // 6067 // then the last dbg.value is describing a parameter "b" using a value that 6068 // is an argument. But since we already has used %a1 to describe a parameter 6069 // we should not handle that last dbg.value here (that would result in an 6070 // incorrect hoisting of the DBG_VALUE to the function entry). 6071 // Notice that we allow one dbg.value per IR level argument, to accommodate 6072 // for the situation with fragments above. 6073 // If there is no node for the value being handled, we return true to skip 6074 // the normal generation of debug info, as it would kill existing debug 6075 // info for the parameter in case of duplicates. 6076 if (VariableIsFunctionInputArg) { 6077 unsigned ArgNo = Arg->getArgNo(); 6078 if (ArgNo >= FuncInfo.DescribedArgs.size()) 6079 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 6080 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 6081 return !NodeMap[V].getNode(); 6082 FuncInfo.DescribedArgs.set(ArgNo); 6083 } 6084 } 6085 6086 bool IsIndirect = false; 6087 std::optional<MachineOperand> Op; 6088 // Some arguments' frame index is recorded during argument lowering. 6089 int FI = FuncInfo.getArgumentFrameIndex(Arg); 6090 if (FI != std::numeric_limits<int>::max()) 6091 Op = MachineOperand::CreateFI(FI); 6092 6093 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 6094 if (!Op && N.getNode()) { 6095 getUnderlyingArgRegs(ArgRegsAndSizes, N); 6096 Register Reg; 6097 if (ArgRegsAndSizes.size() == 1) 6098 Reg = ArgRegsAndSizes.front().first; 6099 6100 if (Reg && Reg.isVirtual()) { 6101 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6102 Register PR = RegInfo.getLiveInPhysReg(Reg); 6103 if (PR) 6104 Reg = PR; 6105 } 6106 if (Reg) { 6107 Op = MachineOperand::CreateReg(Reg, false); 6108 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6109 } 6110 } 6111 6112 if (!Op && N.getNode()) { 6113 // Check if frame index is available. 6114 SDValue LCandidate = peekThroughBitcasts(N); 6115 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 6116 if (FrameIndexSDNode *FINode = 6117 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 6118 Op = MachineOperand::CreateFI(FINode->getIndex()); 6119 } 6120 6121 if (!Op) { 6122 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 6123 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 6124 SplitRegs) { 6125 unsigned Offset = 0; 6126 for (const auto &RegAndSize : SplitRegs) { 6127 // If the expression is already a fragment, the current register 6128 // offset+size might extend beyond the fragment. In this case, only 6129 // the register bits that are inside the fragment are relevant. 6130 int RegFragmentSizeInBits = RegAndSize.second; 6131 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 6132 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 6133 // The register is entirely outside the expression fragment, 6134 // so is irrelevant for debug info. 6135 if (Offset >= ExprFragmentSizeInBits) 6136 break; 6137 // The register is partially outside the expression fragment, only 6138 // the low bits within the fragment are relevant for debug info. 6139 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 6140 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 6141 } 6142 } 6143 6144 auto FragmentExpr = DIExpression::createFragmentExpression( 6145 Expr, Offset, RegFragmentSizeInBits); 6146 Offset += RegAndSize.second; 6147 // If a valid fragment expression cannot be created, the variable's 6148 // correct value cannot be determined and so it is set as Undef. 6149 if (!FragmentExpr) { 6150 SDDbgValue *SDV = DAG.getConstantDbgValue( 6151 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 6152 DAG.AddDbgValue(SDV, false); 6153 continue; 6154 } 6155 MachineInstr *NewMI = 6156 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 6157 Kind != FuncArgumentDbgValueKind::Value); 6158 FuncInfo.ArgDbgValues.push_back(NewMI); 6159 } 6160 }; 6161 6162 // Check if ValueMap has reg number. 6163 DenseMap<const Value *, Register>::const_iterator 6164 VMI = FuncInfo.ValueMap.find(V); 6165 if (VMI != FuncInfo.ValueMap.end()) { 6166 const auto &TLI = DAG.getTargetLoweringInfo(); 6167 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 6168 V->getType(), std::nullopt); 6169 if (RFV.occupiesMultipleRegs()) { 6170 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 6171 return true; 6172 } 6173 6174 Op = MachineOperand::CreateReg(VMI->second, false); 6175 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6176 } else if (ArgRegsAndSizes.size() > 1) { 6177 // This was split due to the calling convention, and no virtual register 6178 // mapping exists for the value. 6179 splitMultiRegDbgValue(ArgRegsAndSizes); 6180 return true; 6181 } 6182 } 6183 6184 if (!Op) 6185 return false; 6186 6187 assert(Variable->isValidLocationForIntrinsic(DL) && 6188 "Expected inlined-at fields to agree"); 6189 MachineInstr *NewMI = nullptr; 6190 6191 if (Op->isReg()) 6192 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 6193 else 6194 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 6195 Variable, Expr); 6196 6197 // Otherwise, use ArgDbgValues. 6198 FuncInfo.ArgDbgValues.push_back(NewMI); 6199 return true; 6200 } 6201 6202 /// Return the appropriate SDDbgValue based on N. 6203 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 6204 DILocalVariable *Variable, 6205 DIExpression *Expr, 6206 const DebugLoc &dl, 6207 unsigned DbgSDNodeOrder) { 6208 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 6209 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 6210 // stack slot locations. 6211 // 6212 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 6213 // debug values here after optimization: 6214 // 6215 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 6216 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 6217 // 6218 // Both describe the direct values of their associated variables. 6219 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 6220 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6221 } 6222 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 6223 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6224 } 6225 6226 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 6227 switch (Intrinsic) { 6228 case Intrinsic::smul_fix: 6229 return ISD::SMULFIX; 6230 case Intrinsic::umul_fix: 6231 return ISD::UMULFIX; 6232 case Intrinsic::smul_fix_sat: 6233 return ISD::SMULFIXSAT; 6234 case Intrinsic::umul_fix_sat: 6235 return ISD::UMULFIXSAT; 6236 case Intrinsic::sdiv_fix: 6237 return ISD::SDIVFIX; 6238 case Intrinsic::udiv_fix: 6239 return ISD::UDIVFIX; 6240 case Intrinsic::sdiv_fix_sat: 6241 return ISD::SDIVFIXSAT; 6242 case Intrinsic::udiv_fix_sat: 6243 return ISD::UDIVFIXSAT; 6244 default: 6245 llvm_unreachable("Unhandled fixed point intrinsic"); 6246 } 6247 } 6248 6249 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6250 const char *FunctionName) { 6251 assert(FunctionName && "FunctionName must not be nullptr"); 6252 SDValue Callee = DAG.getExternalSymbol( 6253 FunctionName, 6254 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6255 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6256 } 6257 6258 /// Given a @llvm.call.preallocated.setup, return the corresponding 6259 /// preallocated call. 6260 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6261 assert(cast<CallBase>(PreallocatedSetup) 6262 ->getCalledFunction() 6263 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6264 "expected call_preallocated_setup Value"); 6265 for (const auto *U : PreallocatedSetup->users()) { 6266 auto *UseCall = cast<CallBase>(U); 6267 const Function *Fn = UseCall->getCalledFunction(); 6268 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6269 return UseCall; 6270 } 6271 } 6272 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6273 } 6274 6275 /// If DI is a debug value with an EntryValue expression, lower it using the 6276 /// corresponding physical register of the associated Argument value 6277 /// (guaranteed to exist by the verifier). 6278 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6279 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6280 DIExpression *Expr, DebugLoc DbgLoc) { 6281 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6282 return false; 6283 6284 // These properties are guaranteed by the verifier. 6285 const Argument *Arg = cast<Argument>(Values[0]); 6286 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6287 6288 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6289 if (ArgIt == FuncInfo.ValueMap.end()) { 6290 LLVM_DEBUG( 6291 dbgs() << "Dropping dbg.value: expression is entry_value but " 6292 "couldn't find an associated register for the Argument\n"); 6293 return true; 6294 } 6295 Register ArgVReg = ArgIt->getSecond(); 6296 6297 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6298 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6299 SDDbgValue *SDV = DAG.getVRegDbgValue( 6300 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6301 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6302 return true; 6303 } 6304 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6305 "couldn't find a physical register\n"); 6306 return true; 6307 } 6308 6309 /// Lower the call to the specified intrinsic function. 6310 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I, 6311 unsigned Intrinsic) { 6312 SDLoc sdl = getCurSDLoc(); 6313 switch (Intrinsic) { 6314 case Intrinsic::experimental_convergence_anchor: 6315 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped)); 6316 break; 6317 case Intrinsic::experimental_convergence_entry: 6318 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped)); 6319 break; 6320 case Intrinsic::experimental_convergence_loop: { 6321 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl); 6322 auto *Token = Bundle->Inputs[0].get(); 6323 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped, 6324 getValue(Token))); 6325 break; 6326 } 6327 } 6328 } 6329 6330 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I, 6331 unsigned IntrinsicID) { 6332 // For now, we're only lowering an 'add' histogram. 6333 // We can add others later, e.g. saturating adds, min/max. 6334 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add && 6335 "Tried to lower unsupported histogram type"); 6336 SDLoc sdl = getCurSDLoc(); 6337 Value *Ptr = I.getOperand(0); 6338 SDValue Inc = getValue(I.getOperand(1)); 6339 SDValue Mask = getValue(I.getOperand(2)); 6340 6341 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6342 DataLayout TargetDL = DAG.getDataLayout(); 6343 EVT VT = Inc.getValueType(); 6344 Align Alignment = DAG.getEVTAlign(VT); 6345 6346 const MDNode *Ranges = getRangeMetadata(I); 6347 6348 SDValue Root = DAG.getRoot(); 6349 SDValue Base; 6350 SDValue Index; 6351 ISD::MemIndexType IndexType; 6352 SDValue Scale; 6353 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 6354 I.getParent(), VT.getScalarStoreSize()); 6355 6356 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 6357 6358 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6359 MachinePointerInfo(AS), 6360 MachineMemOperand::MOLoad | MachineMemOperand::MOStore, 6361 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 6362 6363 if (!UniformBase) { 6364 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6365 Index = getValue(Ptr); 6366 IndexType = ISD::SIGNED_SCALED; 6367 Scale = 6368 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6369 } 6370 6371 EVT IdxVT = Index.getValueType(); 6372 EVT EltTy = IdxVT.getVectorElementType(); 6373 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 6374 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 6375 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 6376 } 6377 6378 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32); 6379 6380 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID}; 6381 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl, 6382 Ops, MMO, IndexType); 6383 6384 setValue(&I, Histogram); 6385 DAG.setRoot(Histogram); 6386 } 6387 6388 /// Lower the call to the specified intrinsic function. 6389 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6390 unsigned Intrinsic) { 6391 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6392 SDLoc sdl = getCurSDLoc(); 6393 DebugLoc dl = getCurDebugLoc(); 6394 SDValue Res; 6395 6396 SDNodeFlags Flags; 6397 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6398 Flags.copyFMF(*FPOp); 6399 6400 switch (Intrinsic) { 6401 default: 6402 // By default, turn this into a target intrinsic node. 6403 visitTargetIntrinsic(I, Intrinsic); 6404 return; 6405 case Intrinsic::vscale: { 6406 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6407 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6408 return; 6409 } 6410 case Intrinsic::vastart: visitVAStart(I); return; 6411 case Intrinsic::vaend: visitVAEnd(I); return; 6412 case Intrinsic::vacopy: visitVACopy(I); return; 6413 case Intrinsic::returnaddress: 6414 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6415 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6416 getValue(I.getArgOperand(0)))); 6417 return; 6418 case Intrinsic::addressofreturnaddress: 6419 setValue(&I, 6420 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6421 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6422 return; 6423 case Intrinsic::sponentry: 6424 setValue(&I, 6425 DAG.getNode(ISD::SPONENTRY, sdl, 6426 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6427 return; 6428 case Intrinsic::frameaddress: 6429 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6430 TLI.getFrameIndexTy(DAG.getDataLayout()), 6431 getValue(I.getArgOperand(0)))); 6432 return; 6433 case Intrinsic::read_volatile_register: 6434 case Intrinsic::read_register: { 6435 Value *Reg = I.getArgOperand(0); 6436 SDValue Chain = getRoot(); 6437 SDValue RegName = 6438 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6439 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6440 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6441 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6442 setValue(&I, Res); 6443 DAG.setRoot(Res.getValue(1)); 6444 return; 6445 } 6446 case Intrinsic::write_register: { 6447 Value *Reg = I.getArgOperand(0); 6448 Value *RegValue = I.getArgOperand(1); 6449 SDValue Chain = getRoot(); 6450 SDValue RegName = 6451 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6452 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6453 RegName, getValue(RegValue))); 6454 return; 6455 } 6456 case Intrinsic::memcpy: { 6457 const auto &MCI = cast<MemCpyInst>(I); 6458 SDValue Op1 = getValue(I.getArgOperand(0)); 6459 SDValue Op2 = getValue(I.getArgOperand(1)); 6460 SDValue Op3 = getValue(I.getArgOperand(2)); 6461 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6462 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6463 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6464 Align Alignment = std::min(DstAlign, SrcAlign); 6465 bool isVol = MCI.isVolatile(); 6466 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6467 // node. 6468 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6469 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6470 /* AlwaysInline */ false, &I, std::nullopt, 6471 MachinePointerInfo(I.getArgOperand(0)), 6472 MachinePointerInfo(I.getArgOperand(1)), 6473 I.getAAMetadata(), AA); 6474 updateDAGForMaybeTailCall(MC); 6475 return; 6476 } 6477 case Intrinsic::memcpy_inline: { 6478 const auto &MCI = cast<MemCpyInlineInst>(I); 6479 SDValue Dst = getValue(I.getArgOperand(0)); 6480 SDValue Src = getValue(I.getArgOperand(1)); 6481 SDValue Size = getValue(I.getArgOperand(2)); 6482 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6483 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6484 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6485 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6486 Align Alignment = std::min(DstAlign, SrcAlign); 6487 bool isVol = MCI.isVolatile(); 6488 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6489 // node. 6490 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6491 /* AlwaysInline */ true, &I, std::nullopt, 6492 MachinePointerInfo(I.getArgOperand(0)), 6493 MachinePointerInfo(I.getArgOperand(1)), 6494 I.getAAMetadata(), AA); 6495 updateDAGForMaybeTailCall(MC); 6496 return; 6497 } 6498 case Intrinsic::memset: { 6499 const auto &MSI = cast<MemSetInst>(I); 6500 SDValue Op1 = getValue(I.getArgOperand(0)); 6501 SDValue Op2 = getValue(I.getArgOperand(1)); 6502 SDValue Op3 = getValue(I.getArgOperand(2)); 6503 // @llvm.memset defines 0 and 1 to both mean no alignment. 6504 Align Alignment = MSI.getDestAlign().valueOrOne(); 6505 bool isVol = MSI.isVolatile(); 6506 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6507 SDValue MS = DAG.getMemset( 6508 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6509 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6510 updateDAGForMaybeTailCall(MS); 6511 return; 6512 } 6513 case Intrinsic::memset_inline: { 6514 const auto &MSII = cast<MemSetInlineInst>(I); 6515 SDValue Dst = getValue(I.getArgOperand(0)); 6516 SDValue Value = getValue(I.getArgOperand(1)); 6517 SDValue Size = getValue(I.getArgOperand(2)); 6518 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6519 // @llvm.memset defines 0 and 1 to both mean no alignment. 6520 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6521 bool isVol = MSII.isVolatile(); 6522 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6523 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6524 /* AlwaysInline */ true, &I, 6525 MachinePointerInfo(I.getArgOperand(0)), 6526 I.getAAMetadata()); 6527 updateDAGForMaybeTailCall(MC); 6528 return; 6529 } 6530 case Intrinsic::memmove: { 6531 const auto &MMI = cast<MemMoveInst>(I); 6532 SDValue Op1 = getValue(I.getArgOperand(0)); 6533 SDValue Op2 = getValue(I.getArgOperand(1)); 6534 SDValue Op3 = getValue(I.getArgOperand(2)); 6535 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6536 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6537 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6538 Align Alignment = std::min(DstAlign, SrcAlign); 6539 bool isVol = MMI.isVolatile(); 6540 // FIXME: Support passing different dest/src alignments to the memmove DAG 6541 // node. 6542 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6543 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I, 6544 /* OverrideTailCall */ std::nullopt, 6545 MachinePointerInfo(I.getArgOperand(0)), 6546 MachinePointerInfo(I.getArgOperand(1)), 6547 I.getAAMetadata(), AA); 6548 updateDAGForMaybeTailCall(MM); 6549 return; 6550 } 6551 case Intrinsic::memcpy_element_unordered_atomic: { 6552 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6553 SDValue Dst = getValue(MI.getRawDest()); 6554 SDValue Src = getValue(MI.getRawSource()); 6555 SDValue Length = getValue(MI.getLength()); 6556 6557 Type *LengthTy = MI.getLength()->getType(); 6558 unsigned ElemSz = MI.getElementSizeInBytes(); 6559 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6560 SDValue MC = 6561 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6562 isTC, MachinePointerInfo(MI.getRawDest()), 6563 MachinePointerInfo(MI.getRawSource())); 6564 updateDAGForMaybeTailCall(MC); 6565 return; 6566 } 6567 case Intrinsic::memmove_element_unordered_atomic: { 6568 auto &MI = cast<AtomicMemMoveInst>(I); 6569 SDValue Dst = getValue(MI.getRawDest()); 6570 SDValue Src = getValue(MI.getRawSource()); 6571 SDValue Length = getValue(MI.getLength()); 6572 6573 Type *LengthTy = MI.getLength()->getType(); 6574 unsigned ElemSz = MI.getElementSizeInBytes(); 6575 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6576 SDValue MC = 6577 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6578 isTC, MachinePointerInfo(MI.getRawDest()), 6579 MachinePointerInfo(MI.getRawSource())); 6580 updateDAGForMaybeTailCall(MC); 6581 return; 6582 } 6583 case Intrinsic::memset_element_unordered_atomic: { 6584 auto &MI = cast<AtomicMemSetInst>(I); 6585 SDValue Dst = getValue(MI.getRawDest()); 6586 SDValue Val = getValue(MI.getValue()); 6587 SDValue Length = getValue(MI.getLength()); 6588 6589 Type *LengthTy = MI.getLength()->getType(); 6590 unsigned ElemSz = MI.getElementSizeInBytes(); 6591 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6592 SDValue MC = 6593 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6594 isTC, MachinePointerInfo(MI.getRawDest())); 6595 updateDAGForMaybeTailCall(MC); 6596 return; 6597 } 6598 case Intrinsic::call_preallocated_setup: { 6599 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6600 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6601 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6602 getRoot(), SrcValue); 6603 setValue(&I, Res); 6604 DAG.setRoot(Res); 6605 return; 6606 } 6607 case Intrinsic::call_preallocated_arg: { 6608 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6609 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6610 SDValue Ops[3]; 6611 Ops[0] = getRoot(); 6612 Ops[1] = SrcValue; 6613 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6614 MVT::i32); // arg index 6615 SDValue Res = DAG.getNode( 6616 ISD::PREALLOCATED_ARG, sdl, 6617 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6618 setValue(&I, Res); 6619 DAG.setRoot(Res.getValue(1)); 6620 return; 6621 } 6622 case Intrinsic::dbg_declare: { 6623 const auto &DI = cast<DbgDeclareInst>(I); 6624 // Debug intrinsics are handled separately in assignment tracking mode. 6625 // Some intrinsics are handled right after Argument lowering. 6626 if (AssignmentTrackingEnabled || 6627 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6628 return; 6629 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6630 DILocalVariable *Variable = DI.getVariable(); 6631 DIExpression *Expression = DI.getExpression(); 6632 dropDanglingDebugInfo(Variable, Expression); 6633 // Assume dbg.declare can not currently use DIArgList, i.e. 6634 // it is non-variadic. 6635 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6636 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6637 DI.getDebugLoc()); 6638 return; 6639 } 6640 case Intrinsic::dbg_label: { 6641 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6642 DILabel *Label = DI.getLabel(); 6643 assert(Label && "Missing label"); 6644 6645 SDDbgLabel *SDV; 6646 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6647 DAG.AddDbgLabel(SDV); 6648 return; 6649 } 6650 case Intrinsic::dbg_assign: { 6651 // Debug intrinsics are handled separately in assignment tracking mode. 6652 if (AssignmentTrackingEnabled) 6653 return; 6654 // If assignment tracking hasn't been enabled then fall through and treat 6655 // the dbg.assign as a dbg.value. 6656 [[fallthrough]]; 6657 } 6658 case Intrinsic::dbg_value: { 6659 // Debug intrinsics are handled separately in assignment tracking mode. 6660 if (AssignmentTrackingEnabled) 6661 return; 6662 const DbgValueInst &DI = cast<DbgValueInst>(I); 6663 assert(DI.getVariable() && "Missing variable"); 6664 6665 DILocalVariable *Variable = DI.getVariable(); 6666 DIExpression *Expression = DI.getExpression(); 6667 dropDanglingDebugInfo(Variable, Expression); 6668 6669 if (DI.isKillLocation()) { 6670 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6671 return; 6672 } 6673 6674 SmallVector<Value *, 4> Values(DI.getValues()); 6675 if (Values.empty()) 6676 return; 6677 6678 bool IsVariadic = DI.hasArgList(); 6679 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6680 SDNodeOrder, IsVariadic)) 6681 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6682 DI.getDebugLoc(), SDNodeOrder); 6683 return; 6684 } 6685 6686 case Intrinsic::eh_typeid_for: { 6687 // Find the type id for the given typeinfo. 6688 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6689 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6690 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6691 setValue(&I, Res); 6692 return; 6693 } 6694 6695 case Intrinsic::eh_return_i32: 6696 case Intrinsic::eh_return_i64: 6697 DAG.getMachineFunction().setCallsEHReturn(true); 6698 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6699 MVT::Other, 6700 getControlRoot(), 6701 getValue(I.getArgOperand(0)), 6702 getValue(I.getArgOperand(1)))); 6703 return; 6704 case Intrinsic::eh_unwind_init: 6705 DAG.getMachineFunction().setCallsUnwindInit(true); 6706 return; 6707 case Intrinsic::eh_dwarf_cfa: 6708 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6709 TLI.getPointerTy(DAG.getDataLayout()), 6710 getValue(I.getArgOperand(0)))); 6711 return; 6712 case Intrinsic::eh_sjlj_callsite: { 6713 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6714 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6715 6716 FuncInfo.setCurrentCallSite(CI->getZExtValue()); 6717 return; 6718 } 6719 case Intrinsic::eh_sjlj_functioncontext: { 6720 // Get and store the index of the function context. 6721 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6722 AllocaInst *FnCtx = 6723 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6724 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6725 MFI.setFunctionContextIndex(FI); 6726 return; 6727 } 6728 case Intrinsic::eh_sjlj_setjmp: { 6729 SDValue Ops[2]; 6730 Ops[0] = getRoot(); 6731 Ops[1] = getValue(I.getArgOperand(0)); 6732 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6733 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6734 setValue(&I, Op.getValue(0)); 6735 DAG.setRoot(Op.getValue(1)); 6736 return; 6737 } 6738 case Intrinsic::eh_sjlj_longjmp: 6739 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6740 getRoot(), getValue(I.getArgOperand(0)))); 6741 return; 6742 case Intrinsic::eh_sjlj_setup_dispatch: 6743 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6744 getRoot())); 6745 return; 6746 case Intrinsic::masked_gather: 6747 visitMaskedGather(I); 6748 return; 6749 case Intrinsic::masked_load: 6750 visitMaskedLoad(I); 6751 return; 6752 case Intrinsic::masked_scatter: 6753 visitMaskedScatter(I); 6754 return; 6755 case Intrinsic::masked_store: 6756 visitMaskedStore(I); 6757 return; 6758 case Intrinsic::masked_expandload: 6759 visitMaskedLoad(I, true /* IsExpanding */); 6760 return; 6761 case Intrinsic::masked_compressstore: 6762 visitMaskedStore(I, true /* IsCompressing */); 6763 return; 6764 case Intrinsic::powi: 6765 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6766 getValue(I.getArgOperand(1)), DAG)); 6767 return; 6768 case Intrinsic::log: 6769 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6770 return; 6771 case Intrinsic::log2: 6772 setValue(&I, 6773 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6774 return; 6775 case Intrinsic::log10: 6776 setValue(&I, 6777 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6778 return; 6779 case Intrinsic::exp: 6780 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6781 return; 6782 case Intrinsic::exp2: 6783 setValue(&I, 6784 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6785 return; 6786 case Intrinsic::pow: 6787 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6788 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6789 return; 6790 case Intrinsic::sqrt: 6791 case Intrinsic::fabs: 6792 case Intrinsic::sin: 6793 case Intrinsic::cos: 6794 case Intrinsic::tan: 6795 case Intrinsic::asin: 6796 case Intrinsic::acos: 6797 case Intrinsic::atan: 6798 case Intrinsic::sinh: 6799 case Intrinsic::cosh: 6800 case Intrinsic::tanh: 6801 case Intrinsic::exp10: 6802 case Intrinsic::floor: 6803 case Intrinsic::ceil: 6804 case Intrinsic::trunc: 6805 case Intrinsic::rint: 6806 case Intrinsic::nearbyint: 6807 case Intrinsic::round: 6808 case Intrinsic::roundeven: 6809 case Intrinsic::canonicalize: { 6810 unsigned Opcode; 6811 // clang-format off 6812 switch (Intrinsic) { 6813 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6814 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6815 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6816 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6817 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6818 case Intrinsic::tan: Opcode = ISD::FTAN; break; 6819 case Intrinsic::asin: Opcode = ISD::FASIN; break; 6820 case Intrinsic::acos: Opcode = ISD::FACOS; break; 6821 case Intrinsic::atan: Opcode = ISD::FATAN; break; 6822 case Intrinsic::sinh: Opcode = ISD::FSINH; break; 6823 case Intrinsic::cosh: Opcode = ISD::FCOSH; break; 6824 case Intrinsic::tanh: Opcode = ISD::FTANH; break; 6825 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6826 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6827 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6828 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6829 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6830 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6831 case Intrinsic::round: Opcode = ISD::FROUND; break; 6832 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6833 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6834 } 6835 // clang-format on 6836 6837 setValue(&I, DAG.getNode(Opcode, sdl, 6838 getValue(I.getArgOperand(0)).getValueType(), 6839 getValue(I.getArgOperand(0)), Flags)); 6840 return; 6841 } 6842 case Intrinsic::lround: 6843 case Intrinsic::llround: 6844 case Intrinsic::lrint: 6845 case Intrinsic::llrint: { 6846 unsigned Opcode; 6847 // clang-format off 6848 switch (Intrinsic) { 6849 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6850 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6851 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6852 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6853 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6854 } 6855 // clang-format on 6856 6857 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6858 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6859 getValue(I.getArgOperand(0)))); 6860 return; 6861 } 6862 case Intrinsic::minnum: 6863 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6864 getValue(I.getArgOperand(0)).getValueType(), 6865 getValue(I.getArgOperand(0)), 6866 getValue(I.getArgOperand(1)), Flags)); 6867 return; 6868 case Intrinsic::maxnum: 6869 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6870 getValue(I.getArgOperand(0)).getValueType(), 6871 getValue(I.getArgOperand(0)), 6872 getValue(I.getArgOperand(1)), Flags)); 6873 return; 6874 case Intrinsic::minimum: 6875 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6876 getValue(I.getArgOperand(0)).getValueType(), 6877 getValue(I.getArgOperand(0)), 6878 getValue(I.getArgOperand(1)), Flags)); 6879 return; 6880 case Intrinsic::maximum: 6881 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6882 getValue(I.getArgOperand(0)).getValueType(), 6883 getValue(I.getArgOperand(0)), 6884 getValue(I.getArgOperand(1)), Flags)); 6885 return; 6886 case Intrinsic::minimumnum: 6887 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl, 6888 getValue(I.getArgOperand(0)).getValueType(), 6889 getValue(I.getArgOperand(0)), 6890 getValue(I.getArgOperand(1)), Flags)); 6891 return; 6892 case Intrinsic::maximumnum: 6893 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl, 6894 getValue(I.getArgOperand(0)).getValueType(), 6895 getValue(I.getArgOperand(0)), 6896 getValue(I.getArgOperand(1)), Flags)); 6897 return; 6898 case Intrinsic::copysign: 6899 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6900 getValue(I.getArgOperand(0)).getValueType(), 6901 getValue(I.getArgOperand(0)), 6902 getValue(I.getArgOperand(1)), Flags)); 6903 return; 6904 case Intrinsic::ldexp: 6905 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6906 getValue(I.getArgOperand(0)).getValueType(), 6907 getValue(I.getArgOperand(0)), 6908 getValue(I.getArgOperand(1)), Flags)); 6909 return; 6910 case Intrinsic::frexp: { 6911 SmallVector<EVT, 2> ValueVTs; 6912 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6913 SDVTList VTs = DAG.getVTList(ValueVTs); 6914 setValue(&I, 6915 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6916 return; 6917 } 6918 case Intrinsic::arithmetic_fence: { 6919 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6920 getValue(I.getArgOperand(0)).getValueType(), 6921 getValue(I.getArgOperand(0)), Flags)); 6922 return; 6923 } 6924 case Intrinsic::fma: 6925 setValue(&I, DAG.getNode( 6926 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6927 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6928 getValue(I.getArgOperand(2)), Flags)); 6929 return; 6930 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6931 case Intrinsic::INTRINSIC: 6932 #include "llvm/IR/ConstrainedOps.def" 6933 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6934 return; 6935 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6936 #include "llvm/IR/VPIntrinsics.def" 6937 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6938 return; 6939 case Intrinsic::fptrunc_round: { 6940 // Get the last argument, the metadata and convert it to an integer in the 6941 // call 6942 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6943 std::optional<RoundingMode> RoundMode = 6944 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6945 6946 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6947 6948 // Propagate fast-math-flags from IR to node(s). 6949 SDNodeFlags Flags; 6950 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6951 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6952 6953 SDValue Result; 6954 Result = DAG.getNode( 6955 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6956 DAG.getTargetConstant((int)*RoundMode, sdl, 6957 TLI.getPointerTy(DAG.getDataLayout()))); 6958 setValue(&I, Result); 6959 6960 return; 6961 } 6962 case Intrinsic::fmuladd: { 6963 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6964 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6965 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6966 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6967 getValue(I.getArgOperand(0)).getValueType(), 6968 getValue(I.getArgOperand(0)), 6969 getValue(I.getArgOperand(1)), 6970 getValue(I.getArgOperand(2)), Flags)); 6971 } else { 6972 // TODO: Intrinsic calls should have fast-math-flags. 6973 SDValue Mul = DAG.getNode( 6974 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6975 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6976 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6977 getValue(I.getArgOperand(0)).getValueType(), 6978 Mul, getValue(I.getArgOperand(2)), Flags); 6979 setValue(&I, Add); 6980 } 6981 return; 6982 } 6983 case Intrinsic::convert_to_fp16: 6984 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6985 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6986 getValue(I.getArgOperand(0)), 6987 DAG.getTargetConstant(0, sdl, 6988 MVT::i32)))); 6989 return; 6990 case Intrinsic::convert_from_fp16: 6991 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6992 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6993 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6994 getValue(I.getArgOperand(0))))); 6995 return; 6996 case Intrinsic::fptosi_sat: { 6997 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6998 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6999 getValue(I.getArgOperand(0)), 7000 DAG.getValueType(VT.getScalarType()))); 7001 return; 7002 } 7003 case Intrinsic::fptoui_sat: { 7004 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7005 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 7006 getValue(I.getArgOperand(0)), 7007 DAG.getValueType(VT.getScalarType()))); 7008 return; 7009 } 7010 case Intrinsic::set_rounding: 7011 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 7012 {getRoot(), getValue(I.getArgOperand(0))}); 7013 setValue(&I, Res); 7014 DAG.setRoot(Res.getValue(0)); 7015 return; 7016 case Intrinsic::is_fpclass: { 7017 const DataLayout DLayout = DAG.getDataLayout(); 7018 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 7019 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 7020 FPClassTest Test = static_cast<FPClassTest>( 7021 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 7022 MachineFunction &MF = DAG.getMachineFunction(); 7023 const Function &F = MF.getFunction(); 7024 SDValue Op = getValue(I.getArgOperand(0)); 7025 SDNodeFlags Flags; 7026 Flags.setNoFPExcept( 7027 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 7028 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 7029 // expansion can use illegal types. Making expansion early allows 7030 // legalizing these types prior to selection. 7031 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 7032 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 7033 setValue(&I, Result); 7034 return; 7035 } 7036 7037 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 7038 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 7039 setValue(&I, V); 7040 return; 7041 } 7042 case Intrinsic::get_fpenv: { 7043 const DataLayout DLayout = DAG.getDataLayout(); 7044 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 7045 Align TempAlign = DAG.getEVTAlign(EnvVT); 7046 SDValue Chain = getRoot(); 7047 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 7048 // and temporary storage in stack. 7049 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 7050 Res = DAG.getNode( 7051 ISD::GET_FPENV, sdl, 7052 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7053 MVT::Other), 7054 Chain); 7055 } else { 7056 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7057 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7058 auto MPI = 7059 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7060 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7061 MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(), 7062 TempAlign); 7063 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7064 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 7065 } 7066 setValue(&I, Res); 7067 DAG.setRoot(Res.getValue(1)); 7068 return; 7069 } 7070 case Intrinsic::set_fpenv: { 7071 const DataLayout DLayout = DAG.getDataLayout(); 7072 SDValue Env = getValue(I.getArgOperand(0)); 7073 EVT EnvVT = Env.getValueType(); 7074 Align TempAlign = DAG.getEVTAlign(EnvVT); 7075 SDValue Chain = getRoot(); 7076 // If SET_FPENV is custom or legal, use it. Otherwise use loading 7077 // environment from memory. 7078 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 7079 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 7080 } else { 7081 // Allocate space in stack, copy environment bits into it and use this 7082 // memory in SET_FPENV_MEM. 7083 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7084 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7085 auto MPI = 7086 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7087 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 7088 MachineMemOperand::MOStore); 7089 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7090 MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(), 7091 TempAlign); 7092 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7093 } 7094 DAG.setRoot(Chain); 7095 return; 7096 } 7097 case Intrinsic::reset_fpenv: 7098 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 7099 return; 7100 case Intrinsic::get_fpmode: 7101 Res = DAG.getNode( 7102 ISD::GET_FPMODE, sdl, 7103 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7104 MVT::Other), 7105 DAG.getRoot()); 7106 setValue(&I, Res); 7107 DAG.setRoot(Res.getValue(1)); 7108 return; 7109 case Intrinsic::set_fpmode: 7110 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 7111 getValue(I.getArgOperand(0))); 7112 DAG.setRoot(Res); 7113 return; 7114 case Intrinsic::reset_fpmode: { 7115 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 7116 DAG.setRoot(Res); 7117 return; 7118 } 7119 case Intrinsic::pcmarker: { 7120 SDValue Tmp = getValue(I.getArgOperand(0)); 7121 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 7122 return; 7123 } 7124 case Intrinsic::readcyclecounter: { 7125 SDValue Op = getRoot(); 7126 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 7127 DAG.getVTList(MVT::i64, MVT::Other), Op); 7128 setValue(&I, Res); 7129 DAG.setRoot(Res.getValue(1)); 7130 return; 7131 } 7132 case Intrinsic::readsteadycounter: { 7133 SDValue Op = getRoot(); 7134 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 7135 DAG.getVTList(MVT::i64, MVT::Other), Op); 7136 setValue(&I, Res); 7137 DAG.setRoot(Res.getValue(1)); 7138 return; 7139 } 7140 case Intrinsic::bitreverse: 7141 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 7142 getValue(I.getArgOperand(0)).getValueType(), 7143 getValue(I.getArgOperand(0)))); 7144 return; 7145 case Intrinsic::bswap: 7146 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 7147 getValue(I.getArgOperand(0)).getValueType(), 7148 getValue(I.getArgOperand(0)))); 7149 return; 7150 case Intrinsic::cttz: { 7151 SDValue Arg = getValue(I.getArgOperand(0)); 7152 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7153 EVT Ty = Arg.getValueType(); 7154 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 7155 sdl, Ty, Arg)); 7156 return; 7157 } 7158 case Intrinsic::ctlz: { 7159 SDValue Arg = getValue(I.getArgOperand(0)); 7160 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7161 EVT Ty = Arg.getValueType(); 7162 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 7163 sdl, Ty, Arg)); 7164 return; 7165 } 7166 case Intrinsic::ctpop: { 7167 SDValue Arg = getValue(I.getArgOperand(0)); 7168 EVT Ty = Arg.getValueType(); 7169 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 7170 return; 7171 } 7172 case Intrinsic::fshl: 7173 case Intrinsic::fshr: { 7174 bool IsFSHL = Intrinsic == Intrinsic::fshl; 7175 SDValue X = getValue(I.getArgOperand(0)); 7176 SDValue Y = getValue(I.getArgOperand(1)); 7177 SDValue Z = getValue(I.getArgOperand(2)); 7178 EVT VT = X.getValueType(); 7179 7180 if (X == Y) { 7181 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 7182 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 7183 } else { 7184 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 7185 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 7186 } 7187 return; 7188 } 7189 case Intrinsic::sadd_sat: { 7190 SDValue Op1 = getValue(I.getArgOperand(0)); 7191 SDValue Op2 = getValue(I.getArgOperand(1)); 7192 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7193 return; 7194 } 7195 case Intrinsic::uadd_sat: { 7196 SDValue Op1 = getValue(I.getArgOperand(0)); 7197 SDValue Op2 = getValue(I.getArgOperand(1)); 7198 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7199 return; 7200 } 7201 case Intrinsic::ssub_sat: { 7202 SDValue Op1 = getValue(I.getArgOperand(0)); 7203 SDValue Op2 = getValue(I.getArgOperand(1)); 7204 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7205 return; 7206 } 7207 case Intrinsic::usub_sat: { 7208 SDValue Op1 = getValue(I.getArgOperand(0)); 7209 SDValue Op2 = getValue(I.getArgOperand(1)); 7210 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7211 return; 7212 } 7213 case Intrinsic::sshl_sat: { 7214 SDValue Op1 = getValue(I.getArgOperand(0)); 7215 SDValue Op2 = getValue(I.getArgOperand(1)); 7216 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7217 return; 7218 } 7219 case Intrinsic::ushl_sat: { 7220 SDValue Op1 = getValue(I.getArgOperand(0)); 7221 SDValue Op2 = getValue(I.getArgOperand(1)); 7222 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7223 return; 7224 } 7225 case Intrinsic::smul_fix: 7226 case Intrinsic::umul_fix: 7227 case Intrinsic::smul_fix_sat: 7228 case Intrinsic::umul_fix_sat: { 7229 SDValue Op1 = getValue(I.getArgOperand(0)); 7230 SDValue Op2 = getValue(I.getArgOperand(1)); 7231 SDValue Op3 = getValue(I.getArgOperand(2)); 7232 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7233 Op1.getValueType(), Op1, Op2, Op3)); 7234 return; 7235 } 7236 case Intrinsic::sdiv_fix: 7237 case Intrinsic::udiv_fix: 7238 case Intrinsic::sdiv_fix_sat: 7239 case Intrinsic::udiv_fix_sat: { 7240 SDValue Op1 = getValue(I.getArgOperand(0)); 7241 SDValue Op2 = getValue(I.getArgOperand(1)); 7242 SDValue Op3 = getValue(I.getArgOperand(2)); 7243 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7244 Op1, Op2, Op3, DAG, TLI)); 7245 return; 7246 } 7247 case Intrinsic::smax: { 7248 SDValue Op1 = getValue(I.getArgOperand(0)); 7249 SDValue Op2 = getValue(I.getArgOperand(1)); 7250 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 7251 return; 7252 } 7253 case Intrinsic::smin: { 7254 SDValue Op1 = getValue(I.getArgOperand(0)); 7255 SDValue Op2 = getValue(I.getArgOperand(1)); 7256 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 7257 return; 7258 } 7259 case Intrinsic::umax: { 7260 SDValue Op1 = getValue(I.getArgOperand(0)); 7261 SDValue Op2 = getValue(I.getArgOperand(1)); 7262 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 7263 return; 7264 } 7265 case Intrinsic::umin: { 7266 SDValue Op1 = getValue(I.getArgOperand(0)); 7267 SDValue Op2 = getValue(I.getArgOperand(1)); 7268 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 7269 return; 7270 } 7271 case Intrinsic::abs: { 7272 // TODO: Preserve "int min is poison" arg in SDAG? 7273 SDValue Op1 = getValue(I.getArgOperand(0)); 7274 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 7275 return; 7276 } 7277 case Intrinsic::scmp: { 7278 SDValue Op1 = getValue(I.getArgOperand(0)); 7279 SDValue Op2 = getValue(I.getArgOperand(1)); 7280 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7281 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2)); 7282 break; 7283 } 7284 case Intrinsic::ucmp: { 7285 SDValue Op1 = getValue(I.getArgOperand(0)); 7286 SDValue Op2 = getValue(I.getArgOperand(1)); 7287 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7288 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2)); 7289 break; 7290 } 7291 case Intrinsic::stacksave: { 7292 SDValue Op = getRoot(); 7293 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7294 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 7295 setValue(&I, Res); 7296 DAG.setRoot(Res.getValue(1)); 7297 return; 7298 } 7299 case Intrinsic::stackrestore: 7300 Res = getValue(I.getArgOperand(0)); 7301 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 7302 return; 7303 case Intrinsic::get_dynamic_area_offset: { 7304 SDValue Op = getRoot(); 7305 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7306 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7307 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 7308 // target. 7309 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 7310 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 7311 " intrinsic!"); 7312 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 7313 Op); 7314 DAG.setRoot(Op); 7315 setValue(&I, Res); 7316 return; 7317 } 7318 case Intrinsic::stackguard: { 7319 MachineFunction &MF = DAG.getMachineFunction(); 7320 const Module &M = *MF.getFunction().getParent(); 7321 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7322 SDValue Chain = getRoot(); 7323 if (TLI.useLoadStackGuardNode()) { 7324 Res = getLoadStackGuard(DAG, sdl, Chain); 7325 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 7326 } else { 7327 const Value *Global = TLI.getSDagStackGuard(M); 7328 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7329 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7330 MachinePointerInfo(Global, 0), Align, 7331 MachineMemOperand::MOVolatile); 7332 } 7333 if (TLI.useStackGuardXorFP()) 7334 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7335 DAG.setRoot(Chain); 7336 setValue(&I, Res); 7337 return; 7338 } 7339 case Intrinsic::stackprotector: { 7340 // Emit code into the DAG to store the stack guard onto the stack. 7341 MachineFunction &MF = DAG.getMachineFunction(); 7342 MachineFrameInfo &MFI = MF.getFrameInfo(); 7343 SDValue Src, Chain = getRoot(); 7344 7345 if (TLI.useLoadStackGuardNode()) 7346 Src = getLoadStackGuard(DAG, sdl, Chain); 7347 else 7348 Src = getValue(I.getArgOperand(0)); // The guard's value. 7349 7350 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7351 7352 int FI = FuncInfo.StaticAllocaMap[Slot]; 7353 MFI.setStackProtectorIndex(FI); 7354 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7355 7356 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7357 7358 // Store the stack protector onto the stack. 7359 Res = DAG.getStore( 7360 Chain, sdl, Src, FIN, 7361 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7362 MaybeAlign(), MachineMemOperand::MOVolatile); 7363 setValue(&I, Res); 7364 DAG.setRoot(Res); 7365 return; 7366 } 7367 case Intrinsic::objectsize: 7368 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7369 7370 case Intrinsic::is_constant: 7371 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7372 7373 case Intrinsic::annotation: 7374 case Intrinsic::ptr_annotation: 7375 case Intrinsic::launder_invariant_group: 7376 case Intrinsic::strip_invariant_group: 7377 // Drop the intrinsic, but forward the value 7378 setValue(&I, getValue(I.getOperand(0))); 7379 return; 7380 7381 case Intrinsic::assume: 7382 case Intrinsic::experimental_noalias_scope_decl: 7383 case Intrinsic::var_annotation: 7384 case Intrinsic::sideeffect: 7385 // Discard annotate attributes, noalias scope declarations, assumptions, and 7386 // artificial side-effects. 7387 return; 7388 7389 case Intrinsic::codeview_annotation: { 7390 // Emit a label associated with this metadata. 7391 MachineFunction &MF = DAG.getMachineFunction(); 7392 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true); 7393 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7394 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7395 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7396 DAG.setRoot(Res); 7397 return; 7398 } 7399 7400 case Intrinsic::init_trampoline: { 7401 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7402 7403 SDValue Ops[6]; 7404 Ops[0] = getRoot(); 7405 Ops[1] = getValue(I.getArgOperand(0)); 7406 Ops[2] = getValue(I.getArgOperand(1)); 7407 Ops[3] = getValue(I.getArgOperand(2)); 7408 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7409 Ops[5] = DAG.getSrcValue(F); 7410 7411 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7412 7413 DAG.setRoot(Res); 7414 return; 7415 } 7416 case Intrinsic::adjust_trampoline: 7417 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7418 TLI.getPointerTy(DAG.getDataLayout()), 7419 getValue(I.getArgOperand(0)))); 7420 return; 7421 case Intrinsic::gcroot: { 7422 assert(DAG.getMachineFunction().getFunction().hasGC() && 7423 "only valid in functions with gc specified, enforced by Verifier"); 7424 assert(GFI && "implied by previous"); 7425 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7426 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7427 7428 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7429 GFI->addStackRoot(FI->getIndex(), TypeMap); 7430 return; 7431 } 7432 case Intrinsic::gcread: 7433 case Intrinsic::gcwrite: 7434 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7435 case Intrinsic::get_rounding: 7436 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7437 setValue(&I, Res); 7438 DAG.setRoot(Res.getValue(1)); 7439 return; 7440 7441 case Intrinsic::expect: 7442 // Just replace __builtin_expect(exp, c) with EXP. 7443 setValue(&I, getValue(I.getArgOperand(0))); 7444 return; 7445 7446 case Intrinsic::ubsantrap: 7447 case Intrinsic::debugtrap: 7448 case Intrinsic::trap: { 7449 StringRef TrapFuncName = 7450 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7451 if (TrapFuncName.empty()) { 7452 switch (Intrinsic) { 7453 case Intrinsic::trap: 7454 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7455 break; 7456 case Intrinsic::debugtrap: 7457 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7458 break; 7459 case Intrinsic::ubsantrap: 7460 DAG.setRoot(DAG.getNode( 7461 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7462 DAG.getTargetConstant( 7463 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7464 MVT::i32))); 7465 break; 7466 default: llvm_unreachable("unknown trap intrinsic"); 7467 } 7468 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(), 7469 I.hasFnAttr(Attribute::NoMerge)); 7470 return; 7471 } 7472 TargetLowering::ArgListTy Args; 7473 if (Intrinsic == Intrinsic::ubsantrap) { 7474 Args.push_back(TargetLoweringBase::ArgListEntry()); 7475 Args[0].Val = I.getArgOperand(0); 7476 Args[0].Node = getValue(Args[0].Val); 7477 Args[0].Ty = Args[0].Val->getType(); 7478 } 7479 7480 TargetLowering::CallLoweringInfo CLI(DAG); 7481 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7482 CallingConv::C, I.getType(), 7483 DAG.getExternalSymbol(TrapFuncName.data(), 7484 TLI.getPointerTy(DAG.getDataLayout())), 7485 std::move(Args)); 7486 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge); 7487 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7488 DAG.setRoot(Result.second); 7489 return; 7490 } 7491 7492 case Intrinsic::allow_runtime_check: 7493 case Intrinsic::allow_ubsan_check: 7494 setValue(&I, getValue(ConstantInt::getTrue(I.getType()))); 7495 return; 7496 7497 case Intrinsic::uadd_with_overflow: 7498 case Intrinsic::sadd_with_overflow: 7499 case Intrinsic::usub_with_overflow: 7500 case Intrinsic::ssub_with_overflow: 7501 case Intrinsic::umul_with_overflow: 7502 case Intrinsic::smul_with_overflow: { 7503 ISD::NodeType Op; 7504 switch (Intrinsic) { 7505 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7506 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7507 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7508 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7509 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7510 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7511 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7512 } 7513 SDValue Op1 = getValue(I.getArgOperand(0)); 7514 SDValue Op2 = getValue(I.getArgOperand(1)); 7515 7516 EVT ResultVT = Op1.getValueType(); 7517 EVT OverflowVT = MVT::i1; 7518 if (ResultVT.isVector()) 7519 OverflowVT = EVT::getVectorVT( 7520 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7521 7522 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7523 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7524 return; 7525 } 7526 case Intrinsic::prefetch: { 7527 SDValue Ops[5]; 7528 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7529 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7530 Ops[0] = DAG.getRoot(); 7531 Ops[1] = getValue(I.getArgOperand(0)); 7532 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7533 MVT::i32); 7534 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7535 MVT::i32); 7536 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7537 MVT::i32); 7538 SDValue Result = DAG.getMemIntrinsicNode( 7539 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7540 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7541 /* align */ std::nullopt, Flags); 7542 7543 // Chain the prefetch in parallel with any pending loads, to stay out of 7544 // the way of later optimizations. 7545 PendingLoads.push_back(Result); 7546 Result = getRoot(); 7547 DAG.setRoot(Result); 7548 return; 7549 } 7550 case Intrinsic::lifetime_start: 7551 case Intrinsic::lifetime_end: { 7552 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7553 // Stack coloring is not enabled in O0, discard region information. 7554 if (TM.getOptLevel() == CodeGenOptLevel::None) 7555 return; 7556 7557 const int64_t ObjectSize = 7558 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7559 Value *const ObjectPtr = I.getArgOperand(1); 7560 SmallVector<const Value *, 4> Allocas; 7561 getUnderlyingObjects(ObjectPtr, Allocas); 7562 7563 for (const Value *Alloca : Allocas) { 7564 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7565 7566 // Could not find an Alloca. 7567 if (!LifetimeObject) 7568 continue; 7569 7570 // First check that the Alloca is static, otherwise it won't have a 7571 // valid frame index. 7572 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7573 if (SI == FuncInfo.StaticAllocaMap.end()) 7574 return; 7575 7576 const int FrameIndex = SI->second; 7577 int64_t Offset; 7578 if (GetPointerBaseWithConstantOffset( 7579 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7580 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7581 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7582 Offset); 7583 DAG.setRoot(Res); 7584 } 7585 return; 7586 } 7587 case Intrinsic::pseudoprobe: { 7588 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7589 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7590 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7591 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7592 DAG.setRoot(Res); 7593 return; 7594 } 7595 case Intrinsic::invariant_start: 7596 // Discard region information. 7597 setValue(&I, 7598 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7599 return; 7600 case Intrinsic::invariant_end: 7601 // Discard region information. 7602 return; 7603 case Intrinsic::clear_cache: { 7604 SDValue InputChain = DAG.getRoot(); 7605 SDValue StartVal = getValue(I.getArgOperand(0)); 7606 SDValue EndVal = getValue(I.getArgOperand(1)); 7607 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other), 7608 {InputChain, StartVal, EndVal}); 7609 setValue(&I, Res); 7610 DAG.setRoot(Res); 7611 return; 7612 } 7613 case Intrinsic::donothing: 7614 case Intrinsic::seh_try_begin: 7615 case Intrinsic::seh_scope_begin: 7616 case Intrinsic::seh_try_end: 7617 case Intrinsic::seh_scope_end: 7618 // ignore 7619 return; 7620 case Intrinsic::experimental_stackmap: 7621 visitStackmap(I); 7622 return; 7623 case Intrinsic::experimental_patchpoint_void: 7624 case Intrinsic::experimental_patchpoint: 7625 visitPatchpoint(I); 7626 return; 7627 case Intrinsic::experimental_gc_statepoint: 7628 LowerStatepoint(cast<GCStatepointInst>(I)); 7629 return; 7630 case Intrinsic::experimental_gc_result: 7631 visitGCResult(cast<GCResultInst>(I)); 7632 return; 7633 case Intrinsic::experimental_gc_relocate: 7634 visitGCRelocate(cast<GCRelocateInst>(I)); 7635 return; 7636 case Intrinsic::instrprof_cover: 7637 llvm_unreachable("instrprof failed to lower a cover"); 7638 case Intrinsic::instrprof_increment: 7639 llvm_unreachable("instrprof failed to lower an increment"); 7640 case Intrinsic::instrprof_timestamp: 7641 llvm_unreachable("instrprof failed to lower a timestamp"); 7642 case Intrinsic::instrprof_value_profile: 7643 llvm_unreachable("instrprof failed to lower a value profiling call"); 7644 case Intrinsic::instrprof_mcdc_parameters: 7645 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7646 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7647 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7648 case Intrinsic::localescape: { 7649 MachineFunction &MF = DAG.getMachineFunction(); 7650 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7651 7652 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7653 // is the same on all targets. 7654 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7655 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7656 if (isa<ConstantPointerNull>(Arg)) 7657 continue; // Skip null pointers. They represent a hole in index space. 7658 AllocaInst *Slot = cast<AllocaInst>(Arg); 7659 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7660 "can only escape static allocas"); 7661 int FI = FuncInfo.StaticAllocaMap[Slot]; 7662 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol( 7663 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7665 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7666 .addSym(FrameAllocSym) 7667 .addFrameIndex(FI); 7668 } 7669 7670 return; 7671 } 7672 7673 case Intrinsic::localrecover: { 7674 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7675 MachineFunction &MF = DAG.getMachineFunction(); 7676 7677 // Get the symbol that defines the frame offset. 7678 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7679 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7680 unsigned IdxVal = 7681 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7682 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol( 7683 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7684 7685 Value *FP = I.getArgOperand(1); 7686 SDValue FPVal = getValue(FP); 7687 EVT PtrVT = FPVal.getValueType(); 7688 7689 // Create a MCSymbol for the label to avoid any target lowering 7690 // that would make this PC relative. 7691 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7692 SDValue OffsetVal = 7693 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7694 7695 // Add the offset to the FP. 7696 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7697 setValue(&I, Add); 7698 7699 return; 7700 } 7701 7702 case Intrinsic::eh_exceptionpointer: 7703 case Intrinsic::eh_exceptioncode: { 7704 // Get the exception pointer vreg, copy from it, and resize it to fit. 7705 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7706 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7707 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7708 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7709 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7710 if (Intrinsic == Intrinsic::eh_exceptioncode) 7711 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7712 setValue(&I, N); 7713 return; 7714 } 7715 case Intrinsic::xray_customevent: { 7716 // Here we want to make sure that the intrinsic behaves as if it has a 7717 // specific calling convention. 7718 const auto &Triple = DAG.getTarget().getTargetTriple(); 7719 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7720 return; 7721 7722 SmallVector<SDValue, 8> Ops; 7723 7724 // We want to say that we always want the arguments in registers. 7725 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7726 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7727 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7728 SDValue Chain = getRoot(); 7729 Ops.push_back(LogEntryVal); 7730 Ops.push_back(StrSizeVal); 7731 Ops.push_back(Chain); 7732 7733 // We need to enforce the calling convention for the callsite, so that 7734 // argument ordering is enforced correctly, and that register allocation can 7735 // see that some registers may be assumed clobbered and have to preserve 7736 // them across calls to the intrinsic. 7737 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7738 sdl, NodeTys, Ops); 7739 SDValue patchableNode = SDValue(MN, 0); 7740 DAG.setRoot(patchableNode); 7741 setValue(&I, patchableNode); 7742 return; 7743 } 7744 case Intrinsic::xray_typedevent: { 7745 // Here we want to make sure that the intrinsic behaves as if it has a 7746 // specific calling convention. 7747 const auto &Triple = DAG.getTarget().getTargetTriple(); 7748 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7749 return; 7750 7751 SmallVector<SDValue, 8> Ops; 7752 7753 // We want to say that we always want the arguments in registers. 7754 // It's unclear to me how manipulating the selection DAG here forces callers 7755 // to provide arguments in registers instead of on the stack. 7756 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7757 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7758 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7759 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7760 SDValue Chain = getRoot(); 7761 Ops.push_back(LogTypeId); 7762 Ops.push_back(LogEntryVal); 7763 Ops.push_back(StrSizeVal); 7764 Ops.push_back(Chain); 7765 7766 // We need to enforce the calling convention for the callsite, so that 7767 // argument ordering is enforced correctly, and that register allocation can 7768 // see that some registers may be assumed clobbered and have to preserve 7769 // them across calls to the intrinsic. 7770 MachineSDNode *MN = DAG.getMachineNode( 7771 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7772 SDValue patchableNode = SDValue(MN, 0); 7773 DAG.setRoot(patchableNode); 7774 setValue(&I, patchableNode); 7775 return; 7776 } 7777 case Intrinsic::experimental_deoptimize: 7778 LowerDeoptimizeCall(&I); 7779 return; 7780 case Intrinsic::experimental_stepvector: 7781 visitStepVector(I); 7782 return; 7783 case Intrinsic::vector_reduce_fadd: 7784 case Intrinsic::vector_reduce_fmul: 7785 case Intrinsic::vector_reduce_add: 7786 case Intrinsic::vector_reduce_mul: 7787 case Intrinsic::vector_reduce_and: 7788 case Intrinsic::vector_reduce_or: 7789 case Intrinsic::vector_reduce_xor: 7790 case Intrinsic::vector_reduce_smax: 7791 case Intrinsic::vector_reduce_smin: 7792 case Intrinsic::vector_reduce_umax: 7793 case Intrinsic::vector_reduce_umin: 7794 case Intrinsic::vector_reduce_fmax: 7795 case Intrinsic::vector_reduce_fmin: 7796 case Intrinsic::vector_reduce_fmaximum: 7797 case Intrinsic::vector_reduce_fminimum: 7798 visitVectorReduce(I, Intrinsic); 7799 return; 7800 7801 case Intrinsic::icall_branch_funnel: { 7802 SmallVector<SDValue, 16> Ops; 7803 Ops.push_back(getValue(I.getArgOperand(0))); 7804 7805 int64_t Offset; 7806 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7807 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7808 if (!Base) 7809 report_fatal_error( 7810 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7811 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7812 7813 struct BranchFunnelTarget { 7814 int64_t Offset; 7815 SDValue Target; 7816 }; 7817 SmallVector<BranchFunnelTarget, 8> Targets; 7818 7819 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7820 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7821 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7822 if (ElemBase != Base) 7823 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7824 "to the same GlobalValue"); 7825 7826 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7827 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7828 if (!GA) 7829 report_fatal_error( 7830 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7831 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7832 GA->getGlobal(), sdl, Val.getValueType(), 7833 GA->getOffset())}); 7834 } 7835 llvm::sort(Targets, 7836 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7837 return T1.Offset < T2.Offset; 7838 }); 7839 7840 for (auto &T : Targets) { 7841 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7842 Ops.push_back(T.Target); 7843 } 7844 7845 Ops.push_back(DAG.getRoot()); // Chain 7846 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7847 MVT::Other, Ops), 7848 0); 7849 DAG.setRoot(N); 7850 setValue(&I, N); 7851 HasTailCall = true; 7852 return; 7853 } 7854 7855 case Intrinsic::wasm_landingpad_index: 7856 // Information this intrinsic contained has been transferred to 7857 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7858 // delete it now. 7859 return; 7860 7861 case Intrinsic::aarch64_settag: 7862 case Intrinsic::aarch64_settag_zero: { 7863 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7864 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7865 SDValue Val = TSI.EmitTargetCodeForSetTag( 7866 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7867 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7868 ZeroMemory); 7869 DAG.setRoot(Val); 7870 setValue(&I, Val); 7871 return; 7872 } 7873 case Intrinsic::amdgcn_cs_chain: { 7874 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7875 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7876 "Non-zero flags not supported yet"); 7877 7878 // At this point we don't care if it's amdgpu_cs_chain or 7879 // amdgpu_cs_chain_preserve. 7880 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7881 7882 Type *RetTy = I.getType(); 7883 assert(RetTy->isVoidTy() && "Should not return"); 7884 7885 SDValue Callee = getValue(I.getOperand(0)); 7886 7887 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7888 // We'll also tack the value of the EXEC mask at the end. 7889 TargetLowering::ArgListTy Args; 7890 Args.reserve(3); 7891 7892 for (unsigned Idx : {2, 3, 1}) { 7893 TargetLowering::ArgListEntry Arg; 7894 Arg.Node = getValue(I.getOperand(Idx)); 7895 Arg.Ty = I.getOperand(Idx)->getType(); 7896 Arg.setAttributes(&I, Idx); 7897 Args.push_back(Arg); 7898 } 7899 7900 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7901 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7902 Args[2].IsInReg = true; // EXEC should be inreg 7903 7904 TargetLowering::CallLoweringInfo CLI(DAG); 7905 CLI.setDebugLoc(getCurSDLoc()) 7906 .setChain(getRoot()) 7907 .setCallee(CC, RetTy, Callee, std::move(Args)) 7908 .setNoReturn(true) 7909 .setTailCall(true) 7910 .setConvergent(I.isConvergent()); 7911 CLI.CB = &I; 7912 std::pair<SDValue, SDValue> Result = 7913 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7914 (void)Result; 7915 assert(!Result.first.getNode() && !Result.second.getNode() && 7916 "Should've lowered as tail call"); 7917 7918 HasTailCall = true; 7919 return; 7920 } 7921 case Intrinsic::ptrmask: { 7922 SDValue Ptr = getValue(I.getOperand(0)); 7923 SDValue Mask = getValue(I.getOperand(1)); 7924 7925 // On arm64_32, pointers are 32 bits when stored in memory, but 7926 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to 7927 // match the index type, but the pointer is 64 bits, so the the mask must be 7928 // zero-extended up to 64 bits to match the pointer. 7929 EVT PtrVT = 7930 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 7931 EVT MemVT = 7932 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 7933 assert(PtrVT == Ptr.getValueType()); 7934 assert(MemVT == Mask.getValueType()); 7935 if (MemVT != PtrVT) 7936 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT); 7937 7938 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7939 return; 7940 } 7941 case Intrinsic::threadlocal_address: { 7942 setValue(&I, getValue(I.getOperand(0))); 7943 return; 7944 } 7945 case Intrinsic::get_active_lane_mask: { 7946 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7947 SDValue Index = getValue(I.getOperand(0)); 7948 EVT ElementVT = Index.getValueType(); 7949 7950 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7951 visitTargetIntrinsic(I, Intrinsic); 7952 return; 7953 } 7954 7955 SDValue TripCount = getValue(I.getOperand(1)); 7956 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7957 CCVT.getVectorElementCount()); 7958 7959 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7960 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7961 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7962 SDValue VectorInduction = DAG.getNode( 7963 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7964 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7965 VectorTripCount, ISD::CondCode::SETULT); 7966 setValue(&I, SetCC); 7967 return; 7968 } 7969 case Intrinsic::experimental_get_vector_length: { 7970 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7971 "Expected positive VF"); 7972 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7973 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7974 7975 SDValue Count = getValue(I.getOperand(0)); 7976 EVT CountVT = Count.getValueType(); 7977 7978 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7979 visitTargetIntrinsic(I, Intrinsic); 7980 return; 7981 } 7982 7983 // Expand to a umin between the trip count and the maximum elements the type 7984 // can hold. 7985 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7986 7987 // Extend the trip count to at least the result VT. 7988 if (CountVT.bitsLT(VT)) { 7989 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7990 CountVT = VT; 7991 } 7992 7993 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7994 ElementCount::get(VF, IsScalable)); 7995 7996 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7997 // Clip to the result type if needed. 7998 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7999 8000 setValue(&I, Trunc); 8001 return; 8002 } 8003 case Intrinsic::experimental_vector_partial_reduce_add: { 8004 SDValue OpNode = getValue(I.getOperand(1)); 8005 EVT ReducedTy = EVT::getEVT(I.getType()); 8006 EVT FullTy = OpNode.getValueType(); 8007 8008 unsigned Stride = ReducedTy.getVectorMinNumElements(); 8009 unsigned ScaleFactor = FullTy.getVectorMinNumElements() / Stride; 8010 8011 // Collect all of the subvectors 8012 std::deque<SDValue> Subvectors; 8013 Subvectors.push_back(getValue(I.getOperand(0))); 8014 for (unsigned i = 0; i < ScaleFactor; i++) { 8015 auto SourceIndex = DAG.getVectorIdxConstant(i * Stride, sdl); 8016 Subvectors.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ReducedTy, 8017 {OpNode, SourceIndex})); 8018 } 8019 8020 // Flatten the subvector tree 8021 while (Subvectors.size() > 1) { 8022 Subvectors.push_back(DAG.getNode(ISD::ADD, sdl, ReducedTy, 8023 {Subvectors[0], Subvectors[1]})); 8024 Subvectors.pop_front(); 8025 Subvectors.pop_front(); 8026 } 8027 8028 assert(Subvectors.size() == 1 && 8029 "There should only be one subvector after tree flattening"); 8030 8031 setValue(&I, Subvectors[0]); 8032 return; 8033 } 8034 case Intrinsic::experimental_cttz_elts: { 8035 auto DL = getCurSDLoc(); 8036 SDValue Op = getValue(I.getOperand(0)); 8037 EVT OpVT = Op.getValueType(); 8038 8039 if (!TLI.shouldExpandCttzElements(OpVT)) { 8040 visitTargetIntrinsic(I, Intrinsic); 8041 return; 8042 } 8043 8044 if (OpVT.getScalarType() != MVT::i1) { 8045 // Compare the input vector elements to zero & use to count trailing zeros 8046 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 8047 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 8048 OpVT.getVectorElementCount()); 8049 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 8050 } 8051 8052 // If the zero-is-poison flag is set, we can assume the upper limit 8053 // of the result is VF-1. 8054 bool ZeroIsPoison = 8055 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero(); 8056 ConstantRange VScaleRange(1, true); // Dummy value. 8057 if (isa<ScalableVectorType>(I.getOperand(0)->getType())) 8058 VScaleRange = getVScaleRange(I.getCaller(), 64); 8059 unsigned EltWidth = TLI.getBitWidthForCttzElements( 8060 I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange); 8061 8062 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 8063 8064 // Create the new vector type & get the vector length 8065 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 8066 OpVT.getVectorElementCount()); 8067 8068 SDValue VL = 8069 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 8070 8071 SDValue StepVec = DAG.getStepVector(DL, NewVT); 8072 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 8073 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 8074 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 8075 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 8076 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 8077 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 8078 8079 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8080 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 8081 8082 setValue(&I, Ret); 8083 return; 8084 } 8085 case Intrinsic::vector_insert: { 8086 SDValue Vec = getValue(I.getOperand(0)); 8087 SDValue SubVec = getValue(I.getOperand(1)); 8088 SDValue Index = getValue(I.getOperand(2)); 8089 8090 // The intrinsic's index type is i64, but the SDNode requires an index type 8091 // suitable for the target. Convert the index as required. 8092 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8093 if (Index.getValueType() != VectorIdxTy) 8094 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 8095 8096 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8097 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 8098 Index)); 8099 return; 8100 } 8101 case Intrinsic::vector_extract: { 8102 SDValue Vec = getValue(I.getOperand(0)); 8103 SDValue Index = getValue(I.getOperand(1)); 8104 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8105 8106 // The intrinsic's index type is i64, but the SDNode requires an index type 8107 // suitable for the target. Convert the index as required. 8108 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8109 if (Index.getValueType() != VectorIdxTy) 8110 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 8111 8112 setValue(&I, 8113 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 8114 return; 8115 } 8116 case Intrinsic::vector_reverse: 8117 visitVectorReverse(I); 8118 return; 8119 case Intrinsic::vector_splice: 8120 visitVectorSplice(I); 8121 return; 8122 case Intrinsic::callbr_landingpad: 8123 visitCallBrLandingPad(I); 8124 return; 8125 case Intrinsic::vector_interleave2: 8126 visitVectorInterleave(I); 8127 return; 8128 case Intrinsic::vector_deinterleave2: 8129 visitVectorDeinterleave(I); 8130 return; 8131 case Intrinsic::experimental_vector_compress: 8132 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl, 8133 getValue(I.getArgOperand(0)).getValueType(), 8134 getValue(I.getArgOperand(0)), 8135 getValue(I.getArgOperand(1)), 8136 getValue(I.getArgOperand(2)), Flags)); 8137 return; 8138 case Intrinsic::experimental_convergence_anchor: 8139 case Intrinsic::experimental_convergence_entry: 8140 case Intrinsic::experimental_convergence_loop: 8141 visitConvergenceControl(I, Intrinsic); 8142 return; 8143 case Intrinsic::experimental_vector_histogram_add: { 8144 visitVectorHistogram(I, Intrinsic); 8145 return; 8146 } 8147 } 8148 } 8149 8150 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 8151 const ConstrainedFPIntrinsic &FPI) { 8152 SDLoc sdl = getCurSDLoc(); 8153 8154 // We do not need to serialize constrained FP intrinsics against 8155 // each other or against (nonvolatile) loads, so they can be 8156 // chained like loads. 8157 SDValue Chain = DAG.getRoot(); 8158 SmallVector<SDValue, 4> Opers; 8159 Opers.push_back(Chain); 8160 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I) 8161 Opers.push_back(getValue(FPI.getArgOperand(I))); 8162 8163 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 8164 assert(Result.getNode()->getNumValues() == 2); 8165 8166 // Push node to the appropriate list so that future instructions can be 8167 // chained up correctly. 8168 SDValue OutChain = Result.getValue(1); 8169 switch (EB) { 8170 case fp::ExceptionBehavior::ebIgnore: 8171 // The only reason why ebIgnore nodes still need to be chained is that 8172 // they might depend on the current rounding mode, and therefore must 8173 // not be moved across instruction that may change that mode. 8174 [[fallthrough]]; 8175 case fp::ExceptionBehavior::ebMayTrap: 8176 // These must not be moved across calls or instructions that may change 8177 // floating-point exception masks. 8178 PendingConstrainedFP.push_back(OutChain); 8179 break; 8180 case fp::ExceptionBehavior::ebStrict: 8181 // These must not be moved across calls or instructions that may change 8182 // floating-point exception masks or read floating-point exception flags. 8183 // In addition, they cannot be optimized out even if unused. 8184 PendingConstrainedFPStrict.push_back(OutChain); 8185 break; 8186 } 8187 }; 8188 8189 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8190 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 8191 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 8192 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 8193 8194 SDNodeFlags Flags; 8195 if (EB == fp::ExceptionBehavior::ebIgnore) 8196 Flags.setNoFPExcept(true); 8197 8198 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 8199 Flags.copyFMF(*FPOp); 8200 8201 unsigned Opcode; 8202 switch (FPI.getIntrinsicID()) { 8203 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8204 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8205 case Intrinsic::INTRINSIC: \ 8206 Opcode = ISD::STRICT_##DAGN; \ 8207 break; 8208 #include "llvm/IR/ConstrainedOps.def" 8209 case Intrinsic::experimental_constrained_fmuladd: { 8210 Opcode = ISD::STRICT_FMA; 8211 // Break fmuladd into fmul and fadd. 8212 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 8213 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 8214 Opers.pop_back(); 8215 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 8216 pushOutChain(Mul, EB); 8217 Opcode = ISD::STRICT_FADD; 8218 Opers.clear(); 8219 Opers.push_back(Mul.getValue(1)); 8220 Opers.push_back(Mul.getValue(0)); 8221 Opers.push_back(getValue(FPI.getArgOperand(2))); 8222 } 8223 break; 8224 } 8225 } 8226 8227 // A few strict DAG nodes carry additional operands that are not 8228 // set up by the default code above. 8229 switch (Opcode) { 8230 default: break; 8231 case ISD::STRICT_FP_ROUND: 8232 Opers.push_back( 8233 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 8234 break; 8235 case ISD::STRICT_FSETCC: 8236 case ISD::STRICT_FSETCCS: { 8237 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 8238 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 8239 if (TM.Options.NoNaNsFPMath) 8240 Condition = getFCmpCodeWithoutNaN(Condition); 8241 Opers.push_back(DAG.getCondCode(Condition)); 8242 break; 8243 } 8244 } 8245 8246 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 8247 pushOutChain(Result, EB); 8248 8249 SDValue FPResult = Result.getValue(0); 8250 setValue(&FPI, FPResult); 8251 } 8252 8253 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 8254 std::optional<unsigned> ResOPC; 8255 switch (VPIntrin.getIntrinsicID()) { 8256 case Intrinsic::vp_ctlz: { 8257 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8258 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 8259 break; 8260 } 8261 case Intrinsic::vp_cttz: { 8262 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8263 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 8264 break; 8265 } 8266 case Intrinsic::vp_cttz_elts: { 8267 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8268 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS; 8269 break; 8270 } 8271 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 8272 case Intrinsic::VPID: \ 8273 ResOPC = ISD::VPSD; \ 8274 break; 8275 #include "llvm/IR/VPIntrinsics.def" 8276 } 8277 8278 if (!ResOPC) 8279 llvm_unreachable( 8280 "Inconsistency: no SDNode available for this VPIntrinsic!"); 8281 8282 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 8283 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 8284 if (VPIntrin.getFastMathFlags().allowReassoc()) 8285 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 8286 : ISD::VP_REDUCE_FMUL; 8287 } 8288 8289 return *ResOPC; 8290 } 8291 8292 void SelectionDAGBuilder::visitVPLoad( 8293 const VPIntrinsic &VPIntrin, EVT VT, 8294 const SmallVectorImpl<SDValue> &OpValues) { 8295 SDLoc DL = getCurSDLoc(); 8296 Value *PtrOperand = VPIntrin.getArgOperand(0); 8297 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8298 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8299 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8300 SDValue LD; 8301 // Do not serialize variable-length loads of constant memory with 8302 // anything. 8303 if (!Alignment) 8304 Alignment = DAG.getEVTAlign(VT); 8305 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8306 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8307 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8308 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8309 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8310 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8311 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 8312 MMO, false /*IsExpanding */); 8313 if (AddToChain) 8314 PendingLoads.push_back(LD.getValue(1)); 8315 setValue(&VPIntrin, LD); 8316 } 8317 8318 void SelectionDAGBuilder::visitVPGather( 8319 const VPIntrinsic &VPIntrin, EVT VT, 8320 const SmallVectorImpl<SDValue> &OpValues) { 8321 SDLoc DL = getCurSDLoc(); 8322 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8323 Value *PtrOperand = VPIntrin.getArgOperand(0); 8324 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8325 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8326 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8327 SDValue LD; 8328 if (!Alignment) 8329 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8330 unsigned AS = 8331 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8332 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8333 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8334 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8335 SDValue Base, Index, Scale; 8336 ISD::MemIndexType IndexType; 8337 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8338 this, VPIntrin.getParent(), 8339 VT.getScalarStoreSize()); 8340 if (!UniformBase) { 8341 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8342 Index = getValue(PtrOperand); 8343 IndexType = ISD::SIGNED_SCALED; 8344 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8345 } 8346 EVT IdxVT = Index.getValueType(); 8347 EVT EltTy = IdxVT.getVectorElementType(); 8348 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8349 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8350 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8351 } 8352 LD = DAG.getGatherVP( 8353 DAG.getVTList(VT, MVT::Other), VT, DL, 8354 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 8355 IndexType); 8356 PendingLoads.push_back(LD.getValue(1)); 8357 setValue(&VPIntrin, LD); 8358 } 8359 8360 void SelectionDAGBuilder::visitVPStore( 8361 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8362 SDLoc DL = getCurSDLoc(); 8363 Value *PtrOperand = VPIntrin.getArgOperand(1); 8364 EVT VT = OpValues[0].getValueType(); 8365 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8366 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8367 SDValue ST; 8368 if (!Alignment) 8369 Alignment = DAG.getEVTAlign(VT); 8370 SDValue Ptr = OpValues[1]; 8371 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 8372 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8373 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8374 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8375 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 8376 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 8377 /* IsTruncating */ false, /*IsCompressing*/ false); 8378 DAG.setRoot(ST); 8379 setValue(&VPIntrin, ST); 8380 } 8381 8382 void SelectionDAGBuilder::visitVPScatter( 8383 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8384 SDLoc DL = getCurSDLoc(); 8385 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8386 Value *PtrOperand = VPIntrin.getArgOperand(1); 8387 EVT VT = OpValues[0].getValueType(); 8388 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8389 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8390 SDValue ST; 8391 if (!Alignment) 8392 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8393 unsigned AS = 8394 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8395 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8396 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8397 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8398 SDValue Base, Index, Scale; 8399 ISD::MemIndexType IndexType; 8400 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8401 this, VPIntrin.getParent(), 8402 VT.getScalarStoreSize()); 8403 if (!UniformBase) { 8404 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8405 Index = getValue(PtrOperand); 8406 IndexType = ISD::SIGNED_SCALED; 8407 Scale = 8408 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8409 } 8410 EVT IdxVT = Index.getValueType(); 8411 EVT EltTy = IdxVT.getVectorElementType(); 8412 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8413 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8414 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8415 } 8416 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8417 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8418 OpValues[2], OpValues[3]}, 8419 MMO, IndexType); 8420 DAG.setRoot(ST); 8421 setValue(&VPIntrin, ST); 8422 } 8423 8424 void SelectionDAGBuilder::visitVPStridedLoad( 8425 const VPIntrinsic &VPIntrin, EVT VT, 8426 const SmallVectorImpl<SDValue> &OpValues) { 8427 SDLoc DL = getCurSDLoc(); 8428 Value *PtrOperand = VPIntrin.getArgOperand(0); 8429 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8430 if (!Alignment) 8431 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8432 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8433 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8434 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8435 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8436 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8437 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8438 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8439 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8440 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8441 8442 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8443 OpValues[2], OpValues[3], MMO, 8444 false /*IsExpanding*/); 8445 8446 if (AddToChain) 8447 PendingLoads.push_back(LD.getValue(1)); 8448 setValue(&VPIntrin, LD); 8449 } 8450 8451 void SelectionDAGBuilder::visitVPStridedStore( 8452 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8453 SDLoc DL = getCurSDLoc(); 8454 Value *PtrOperand = VPIntrin.getArgOperand(1); 8455 EVT VT = OpValues[0].getValueType(); 8456 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8457 if (!Alignment) 8458 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8459 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8460 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8461 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8462 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8463 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8464 8465 SDValue ST = DAG.getStridedStoreVP( 8466 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8467 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8468 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8469 /*IsCompressing*/ false); 8470 8471 DAG.setRoot(ST); 8472 setValue(&VPIntrin, ST); 8473 } 8474 8475 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8477 SDLoc DL = getCurSDLoc(); 8478 8479 ISD::CondCode Condition; 8480 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8481 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8482 if (IsFP) { 8483 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8484 // flags, but calls that don't return floating-point types can't be 8485 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8486 Condition = getFCmpCondCode(CondCode); 8487 if (TM.Options.NoNaNsFPMath) 8488 Condition = getFCmpCodeWithoutNaN(Condition); 8489 } else { 8490 Condition = getICmpCondCode(CondCode); 8491 } 8492 8493 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8494 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8495 // #2 is the condition code 8496 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8497 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8498 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8499 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8500 "Unexpected target EVL type"); 8501 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8502 8503 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8504 VPIntrin.getType()); 8505 setValue(&VPIntrin, 8506 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8507 } 8508 8509 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8510 const VPIntrinsic &VPIntrin) { 8511 SDLoc DL = getCurSDLoc(); 8512 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8513 8514 auto IID = VPIntrin.getIntrinsicID(); 8515 8516 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8517 return visitVPCmp(*CmpI); 8518 8519 SmallVector<EVT, 4> ValueVTs; 8520 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8521 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8522 SDVTList VTs = DAG.getVTList(ValueVTs); 8523 8524 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8525 8526 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8527 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8528 "Unexpected target EVL type"); 8529 8530 // Request operands. 8531 SmallVector<SDValue, 7> OpValues; 8532 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8533 auto Op = getValue(VPIntrin.getArgOperand(I)); 8534 if (I == EVLParamPos) 8535 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8536 OpValues.push_back(Op); 8537 } 8538 8539 switch (Opcode) { 8540 default: { 8541 SDNodeFlags SDFlags; 8542 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8543 SDFlags.copyFMF(*FPMO); 8544 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8545 setValue(&VPIntrin, Result); 8546 break; 8547 } 8548 case ISD::VP_LOAD: 8549 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8550 break; 8551 case ISD::VP_GATHER: 8552 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8553 break; 8554 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8555 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8556 break; 8557 case ISD::VP_STORE: 8558 visitVPStore(VPIntrin, OpValues); 8559 break; 8560 case ISD::VP_SCATTER: 8561 visitVPScatter(VPIntrin, OpValues); 8562 break; 8563 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8564 visitVPStridedStore(VPIntrin, OpValues); 8565 break; 8566 case ISD::VP_FMULADD: { 8567 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8568 SDNodeFlags SDFlags; 8569 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8570 SDFlags.copyFMF(*FPMO); 8571 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8572 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8573 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8574 } else { 8575 SDValue Mul = DAG.getNode( 8576 ISD::VP_FMUL, DL, VTs, 8577 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8578 SDValue Add = 8579 DAG.getNode(ISD::VP_FADD, DL, VTs, 8580 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8581 setValue(&VPIntrin, Add); 8582 } 8583 break; 8584 } 8585 case ISD::VP_IS_FPCLASS: { 8586 const DataLayout DLayout = DAG.getDataLayout(); 8587 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8588 auto Constant = OpValues[1]->getAsZExtVal(); 8589 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8590 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8591 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8592 setValue(&VPIntrin, V); 8593 return; 8594 } 8595 case ISD::VP_INTTOPTR: { 8596 SDValue N = OpValues[0]; 8597 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8598 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8599 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8600 OpValues[2]); 8601 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8602 OpValues[2]); 8603 setValue(&VPIntrin, N); 8604 break; 8605 } 8606 case ISD::VP_PTRTOINT: { 8607 SDValue N = OpValues[0]; 8608 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8609 VPIntrin.getType()); 8610 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8611 VPIntrin.getOperand(0)->getType()); 8612 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8613 OpValues[2]); 8614 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8615 OpValues[2]); 8616 setValue(&VPIntrin, N); 8617 break; 8618 } 8619 case ISD::VP_ABS: 8620 case ISD::VP_CTLZ: 8621 case ISD::VP_CTLZ_ZERO_UNDEF: 8622 case ISD::VP_CTTZ: 8623 case ISD::VP_CTTZ_ZERO_UNDEF: 8624 case ISD::VP_CTTZ_ELTS_ZERO_UNDEF: 8625 case ISD::VP_CTTZ_ELTS: { 8626 SDValue Result = 8627 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8628 setValue(&VPIntrin, Result); 8629 break; 8630 } 8631 } 8632 } 8633 8634 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8635 const BasicBlock *EHPadBB, 8636 MCSymbol *&BeginLabel) { 8637 MachineFunction &MF = DAG.getMachineFunction(); 8638 8639 // Insert a label before the invoke call to mark the try range. This can be 8640 // used to detect deletion of the invoke via the MachineModuleInfo. 8641 BeginLabel = MF.getContext().createTempSymbol(); 8642 8643 // For SjLj, keep track of which landing pads go with which invokes 8644 // so as to maintain the ordering of pads in the LSDA. 8645 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite(); 8646 if (CallSiteIndex) { 8647 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8648 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex); 8649 8650 // Now that the call site is handled, stop tracking it. 8651 FuncInfo.setCurrentCallSite(0); 8652 } 8653 8654 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8655 } 8656 8657 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8658 const BasicBlock *EHPadBB, 8659 MCSymbol *BeginLabel) { 8660 assert(BeginLabel && "BeginLabel should've been set"); 8661 8662 MachineFunction &MF = DAG.getMachineFunction(); 8663 8664 // Insert a label at the end of the invoke call to mark the try range. This 8665 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8666 MCSymbol *EndLabel = MF.getContext().createTempSymbol(); 8667 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8668 8669 // Inform MachineModuleInfo of range. 8670 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8671 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8672 // actually use outlined funclets and their LSDA info style. 8673 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8674 assert(II && "II should've been set"); 8675 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8676 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8677 } else if (!isScopedEHPersonality(Pers)) { 8678 assert(EHPadBB); 8679 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel); 8680 } 8681 8682 return Chain; 8683 } 8684 8685 std::pair<SDValue, SDValue> 8686 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8687 const BasicBlock *EHPadBB) { 8688 MCSymbol *BeginLabel = nullptr; 8689 8690 if (EHPadBB) { 8691 // Both PendingLoads and PendingExports must be flushed here; 8692 // this call might not return. 8693 (void)getRoot(); 8694 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8695 CLI.setChain(getRoot()); 8696 } 8697 8698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8699 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8700 8701 assert((CLI.IsTailCall || Result.second.getNode()) && 8702 "Non-null chain expected with non-tail call!"); 8703 assert((Result.second.getNode() || !Result.first.getNode()) && 8704 "Null value expected with tail call!"); 8705 8706 if (!Result.second.getNode()) { 8707 // As a special case, a null chain means that a tail call has been emitted 8708 // and the DAG root is already updated. 8709 HasTailCall = true; 8710 8711 // Since there's no actual continuation from this block, nothing can be 8712 // relying on us setting vregs for them. 8713 PendingExports.clear(); 8714 } else { 8715 DAG.setRoot(Result.second); 8716 } 8717 8718 if (EHPadBB) { 8719 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8720 BeginLabel)); 8721 Result.second = getRoot(); 8722 } 8723 8724 return Result; 8725 } 8726 8727 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8728 bool isTailCall, bool isMustTailCall, 8729 const BasicBlock *EHPadBB, 8730 const TargetLowering::PtrAuthInfo *PAI) { 8731 auto &DL = DAG.getDataLayout(); 8732 FunctionType *FTy = CB.getFunctionType(); 8733 Type *RetTy = CB.getType(); 8734 8735 TargetLowering::ArgListTy Args; 8736 Args.reserve(CB.arg_size()); 8737 8738 const Value *SwiftErrorVal = nullptr; 8739 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8740 8741 if (isTailCall) { 8742 // Avoid emitting tail calls in functions with the disable-tail-calls 8743 // attribute. 8744 auto *Caller = CB.getParent()->getParent(); 8745 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8746 "true" && !isMustTailCall) 8747 isTailCall = false; 8748 8749 // We can't tail call inside a function with a swifterror argument. Lowering 8750 // does not support this yet. It would have to move into the swifterror 8751 // register before the call. 8752 if (TLI.supportSwiftError() && 8753 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8754 isTailCall = false; 8755 } 8756 8757 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8758 TargetLowering::ArgListEntry Entry; 8759 const Value *V = *I; 8760 8761 // Skip empty types 8762 if (V->getType()->isEmptyTy()) 8763 continue; 8764 8765 SDValue ArgNode = getValue(V); 8766 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8767 8768 Entry.setAttributes(&CB, I - CB.arg_begin()); 8769 8770 // Use swifterror virtual register as input to the call. 8771 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8772 SwiftErrorVal = V; 8773 // We find the virtual register for the actual swifterror argument. 8774 // Instead of using the Value, we use the virtual register instead. 8775 Entry.Node = 8776 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8777 EVT(TLI.getPointerTy(DL))); 8778 } 8779 8780 Args.push_back(Entry); 8781 8782 // If we have an explicit sret argument that is an Instruction, (i.e., it 8783 // might point to function-local memory), we can't meaningfully tail-call. 8784 if (Entry.IsSRet && isa<Instruction>(V)) 8785 isTailCall = false; 8786 } 8787 8788 // If call site has a cfguardtarget operand bundle, create and add an 8789 // additional ArgListEntry. 8790 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8791 TargetLowering::ArgListEntry Entry; 8792 Value *V = Bundle->Inputs[0]; 8793 SDValue ArgNode = getValue(V); 8794 Entry.Node = ArgNode; 8795 Entry.Ty = V->getType(); 8796 Entry.IsCFGuardTarget = true; 8797 Args.push_back(Entry); 8798 } 8799 8800 // Check if target-independent constraints permit a tail call here. 8801 // Target-dependent constraints are checked within TLI->LowerCallTo. 8802 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8803 isTailCall = false; 8804 8805 // Disable tail calls if there is an swifterror argument. Targets have not 8806 // been updated to support tail calls. 8807 if (TLI.supportSwiftError() && SwiftErrorVal) 8808 isTailCall = false; 8809 8810 ConstantInt *CFIType = nullptr; 8811 if (CB.isIndirectCall()) { 8812 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8813 if (!TLI.supportKCFIBundles()) 8814 report_fatal_error( 8815 "Target doesn't support calls with kcfi operand bundles."); 8816 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8817 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8818 } 8819 } 8820 8821 SDValue ConvControlToken; 8822 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) { 8823 auto *Token = Bundle->Inputs[0].get(); 8824 ConvControlToken = getValue(Token); 8825 } 8826 8827 TargetLowering::CallLoweringInfo CLI(DAG); 8828 CLI.setDebugLoc(getCurSDLoc()) 8829 .setChain(getRoot()) 8830 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8831 .setTailCall(isTailCall) 8832 .setConvergent(CB.isConvergent()) 8833 .setIsPreallocated( 8834 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8835 .setCFIType(CFIType) 8836 .setConvergenceControlToken(ConvControlToken); 8837 8838 // Set the pointer authentication info if we have it. 8839 if (PAI) { 8840 if (!TLI.supportPtrAuthBundles()) 8841 report_fatal_error( 8842 "This target doesn't support calls with ptrauth operand bundles."); 8843 CLI.setPtrAuth(*PAI); 8844 } 8845 8846 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8847 8848 if (Result.first.getNode()) { 8849 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8850 setValue(&CB, Result.first); 8851 } 8852 8853 // The last element of CLI.InVals has the SDValue for swifterror return. 8854 // Here we copy it to a virtual register and update SwiftErrorMap for 8855 // book-keeping. 8856 if (SwiftErrorVal && TLI.supportSwiftError()) { 8857 // Get the last element of InVals. 8858 SDValue Src = CLI.InVals.back(); 8859 Register VReg = 8860 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8861 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8862 DAG.setRoot(CopyNode); 8863 } 8864 } 8865 8866 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8867 SelectionDAGBuilder &Builder) { 8868 // Check to see if this load can be trivially constant folded, e.g. if the 8869 // input is from a string literal. 8870 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8871 // Cast pointer to the type we really want to load. 8872 Type *LoadTy = 8873 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8874 if (LoadVT.isVector()) 8875 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8876 8877 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8878 PointerType::getUnqual(LoadTy)); 8879 8880 if (const Constant *LoadCst = 8881 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8882 LoadTy, Builder.DAG.getDataLayout())) 8883 return Builder.getValue(LoadCst); 8884 } 8885 8886 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8887 // still constant memory, the input chain can be the entry node. 8888 SDValue Root; 8889 bool ConstantMemory = false; 8890 8891 // Do not serialize (non-volatile) loads of constant memory with anything. 8892 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8893 Root = Builder.DAG.getEntryNode(); 8894 ConstantMemory = true; 8895 } else { 8896 // Do not serialize non-volatile loads against each other. 8897 Root = Builder.DAG.getRoot(); 8898 } 8899 8900 SDValue Ptr = Builder.getValue(PtrVal); 8901 SDValue LoadVal = 8902 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8903 MachinePointerInfo(PtrVal), Align(1)); 8904 8905 if (!ConstantMemory) 8906 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8907 return LoadVal; 8908 } 8909 8910 /// Record the value for an instruction that produces an integer result, 8911 /// converting the type where necessary. 8912 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8913 SDValue Value, 8914 bool IsSigned) { 8915 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8916 I.getType(), true); 8917 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8918 setValue(&I, Value); 8919 } 8920 8921 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8922 /// true and lower it. Otherwise return false, and it will be lowered like a 8923 /// normal call. 8924 /// The caller already checked that \p I calls the appropriate LibFunc with a 8925 /// correct prototype. 8926 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8927 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8928 const Value *Size = I.getArgOperand(2); 8929 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8930 if (CSize && CSize->getZExtValue() == 0) { 8931 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8932 I.getType(), true); 8933 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8934 return true; 8935 } 8936 8937 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8938 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8939 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8940 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8941 if (Res.first.getNode()) { 8942 processIntegerCallValue(I, Res.first, true); 8943 PendingLoads.push_back(Res.second); 8944 return true; 8945 } 8946 8947 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8948 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8949 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8950 return false; 8951 8952 // If the target has a fast compare for the given size, it will return a 8953 // preferred load type for that size. Require that the load VT is legal and 8954 // that the target supports unaligned loads of that type. Otherwise, return 8955 // INVALID. 8956 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8958 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8959 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8960 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8961 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8962 // TODO: Check alignment of src and dest ptrs. 8963 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8964 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8965 if (!TLI.isTypeLegal(LVT) || 8966 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8967 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8968 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8969 } 8970 8971 return LVT; 8972 }; 8973 8974 // This turns into unaligned loads. We only do this if the target natively 8975 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8976 // we'll only produce a small number of byte loads. 8977 MVT LoadVT; 8978 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8979 switch (NumBitsToCompare) { 8980 default: 8981 return false; 8982 case 16: 8983 LoadVT = MVT::i16; 8984 break; 8985 case 32: 8986 LoadVT = MVT::i32; 8987 break; 8988 case 64: 8989 case 128: 8990 case 256: 8991 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8992 break; 8993 } 8994 8995 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8996 return false; 8997 8998 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8999 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 9000 9001 // Bitcast to a wide integer type if the loads are vectors. 9002 if (LoadVT.isVector()) { 9003 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 9004 LoadL = DAG.getBitcast(CmpVT, LoadL); 9005 LoadR = DAG.getBitcast(CmpVT, LoadR); 9006 } 9007 9008 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 9009 processIntegerCallValue(I, Cmp, false); 9010 return true; 9011 } 9012 9013 /// See if we can lower a memchr call into an optimized form. If so, return 9014 /// true and lower it. Otherwise return false, and it will be lowered like a 9015 /// normal call. 9016 /// The caller already checked that \p I calls the appropriate LibFunc with a 9017 /// correct prototype. 9018 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 9019 const Value *Src = I.getArgOperand(0); 9020 const Value *Char = I.getArgOperand(1); 9021 const Value *Length = I.getArgOperand(2); 9022 9023 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9024 std::pair<SDValue, SDValue> Res = 9025 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 9026 getValue(Src), getValue(Char), getValue(Length), 9027 MachinePointerInfo(Src)); 9028 if (Res.first.getNode()) { 9029 setValue(&I, Res.first); 9030 PendingLoads.push_back(Res.second); 9031 return true; 9032 } 9033 9034 return false; 9035 } 9036 9037 /// See if we can lower a mempcpy call into an optimized form. If so, return 9038 /// true and lower it. Otherwise return false, and it will be lowered like a 9039 /// normal call. 9040 /// The caller already checked that \p I calls the appropriate LibFunc with a 9041 /// correct prototype. 9042 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 9043 SDValue Dst = getValue(I.getArgOperand(0)); 9044 SDValue Src = getValue(I.getArgOperand(1)); 9045 SDValue Size = getValue(I.getArgOperand(2)); 9046 9047 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 9048 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 9049 // DAG::getMemcpy needs Alignment to be defined. 9050 Align Alignment = std::min(DstAlign, SrcAlign); 9051 9052 SDLoc sdl = getCurSDLoc(); 9053 9054 // In the mempcpy context we need to pass in a false value for isTailCall 9055 // because the return pointer needs to be adjusted by the size of 9056 // the copied memory. 9057 SDValue Root = getMemoryRoot(); 9058 SDValue MC = DAG.getMemcpy( 9059 Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr, 9060 std::nullopt, MachinePointerInfo(I.getArgOperand(0)), 9061 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata()); 9062 assert(MC.getNode() != nullptr && 9063 "** memcpy should not be lowered as TailCall in mempcpy context **"); 9064 DAG.setRoot(MC); 9065 9066 // Check if Size needs to be truncated or extended. 9067 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 9068 9069 // Adjust return pointer to point just past the last dst byte. 9070 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 9071 Dst, Size); 9072 setValue(&I, DstPlusSize); 9073 return true; 9074 } 9075 9076 /// See if we can lower a strcpy call into an optimized form. If so, return 9077 /// true and lower it, otherwise return false and it will be lowered like a 9078 /// normal call. 9079 /// The caller already checked that \p I calls the appropriate LibFunc with a 9080 /// correct prototype. 9081 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 9082 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9083 9084 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9085 std::pair<SDValue, SDValue> Res = 9086 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 9087 getValue(Arg0), getValue(Arg1), 9088 MachinePointerInfo(Arg0), 9089 MachinePointerInfo(Arg1), isStpcpy); 9090 if (Res.first.getNode()) { 9091 setValue(&I, Res.first); 9092 DAG.setRoot(Res.second); 9093 return true; 9094 } 9095 9096 return false; 9097 } 9098 9099 /// See if we can lower a strcmp call into an optimized form. If so, return 9100 /// true and lower it, otherwise return false and it will be lowered like a 9101 /// normal call. 9102 /// The caller already checked that \p I calls the appropriate LibFunc with a 9103 /// correct prototype. 9104 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 9105 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9106 9107 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9108 std::pair<SDValue, SDValue> Res = 9109 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 9110 getValue(Arg0), getValue(Arg1), 9111 MachinePointerInfo(Arg0), 9112 MachinePointerInfo(Arg1)); 9113 if (Res.first.getNode()) { 9114 processIntegerCallValue(I, Res.first, true); 9115 PendingLoads.push_back(Res.second); 9116 return true; 9117 } 9118 9119 return false; 9120 } 9121 9122 /// See if we can lower a strlen call into an optimized form. If so, return 9123 /// true and lower it, otherwise return false and it will be lowered like a 9124 /// normal call. 9125 /// The caller already checked that \p I calls the appropriate LibFunc with a 9126 /// correct prototype. 9127 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 9128 const Value *Arg0 = I.getArgOperand(0); 9129 9130 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9131 std::pair<SDValue, SDValue> Res = 9132 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 9133 getValue(Arg0), MachinePointerInfo(Arg0)); 9134 if (Res.first.getNode()) { 9135 processIntegerCallValue(I, Res.first, false); 9136 PendingLoads.push_back(Res.second); 9137 return true; 9138 } 9139 9140 return false; 9141 } 9142 9143 /// See if we can lower a strnlen call into an optimized form. If so, return 9144 /// true and lower it, otherwise return false and it will be lowered like a 9145 /// normal call. 9146 /// The caller already checked that \p I calls the appropriate LibFunc with a 9147 /// correct prototype. 9148 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 9149 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9150 9151 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9152 std::pair<SDValue, SDValue> Res = 9153 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 9154 getValue(Arg0), getValue(Arg1), 9155 MachinePointerInfo(Arg0)); 9156 if (Res.first.getNode()) { 9157 processIntegerCallValue(I, Res.first, false); 9158 PendingLoads.push_back(Res.second); 9159 return true; 9160 } 9161 9162 return false; 9163 } 9164 9165 /// See if we can lower a unary floating-point operation into an SDNode with 9166 /// the specified Opcode. If so, return true and lower it, otherwise return 9167 /// false and it will be lowered like a normal call. 9168 /// The caller already checked that \p I calls the appropriate LibFunc with a 9169 /// correct prototype. 9170 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 9171 unsigned Opcode) { 9172 // We already checked this call's prototype; verify it doesn't modify errno. 9173 if (!I.onlyReadsMemory()) 9174 return false; 9175 9176 SDNodeFlags Flags; 9177 Flags.copyFMF(cast<FPMathOperator>(I)); 9178 9179 SDValue Tmp = getValue(I.getArgOperand(0)); 9180 setValue(&I, 9181 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 9182 return true; 9183 } 9184 9185 /// See if we can lower a binary floating-point operation into an SDNode with 9186 /// the specified Opcode. If so, return true and lower it. Otherwise return 9187 /// false, and it will be lowered like a normal call. 9188 /// The caller already checked that \p I calls the appropriate LibFunc with a 9189 /// correct prototype. 9190 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 9191 unsigned Opcode) { 9192 // We already checked this call's prototype; verify it doesn't modify errno. 9193 if (!I.onlyReadsMemory()) 9194 return false; 9195 9196 SDNodeFlags Flags; 9197 Flags.copyFMF(cast<FPMathOperator>(I)); 9198 9199 SDValue Tmp0 = getValue(I.getArgOperand(0)); 9200 SDValue Tmp1 = getValue(I.getArgOperand(1)); 9201 EVT VT = Tmp0.getValueType(); 9202 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 9203 return true; 9204 } 9205 9206 void SelectionDAGBuilder::visitCall(const CallInst &I) { 9207 // Handle inline assembly differently. 9208 if (I.isInlineAsm()) { 9209 visitInlineAsm(I); 9210 return; 9211 } 9212 9213 diagnoseDontCall(I); 9214 9215 if (Function *F = I.getCalledFunction()) { 9216 if (F->isDeclaration()) { 9217 // Is this an LLVM intrinsic or a target-specific intrinsic? 9218 unsigned IID = F->getIntrinsicID(); 9219 if (!IID) 9220 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 9221 IID = II->getIntrinsicID(F); 9222 9223 if (IID) { 9224 visitIntrinsicCall(I, IID); 9225 return; 9226 } 9227 } 9228 9229 // Check for well-known libc/libm calls. If the function is internal, it 9230 // can't be a library call. Don't do the check if marked as nobuiltin for 9231 // some reason or the call site requires strict floating point semantics. 9232 LibFunc Func; 9233 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 9234 F->hasName() && LibInfo->getLibFunc(*F, Func) && 9235 LibInfo->hasOptimizedCodeGen(Func)) { 9236 switch (Func) { 9237 default: break; 9238 case LibFunc_bcmp: 9239 if (visitMemCmpBCmpCall(I)) 9240 return; 9241 break; 9242 case LibFunc_copysign: 9243 case LibFunc_copysignf: 9244 case LibFunc_copysignl: 9245 // We already checked this call's prototype; verify it doesn't modify 9246 // errno. 9247 if (I.onlyReadsMemory()) { 9248 SDValue LHS = getValue(I.getArgOperand(0)); 9249 SDValue RHS = getValue(I.getArgOperand(1)); 9250 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 9251 LHS.getValueType(), LHS, RHS)); 9252 return; 9253 } 9254 break; 9255 case LibFunc_fabs: 9256 case LibFunc_fabsf: 9257 case LibFunc_fabsl: 9258 if (visitUnaryFloatCall(I, ISD::FABS)) 9259 return; 9260 break; 9261 case LibFunc_fmin: 9262 case LibFunc_fminf: 9263 case LibFunc_fminl: 9264 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 9265 return; 9266 break; 9267 case LibFunc_fmax: 9268 case LibFunc_fmaxf: 9269 case LibFunc_fmaxl: 9270 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 9271 return; 9272 break; 9273 case LibFunc_fminimum_num: 9274 case LibFunc_fminimum_numf: 9275 case LibFunc_fminimum_numl: 9276 if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM)) 9277 return; 9278 break; 9279 case LibFunc_fmaximum_num: 9280 case LibFunc_fmaximum_numf: 9281 case LibFunc_fmaximum_numl: 9282 if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM)) 9283 return; 9284 break; 9285 case LibFunc_sin: 9286 case LibFunc_sinf: 9287 case LibFunc_sinl: 9288 if (visitUnaryFloatCall(I, ISD::FSIN)) 9289 return; 9290 break; 9291 case LibFunc_cos: 9292 case LibFunc_cosf: 9293 case LibFunc_cosl: 9294 if (visitUnaryFloatCall(I, ISD::FCOS)) 9295 return; 9296 break; 9297 case LibFunc_tan: 9298 case LibFunc_tanf: 9299 case LibFunc_tanl: 9300 if (visitUnaryFloatCall(I, ISD::FTAN)) 9301 return; 9302 break; 9303 case LibFunc_asin: 9304 case LibFunc_asinf: 9305 case LibFunc_asinl: 9306 if (visitUnaryFloatCall(I, ISD::FASIN)) 9307 return; 9308 break; 9309 case LibFunc_acos: 9310 case LibFunc_acosf: 9311 case LibFunc_acosl: 9312 if (visitUnaryFloatCall(I, ISD::FACOS)) 9313 return; 9314 break; 9315 case LibFunc_atan: 9316 case LibFunc_atanf: 9317 case LibFunc_atanl: 9318 if (visitUnaryFloatCall(I, ISD::FATAN)) 9319 return; 9320 break; 9321 case LibFunc_sinh: 9322 case LibFunc_sinhf: 9323 case LibFunc_sinhl: 9324 if (visitUnaryFloatCall(I, ISD::FSINH)) 9325 return; 9326 break; 9327 case LibFunc_cosh: 9328 case LibFunc_coshf: 9329 case LibFunc_coshl: 9330 if (visitUnaryFloatCall(I, ISD::FCOSH)) 9331 return; 9332 break; 9333 case LibFunc_tanh: 9334 case LibFunc_tanhf: 9335 case LibFunc_tanhl: 9336 if (visitUnaryFloatCall(I, ISD::FTANH)) 9337 return; 9338 break; 9339 case LibFunc_sqrt: 9340 case LibFunc_sqrtf: 9341 case LibFunc_sqrtl: 9342 case LibFunc_sqrt_finite: 9343 case LibFunc_sqrtf_finite: 9344 case LibFunc_sqrtl_finite: 9345 if (visitUnaryFloatCall(I, ISD::FSQRT)) 9346 return; 9347 break; 9348 case LibFunc_floor: 9349 case LibFunc_floorf: 9350 case LibFunc_floorl: 9351 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 9352 return; 9353 break; 9354 case LibFunc_nearbyint: 9355 case LibFunc_nearbyintf: 9356 case LibFunc_nearbyintl: 9357 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 9358 return; 9359 break; 9360 case LibFunc_ceil: 9361 case LibFunc_ceilf: 9362 case LibFunc_ceill: 9363 if (visitUnaryFloatCall(I, ISD::FCEIL)) 9364 return; 9365 break; 9366 case LibFunc_rint: 9367 case LibFunc_rintf: 9368 case LibFunc_rintl: 9369 if (visitUnaryFloatCall(I, ISD::FRINT)) 9370 return; 9371 break; 9372 case LibFunc_round: 9373 case LibFunc_roundf: 9374 case LibFunc_roundl: 9375 if (visitUnaryFloatCall(I, ISD::FROUND)) 9376 return; 9377 break; 9378 case LibFunc_trunc: 9379 case LibFunc_truncf: 9380 case LibFunc_truncl: 9381 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 9382 return; 9383 break; 9384 case LibFunc_log2: 9385 case LibFunc_log2f: 9386 case LibFunc_log2l: 9387 if (visitUnaryFloatCall(I, ISD::FLOG2)) 9388 return; 9389 break; 9390 case LibFunc_exp2: 9391 case LibFunc_exp2f: 9392 case LibFunc_exp2l: 9393 if (visitUnaryFloatCall(I, ISD::FEXP2)) 9394 return; 9395 break; 9396 case LibFunc_exp10: 9397 case LibFunc_exp10f: 9398 case LibFunc_exp10l: 9399 if (visitUnaryFloatCall(I, ISD::FEXP10)) 9400 return; 9401 break; 9402 case LibFunc_ldexp: 9403 case LibFunc_ldexpf: 9404 case LibFunc_ldexpl: 9405 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 9406 return; 9407 break; 9408 case LibFunc_memcmp: 9409 if (visitMemCmpBCmpCall(I)) 9410 return; 9411 break; 9412 case LibFunc_mempcpy: 9413 if (visitMemPCpyCall(I)) 9414 return; 9415 break; 9416 case LibFunc_memchr: 9417 if (visitMemChrCall(I)) 9418 return; 9419 break; 9420 case LibFunc_strcpy: 9421 if (visitStrCpyCall(I, false)) 9422 return; 9423 break; 9424 case LibFunc_stpcpy: 9425 if (visitStrCpyCall(I, true)) 9426 return; 9427 break; 9428 case LibFunc_strcmp: 9429 if (visitStrCmpCall(I)) 9430 return; 9431 break; 9432 case LibFunc_strlen: 9433 if (visitStrLenCall(I)) 9434 return; 9435 break; 9436 case LibFunc_strnlen: 9437 if (visitStrNLenCall(I)) 9438 return; 9439 break; 9440 } 9441 } 9442 } 9443 9444 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 9445 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr); 9446 return; 9447 } 9448 9449 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9450 // have to do anything here to lower funclet bundles. 9451 // CFGuardTarget bundles are lowered in LowerCallTo. 9452 assert(!I.hasOperandBundlesOtherThan( 9453 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9454 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9455 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi, 9456 LLVMContext::OB_convergencectrl}) && 9457 "Cannot lower calls with arbitrary operand bundles!"); 9458 9459 SDValue Callee = getValue(I.getCalledOperand()); 9460 9461 if (I.hasDeoptState()) 9462 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9463 else 9464 // Check if we can potentially perform a tail call. More detailed checking 9465 // is be done within LowerCallTo, after more information about the call is 9466 // known. 9467 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9468 } 9469 9470 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle( 9471 const CallBase &CB, const BasicBlock *EHPadBB) { 9472 auto PAB = CB.getOperandBundle("ptrauth"); 9473 const Value *CalleeV = CB.getCalledOperand(); 9474 9475 // Gather the call ptrauth data from the operand bundle: 9476 // [ i32 <key>, i64 <discriminator> ] 9477 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]); 9478 const Value *Discriminator = PAB->Inputs[1]; 9479 9480 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key"); 9481 assert(Discriminator->getType()->isIntegerTy(64) && 9482 "Invalid ptrauth discriminator"); 9483 9484 // Look through ptrauth constants to find the raw callee. 9485 // Do a direct unauthenticated call if we found it and everything matches. 9486 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV)) 9487 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator, 9488 DAG.getDataLayout())) 9489 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(), 9490 CB.isMustTailCall(), EHPadBB); 9491 9492 // Functions should never be ptrauth-called directly. 9493 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call"); 9494 9495 // Otherwise, do an authenticated indirect call. 9496 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(), 9497 getValue(Discriminator)}; 9498 9499 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(), 9500 EHPadBB, &PAI); 9501 } 9502 9503 namespace { 9504 9505 /// AsmOperandInfo - This contains information for each constraint that we are 9506 /// lowering. 9507 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9508 public: 9509 /// CallOperand - If this is the result output operand or a clobber 9510 /// this is null, otherwise it is the incoming operand to the CallInst. 9511 /// This gets modified as the asm is processed. 9512 SDValue CallOperand; 9513 9514 /// AssignedRegs - If this is a register or register class operand, this 9515 /// contains the set of register corresponding to the operand. 9516 RegsForValue AssignedRegs; 9517 9518 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9519 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9520 } 9521 9522 /// Whether or not this operand accesses memory 9523 bool hasMemory(const TargetLowering &TLI) const { 9524 // Indirect operand accesses access memory. 9525 if (isIndirect) 9526 return true; 9527 9528 for (const auto &Code : Codes) 9529 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9530 return true; 9531 9532 return false; 9533 } 9534 }; 9535 9536 9537 } // end anonymous namespace 9538 9539 /// Make sure that the output operand \p OpInfo and its corresponding input 9540 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9541 /// out). 9542 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9543 SDISelAsmOperandInfo &MatchingOpInfo, 9544 SelectionDAG &DAG) { 9545 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9546 return; 9547 9548 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9549 const auto &TLI = DAG.getTargetLoweringInfo(); 9550 9551 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9552 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9553 OpInfo.ConstraintVT); 9554 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9555 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9556 MatchingOpInfo.ConstraintVT); 9557 if ((OpInfo.ConstraintVT.isInteger() != 9558 MatchingOpInfo.ConstraintVT.isInteger()) || 9559 (MatchRC.second != InputRC.second)) { 9560 // FIXME: error out in a more elegant fashion 9561 report_fatal_error("Unsupported asm: input constraint" 9562 " with a matching output constraint of" 9563 " incompatible type!"); 9564 } 9565 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9566 } 9567 9568 /// Get a direct memory input to behave well as an indirect operand. 9569 /// This may introduce stores, hence the need for a \p Chain. 9570 /// \return The (possibly updated) chain. 9571 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9572 SDISelAsmOperandInfo &OpInfo, 9573 SelectionDAG &DAG) { 9574 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9575 9576 // If we don't have an indirect input, put it in the constpool if we can, 9577 // otherwise spill it to a stack slot. 9578 // TODO: This isn't quite right. We need to handle these according to 9579 // the addressing mode that the constraint wants. Also, this may take 9580 // an additional register for the computation and we don't want that 9581 // either. 9582 9583 // If the operand is a float, integer, or vector constant, spill to a 9584 // constant pool entry to get its address. 9585 const Value *OpVal = OpInfo.CallOperandVal; 9586 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9587 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9588 OpInfo.CallOperand = DAG.getConstantPool( 9589 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9590 return Chain; 9591 } 9592 9593 // Otherwise, create a stack slot and emit a store to it before the asm. 9594 Type *Ty = OpVal->getType(); 9595 auto &DL = DAG.getDataLayout(); 9596 TypeSize TySize = DL.getTypeAllocSize(Ty); 9597 MachineFunction &MF = DAG.getMachineFunction(); 9598 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 9599 int StackID = 0; 9600 if (TySize.isScalable()) 9601 StackID = TFI->getStackIDForScalableVectors(); 9602 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(), 9603 DL.getPrefTypeAlign(Ty), false, 9604 nullptr, StackID); 9605 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9606 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9607 MachinePointerInfo::getFixedStack(MF, SSFI), 9608 TLI.getMemValueType(DL, Ty)); 9609 OpInfo.CallOperand = StackSlot; 9610 9611 return Chain; 9612 } 9613 9614 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9615 /// specified operand. We prefer to assign virtual registers, to allow the 9616 /// register allocator to handle the assignment process. However, if the asm 9617 /// uses features that we can't model on machineinstrs, we have SDISel do the 9618 /// allocation. This produces generally horrible, but correct, code. 9619 /// 9620 /// OpInfo describes the operand 9621 /// RefOpInfo describes the matching operand if any, the operand otherwise 9622 static std::optional<unsigned> 9623 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9624 SDISelAsmOperandInfo &OpInfo, 9625 SDISelAsmOperandInfo &RefOpInfo) { 9626 LLVMContext &Context = *DAG.getContext(); 9627 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9628 9629 MachineFunction &MF = DAG.getMachineFunction(); 9630 SmallVector<unsigned, 4> Regs; 9631 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9632 9633 // No work to do for memory/address operands. 9634 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9635 OpInfo.ConstraintType == TargetLowering::C_Address) 9636 return std::nullopt; 9637 9638 // If this is a constraint for a single physreg, or a constraint for a 9639 // register class, find it. 9640 unsigned AssignedReg; 9641 const TargetRegisterClass *RC; 9642 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9643 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9644 // RC is unset only on failure. Return immediately. 9645 if (!RC) 9646 return std::nullopt; 9647 9648 // Get the actual register value type. This is important, because the user 9649 // may have asked for (e.g.) the AX register in i32 type. We need to 9650 // remember that AX is actually i16 to get the right extension. 9651 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9652 9653 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9654 // If this is an FP operand in an integer register (or visa versa), or more 9655 // generally if the operand value disagrees with the register class we plan 9656 // to stick it in, fix the operand type. 9657 // 9658 // If this is an input value, the bitcast to the new type is done now. 9659 // Bitcast for output value is done at the end of visitInlineAsm(). 9660 if ((OpInfo.Type == InlineAsm::isOutput || 9661 OpInfo.Type == InlineAsm::isInput) && 9662 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9663 // Try to convert to the first EVT that the reg class contains. If the 9664 // types are identical size, use a bitcast to convert (e.g. two differing 9665 // vector types). Note: output bitcast is done at the end of 9666 // visitInlineAsm(). 9667 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9668 // Exclude indirect inputs while they are unsupported because the code 9669 // to perform the load is missing and thus OpInfo.CallOperand still 9670 // refers to the input address rather than the pointed-to value. 9671 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9672 OpInfo.CallOperand = 9673 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9674 OpInfo.ConstraintVT = RegVT; 9675 // If the operand is an FP value and we want it in integer registers, 9676 // use the corresponding integer type. This turns an f64 value into 9677 // i64, which can be passed with two i32 values on a 32-bit machine. 9678 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9679 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9680 if (OpInfo.Type == InlineAsm::isInput) 9681 OpInfo.CallOperand = 9682 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9683 OpInfo.ConstraintVT = VT; 9684 } 9685 } 9686 } 9687 9688 // No need to allocate a matching input constraint since the constraint it's 9689 // matching to has already been allocated. 9690 if (OpInfo.isMatchingInputConstraint()) 9691 return std::nullopt; 9692 9693 EVT ValueVT = OpInfo.ConstraintVT; 9694 if (OpInfo.ConstraintVT == MVT::Other) 9695 ValueVT = RegVT; 9696 9697 // Initialize NumRegs. 9698 unsigned NumRegs = 1; 9699 if (OpInfo.ConstraintVT != MVT::Other) 9700 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9701 9702 // If this is a constraint for a specific physical register, like {r17}, 9703 // assign it now. 9704 9705 // If this associated to a specific register, initialize iterator to correct 9706 // place. If virtual, make sure we have enough registers 9707 9708 // Initialize iterator if necessary 9709 TargetRegisterClass::iterator I = RC->begin(); 9710 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9711 9712 // Do not check for single registers. 9713 if (AssignedReg) { 9714 I = std::find(I, RC->end(), AssignedReg); 9715 if (I == RC->end()) { 9716 // RC does not contain the selected register, which indicates a 9717 // mismatch between the register and the required type/bitwidth. 9718 return {AssignedReg}; 9719 } 9720 } 9721 9722 for (; NumRegs; --NumRegs, ++I) { 9723 assert(I != RC->end() && "Ran out of registers to allocate!"); 9724 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9725 Regs.push_back(R); 9726 } 9727 9728 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9729 return std::nullopt; 9730 } 9731 9732 static unsigned 9733 findMatchingInlineAsmOperand(unsigned OperandNo, 9734 const std::vector<SDValue> &AsmNodeOperands) { 9735 // Scan until we find the definition we already emitted of this operand. 9736 unsigned CurOp = InlineAsm::Op_FirstOperand; 9737 for (; OperandNo; --OperandNo) { 9738 // Advance to the next operand. 9739 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9740 const InlineAsm::Flag F(OpFlag); 9741 assert( 9742 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9743 "Skipped past definitions?"); 9744 CurOp += F.getNumOperandRegisters() + 1; 9745 } 9746 return CurOp; 9747 } 9748 9749 namespace { 9750 9751 class ExtraFlags { 9752 unsigned Flags = 0; 9753 9754 public: 9755 explicit ExtraFlags(const CallBase &Call) { 9756 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9757 if (IA->hasSideEffects()) 9758 Flags |= InlineAsm::Extra_HasSideEffects; 9759 if (IA->isAlignStack()) 9760 Flags |= InlineAsm::Extra_IsAlignStack; 9761 if (Call.isConvergent()) 9762 Flags |= InlineAsm::Extra_IsConvergent; 9763 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9764 } 9765 9766 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9767 // Ideally, we would only check against memory constraints. However, the 9768 // meaning of an Other constraint can be target-specific and we can't easily 9769 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9770 // for Other constraints as well. 9771 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9772 OpInfo.ConstraintType == TargetLowering::C_Other) { 9773 if (OpInfo.Type == InlineAsm::isInput) 9774 Flags |= InlineAsm::Extra_MayLoad; 9775 else if (OpInfo.Type == InlineAsm::isOutput) 9776 Flags |= InlineAsm::Extra_MayStore; 9777 else if (OpInfo.Type == InlineAsm::isClobber) 9778 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9779 } 9780 } 9781 9782 unsigned get() const { return Flags; } 9783 }; 9784 9785 } // end anonymous namespace 9786 9787 static bool isFunction(SDValue Op) { 9788 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9789 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9790 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9791 9792 // In normal "call dllimport func" instruction (non-inlineasm) it force 9793 // indirect access by specifing call opcode. And usually specially print 9794 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9795 // not do in this way now. (In fact, this is similar with "Data Access" 9796 // action). So here we ignore dllimport function. 9797 if (Fn && !Fn->hasDLLImportStorageClass()) 9798 return true; 9799 } 9800 } 9801 return false; 9802 } 9803 9804 /// visitInlineAsm - Handle a call to an InlineAsm object. 9805 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9806 const BasicBlock *EHPadBB) { 9807 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9808 9809 /// ConstraintOperands - Information about all of the constraints. 9810 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9811 9812 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9813 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9814 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9815 9816 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9817 // AsmDialect, MayLoad, MayStore). 9818 bool HasSideEffect = IA->hasSideEffects(); 9819 ExtraFlags ExtraInfo(Call); 9820 9821 for (auto &T : TargetConstraints) { 9822 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9823 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9824 9825 if (OpInfo.CallOperandVal) 9826 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9827 9828 if (!HasSideEffect) 9829 HasSideEffect = OpInfo.hasMemory(TLI); 9830 9831 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9832 // FIXME: Could we compute this on OpInfo rather than T? 9833 9834 // Compute the constraint code and ConstraintType to use. 9835 TLI.ComputeConstraintToUse(T, SDValue()); 9836 9837 if (T.ConstraintType == TargetLowering::C_Immediate && 9838 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9839 // We've delayed emitting a diagnostic like the "n" constraint because 9840 // inlining could cause an integer showing up. 9841 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9842 "' expects an integer constant " 9843 "expression"); 9844 9845 ExtraInfo.update(T); 9846 } 9847 9848 // We won't need to flush pending loads if this asm doesn't touch 9849 // memory and is nonvolatile. 9850 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9851 9852 bool EmitEHLabels = isa<InvokeInst>(Call); 9853 if (EmitEHLabels) { 9854 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9855 } 9856 bool IsCallBr = isa<CallBrInst>(Call); 9857 9858 if (IsCallBr || EmitEHLabels) { 9859 // If this is a callbr or invoke we need to flush pending exports since 9860 // inlineasm_br and invoke are terminators. 9861 // We need to do this before nodes are glued to the inlineasm_br node. 9862 Chain = getControlRoot(); 9863 } 9864 9865 MCSymbol *BeginLabel = nullptr; 9866 if (EmitEHLabels) { 9867 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9868 } 9869 9870 int OpNo = -1; 9871 SmallVector<StringRef> AsmStrs; 9872 IA->collectAsmStrs(AsmStrs); 9873 9874 // Second pass over the constraints: compute which constraint option to use. 9875 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9876 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9877 OpNo++; 9878 9879 // If this is an output operand with a matching input operand, look up the 9880 // matching input. If their types mismatch, e.g. one is an integer, the 9881 // other is floating point, or their sizes are different, flag it as an 9882 // error. 9883 if (OpInfo.hasMatchingInput()) { 9884 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9885 patchMatchingInput(OpInfo, Input, DAG); 9886 } 9887 9888 // Compute the constraint code and ConstraintType to use. 9889 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9890 9891 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9892 OpInfo.Type == InlineAsm::isClobber) || 9893 OpInfo.ConstraintType == TargetLowering::C_Address) 9894 continue; 9895 9896 // In Linux PIC model, there are 4 cases about value/label addressing: 9897 // 9898 // 1: Function call or Label jmp inside the module. 9899 // 2: Data access (such as global variable, static variable) inside module. 9900 // 3: Function call or Label jmp outside the module. 9901 // 4: Data access (such as global variable) outside the module. 9902 // 9903 // Due to current llvm inline asm architecture designed to not "recognize" 9904 // the asm code, there are quite troubles for us to treat mem addressing 9905 // differently for same value/adress used in different instuctions. 9906 // For example, in pic model, call a func may in plt way or direclty 9907 // pc-related, but lea/mov a function adress may use got. 9908 // 9909 // Here we try to "recognize" function call for the case 1 and case 3 in 9910 // inline asm. And try to adjust the constraint for them. 9911 // 9912 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9913 // label, so here we don't handle jmp function label now, but we need to 9914 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9915 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9916 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9917 TM.getCodeModel() != CodeModel::Large) { 9918 OpInfo.isIndirect = false; 9919 OpInfo.ConstraintType = TargetLowering::C_Address; 9920 } 9921 9922 // If this is a memory input, and if the operand is not indirect, do what we 9923 // need to provide an address for the memory input. 9924 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9925 !OpInfo.isIndirect) { 9926 assert((OpInfo.isMultipleAlternative || 9927 (OpInfo.Type == InlineAsm::isInput)) && 9928 "Can only indirectify direct input operands!"); 9929 9930 // Memory operands really want the address of the value. 9931 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9932 9933 // There is no longer a Value* corresponding to this operand. 9934 OpInfo.CallOperandVal = nullptr; 9935 9936 // It is now an indirect operand. 9937 OpInfo.isIndirect = true; 9938 } 9939 9940 } 9941 9942 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9943 std::vector<SDValue> AsmNodeOperands; 9944 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9945 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9946 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9947 9948 // If we have a !srcloc metadata node associated with it, we want to attach 9949 // this to the ultimately generated inline asm machineinstr. To do this, we 9950 // pass in the third operand as this (potentially null) inline asm MDNode. 9951 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9952 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9953 9954 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9955 // bits as operand 3. 9956 AsmNodeOperands.push_back(DAG.getTargetConstant( 9957 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9958 9959 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9960 // this, assign virtual and physical registers for inputs and otput. 9961 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9962 // Assign Registers. 9963 SDISelAsmOperandInfo &RefOpInfo = 9964 OpInfo.isMatchingInputConstraint() 9965 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9966 : OpInfo; 9967 const auto RegError = 9968 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9969 if (RegError) { 9970 const MachineFunction &MF = DAG.getMachineFunction(); 9971 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9972 const char *RegName = TRI.getName(*RegError); 9973 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9974 "' allocated for constraint '" + 9975 Twine(OpInfo.ConstraintCode) + 9976 "' does not match required type"); 9977 return; 9978 } 9979 9980 auto DetectWriteToReservedRegister = [&]() { 9981 const MachineFunction &MF = DAG.getMachineFunction(); 9982 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9983 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9984 if (Register::isPhysicalRegister(Reg) && 9985 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9986 const char *RegName = TRI.getName(Reg); 9987 emitInlineAsmError(Call, "write to reserved register '" + 9988 Twine(RegName) + "'"); 9989 return true; 9990 } 9991 } 9992 return false; 9993 }; 9994 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9995 (OpInfo.Type == InlineAsm::isInput && 9996 !OpInfo.isMatchingInputConstraint())) && 9997 "Only address as input operand is allowed."); 9998 9999 switch (OpInfo.Type) { 10000 case InlineAsm::isOutput: 10001 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 10002 const InlineAsm::ConstraintCode ConstraintID = 10003 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10004 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10005 "Failed to convert memory constraint code to constraint id."); 10006 10007 // Add information to the INLINEASM node to know about this output. 10008 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 10009 OpFlags.setMemConstraint(ConstraintID); 10010 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 10011 MVT::i32)); 10012 AsmNodeOperands.push_back(OpInfo.CallOperand); 10013 } else { 10014 // Otherwise, this outputs to a register (directly for C_Register / 10015 // C_RegisterClass, and a target-defined fashion for 10016 // C_Immediate/C_Other). Find a register that we can use. 10017 if (OpInfo.AssignedRegs.Regs.empty()) { 10018 emitInlineAsmError( 10019 Call, "couldn't allocate output register for constraint '" + 10020 Twine(OpInfo.ConstraintCode) + "'"); 10021 return; 10022 } 10023 10024 if (DetectWriteToReservedRegister()) 10025 return; 10026 10027 // Add information to the INLINEASM node to know that this register is 10028 // set. 10029 OpInfo.AssignedRegs.AddInlineAsmOperands( 10030 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 10031 : InlineAsm::Kind::RegDef, 10032 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 10033 } 10034 break; 10035 10036 case InlineAsm::isInput: 10037 case InlineAsm::isLabel: { 10038 SDValue InOperandVal = OpInfo.CallOperand; 10039 10040 if (OpInfo.isMatchingInputConstraint()) { 10041 // If this is required to match an output register we have already set, 10042 // just use its register. 10043 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 10044 AsmNodeOperands); 10045 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 10046 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 10047 if (OpInfo.isIndirect) { 10048 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 10049 emitInlineAsmError(Call, "inline asm not supported yet: " 10050 "don't know how to handle tied " 10051 "indirect register inputs"); 10052 return; 10053 } 10054 10055 SmallVector<unsigned, 4> Regs; 10056 MachineFunction &MF = DAG.getMachineFunction(); 10057 MachineRegisterInfo &MRI = MF.getRegInfo(); 10058 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 10059 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 10060 Register TiedReg = R->getReg(); 10061 MVT RegVT = R->getSimpleValueType(0); 10062 const TargetRegisterClass *RC = 10063 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 10064 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 10065 : TRI.getMinimalPhysRegClass(TiedReg); 10066 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 10067 Regs.push_back(MRI.createVirtualRegister(RC)); 10068 10069 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 10070 10071 SDLoc dl = getCurSDLoc(); 10072 // Use the produced MatchedRegs object to 10073 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 10074 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 10075 OpInfo.getMatchedOperand(), dl, DAG, 10076 AsmNodeOperands); 10077 break; 10078 } 10079 10080 assert(Flag.isMemKind() && "Unknown matching constraint!"); 10081 assert(Flag.getNumOperandRegisters() == 1 && 10082 "Unexpected number of operands"); 10083 // Add information to the INLINEASM node to know about this input. 10084 // See InlineAsm.h isUseOperandTiedToDef. 10085 Flag.clearMemConstraint(); 10086 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 10087 AsmNodeOperands.push_back(DAG.getTargetConstant( 10088 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10089 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 10090 break; 10091 } 10092 10093 // Treat indirect 'X' constraint as memory. 10094 if (OpInfo.ConstraintType == TargetLowering::C_Other && 10095 OpInfo.isIndirect) 10096 OpInfo.ConstraintType = TargetLowering::C_Memory; 10097 10098 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 10099 OpInfo.ConstraintType == TargetLowering::C_Other) { 10100 std::vector<SDValue> Ops; 10101 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 10102 Ops, DAG); 10103 if (Ops.empty()) { 10104 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 10105 if (isa<ConstantSDNode>(InOperandVal)) { 10106 emitInlineAsmError(Call, "value out of range for constraint '" + 10107 Twine(OpInfo.ConstraintCode) + "'"); 10108 return; 10109 } 10110 10111 emitInlineAsmError(Call, 10112 "invalid operand for inline asm constraint '" + 10113 Twine(OpInfo.ConstraintCode) + "'"); 10114 return; 10115 } 10116 10117 // Add information to the INLINEASM node to know about this input. 10118 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 10119 AsmNodeOperands.push_back(DAG.getTargetConstant( 10120 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10121 llvm::append_range(AsmNodeOperands, Ops); 10122 break; 10123 } 10124 10125 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 10126 assert((OpInfo.isIndirect || 10127 OpInfo.ConstraintType != TargetLowering::C_Memory) && 10128 "Operand must be indirect to be a mem!"); 10129 assert(InOperandVal.getValueType() == 10130 TLI.getPointerTy(DAG.getDataLayout()) && 10131 "Memory operands expect pointer values"); 10132 10133 const InlineAsm::ConstraintCode ConstraintID = 10134 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10135 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10136 "Failed to convert memory constraint code to constraint id."); 10137 10138 // Add information to the INLINEASM node to know about this input. 10139 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 10140 ResOpType.setMemConstraint(ConstraintID); 10141 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 10142 getCurSDLoc(), 10143 MVT::i32)); 10144 AsmNodeOperands.push_back(InOperandVal); 10145 break; 10146 } 10147 10148 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 10149 const InlineAsm::ConstraintCode ConstraintID = 10150 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10151 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10152 "Failed to convert memory constraint code to constraint id."); 10153 10154 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 10155 10156 SDValue AsmOp = InOperandVal; 10157 if (isFunction(InOperandVal)) { 10158 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 10159 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 10160 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 10161 InOperandVal.getValueType(), 10162 GA->getOffset()); 10163 } 10164 10165 // Add information to the INLINEASM node to know about this input. 10166 ResOpType.setMemConstraint(ConstraintID); 10167 10168 AsmNodeOperands.push_back( 10169 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 10170 10171 AsmNodeOperands.push_back(AsmOp); 10172 break; 10173 } 10174 10175 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 10176 OpInfo.ConstraintType != TargetLowering::C_Register) { 10177 emitInlineAsmError(Call, "unknown asm constraint '" + 10178 Twine(OpInfo.ConstraintCode) + "'"); 10179 return; 10180 } 10181 10182 // TODO: Support this. 10183 if (OpInfo.isIndirect) { 10184 emitInlineAsmError( 10185 Call, "Don't know how to handle indirect register inputs yet " 10186 "for constraint '" + 10187 Twine(OpInfo.ConstraintCode) + "'"); 10188 return; 10189 } 10190 10191 // Copy the input into the appropriate registers. 10192 if (OpInfo.AssignedRegs.Regs.empty()) { 10193 emitInlineAsmError(Call, 10194 "couldn't allocate input reg for constraint '" + 10195 Twine(OpInfo.ConstraintCode) + "'"); 10196 return; 10197 } 10198 10199 if (DetectWriteToReservedRegister()) 10200 return; 10201 10202 SDLoc dl = getCurSDLoc(); 10203 10204 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 10205 &Call); 10206 10207 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 10208 0, dl, DAG, AsmNodeOperands); 10209 break; 10210 } 10211 case InlineAsm::isClobber: 10212 // Add the clobbered value to the operand list, so that the register 10213 // allocator is aware that the physreg got clobbered. 10214 if (!OpInfo.AssignedRegs.Regs.empty()) 10215 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 10216 false, 0, getCurSDLoc(), DAG, 10217 AsmNodeOperands); 10218 break; 10219 } 10220 } 10221 10222 // Finish up input operands. Set the input chain and add the flag last. 10223 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 10224 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 10225 10226 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 10227 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 10228 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 10229 Glue = Chain.getValue(1); 10230 10231 // Do additional work to generate outputs. 10232 10233 SmallVector<EVT, 1> ResultVTs; 10234 SmallVector<SDValue, 1> ResultValues; 10235 SmallVector<SDValue, 8> OutChains; 10236 10237 llvm::Type *CallResultType = Call.getType(); 10238 ArrayRef<Type *> ResultTypes; 10239 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 10240 ResultTypes = StructResult->elements(); 10241 else if (!CallResultType->isVoidTy()) 10242 ResultTypes = ArrayRef(CallResultType); 10243 10244 auto CurResultType = ResultTypes.begin(); 10245 auto handleRegAssign = [&](SDValue V) { 10246 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 10247 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 10248 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 10249 ++CurResultType; 10250 // If the type of the inline asm call site return value is different but has 10251 // same size as the type of the asm output bitcast it. One example of this 10252 // is for vectors with different width / number of elements. This can 10253 // happen for register classes that can contain multiple different value 10254 // types. The preg or vreg allocated may not have the same VT as was 10255 // expected. 10256 // 10257 // This can also happen for a return value that disagrees with the register 10258 // class it is put in, eg. a double in a general-purpose register on a 10259 // 32-bit machine. 10260 if (ResultVT != V.getValueType() && 10261 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 10262 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 10263 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 10264 V.getValueType().isInteger()) { 10265 // If a result value was tied to an input value, the computed result 10266 // may have a wider width than the expected result. Extract the 10267 // relevant portion. 10268 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 10269 } 10270 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 10271 ResultVTs.push_back(ResultVT); 10272 ResultValues.push_back(V); 10273 }; 10274 10275 // Deal with output operands. 10276 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10277 if (OpInfo.Type == InlineAsm::isOutput) { 10278 SDValue Val; 10279 // Skip trivial output operands. 10280 if (OpInfo.AssignedRegs.Regs.empty()) 10281 continue; 10282 10283 switch (OpInfo.ConstraintType) { 10284 case TargetLowering::C_Register: 10285 case TargetLowering::C_RegisterClass: 10286 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 10287 Chain, &Glue, &Call); 10288 break; 10289 case TargetLowering::C_Immediate: 10290 case TargetLowering::C_Other: 10291 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 10292 OpInfo, DAG); 10293 break; 10294 case TargetLowering::C_Memory: 10295 break; // Already handled. 10296 case TargetLowering::C_Address: 10297 break; // Silence warning. 10298 case TargetLowering::C_Unknown: 10299 assert(false && "Unexpected unknown constraint"); 10300 } 10301 10302 // Indirect output manifest as stores. Record output chains. 10303 if (OpInfo.isIndirect) { 10304 const Value *Ptr = OpInfo.CallOperandVal; 10305 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 10306 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 10307 MachinePointerInfo(Ptr)); 10308 OutChains.push_back(Store); 10309 } else { 10310 // generate CopyFromRegs to associated registers. 10311 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 10312 if (Val.getOpcode() == ISD::MERGE_VALUES) { 10313 for (const SDValue &V : Val->op_values()) 10314 handleRegAssign(V); 10315 } else 10316 handleRegAssign(Val); 10317 } 10318 } 10319 } 10320 10321 // Set results. 10322 if (!ResultValues.empty()) { 10323 assert(CurResultType == ResultTypes.end() && 10324 "Mismatch in number of ResultTypes"); 10325 assert(ResultValues.size() == ResultTypes.size() && 10326 "Mismatch in number of output operands in asm result"); 10327 10328 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10329 DAG.getVTList(ResultVTs), ResultValues); 10330 setValue(&Call, V); 10331 } 10332 10333 // Collect store chains. 10334 if (!OutChains.empty()) 10335 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 10336 10337 if (EmitEHLabels) { 10338 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 10339 } 10340 10341 // Only Update Root if inline assembly has a memory effect. 10342 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 10343 EmitEHLabels) 10344 DAG.setRoot(Chain); 10345 } 10346 10347 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 10348 const Twine &Message) { 10349 LLVMContext &Ctx = *DAG.getContext(); 10350 Ctx.emitError(&Call, Message); 10351 10352 // Make sure we leave the DAG in a valid state 10353 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10354 SmallVector<EVT, 1> ValueVTs; 10355 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 10356 10357 if (ValueVTs.empty()) 10358 return; 10359 10360 SmallVector<SDValue, 1> Ops; 10361 for (const EVT &VT : ValueVTs) 10362 Ops.push_back(DAG.getUNDEF(VT)); 10363 10364 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 10365 } 10366 10367 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 10368 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 10369 MVT::Other, getRoot(), 10370 getValue(I.getArgOperand(0)), 10371 DAG.getSrcValue(I.getArgOperand(0)))); 10372 } 10373 10374 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 10375 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10376 const DataLayout &DL = DAG.getDataLayout(); 10377 SDValue V = DAG.getVAArg( 10378 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 10379 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 10380 DL.getABITypeAlign(I.getType()).value()); 10381 DAG.setRoot(V.getValue(1)); 10382 10383 if (I.getType()->isPointerTy()) 10384 V = DAG.getPtrExtOrTrunc( 10385 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 10386 setValue(&I, V); 10387 } 10388 10389 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 10390 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 10391 MVT::Other, getRoot(), 10392 getValue(I.getArgOperand(0)), 10393 DAG.getSrcValue(I.getArgOperand(0)))); 10394 } 10395 10396 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 10397 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 10398 MVT::Other, getRoot(), 10399 getValue(I.getArgOperand(0)), 10400 getValue(I.getArgOperand(1)), 10401 DAG.getSrcValue(I.getArgOperand(0)), 10402 DAG.getSrcValue(I.getArgOperand(1)))); 10403 } 10404 10405 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 10406 const Instruction &I, 10407 SDValue Op) { 10408 std::optional<ConstantRange> CR = getRange(I); 10409 10410 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped()) 10411 return Op; 10412 10413 APInt Lo = CR->getUnsignedMin(); 10414 if (!Lo.isMinValue()) 10415 return Op; 10416 10417 APInt Hi = CR->getUnsignedMax(); 10418 unsigned Bits = std::max(Hi.getActiveBits(), 10419 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 10420 10421 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 10422 10423 SDLoc SL = getCurSDLoc(); 10424 10425 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 10426 DAG.getValueType(SmallVT)); 10427 unsigned NumVals = Op.getNode()->getNumValues(); 10428 if (NumVals == 1) 10429 return ZExt; 10430 10431 SmallVector<SDValue, 4> Ops; 10432 10433 Ops.push_back(ZExt); 10434 for (unsigned I = 1; I != NumVals; ++I) 10435 Ops.push_back(Op.getValue(I)); 10436 10437 return DAG.getMergeValues(Ops, SL); 10438 } 10439 10440 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 10441 /// the call being lowered. 10442 /// 10443 /// This is a helper for lowering intrinsics that follow a target calling 10444 /// convention or require stack pointer adjustment. Only a subset of the 10445 /// intrinsic's operands need to participate in the calling convention. 10446 void SelectionDAGBuilder::populateCallLoweringInfo( 10447 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 10448 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 10449 AttributeSet RetAttrs, bool IsPatchPoint) { 10450 TargetLowering::ArgListTy Args; 10451 Args.reserve(NumArgs); 10452 10453 // Populate the argument list. 10454 // Attributes for args start at offset 1, after the return attribute. 10455 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 10456 ArgI != ArgE; ++ArgI) { 10457 const Value *V = Call->getOperand(ArgI); 10458 10459 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 10460 10461 TargetLowering::ArgListEntry Entry; 10462 Entry.Node = getValue(V); 10463 Entry.Ty = V->getType(); 10464 Entry.setAttributes(Call, ArgI); 10465 Args.push_back(Entry); 10466 } 10467 10468 CLI.setDebugLoc(getCurSDLoc()) 10469 .setChain(getRoot()) 10470 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 10471 RetAttrs) 10472 .setDiscardResult(Call->use_empty()) 10473 .setIsPatchPoint(IsPatchPoint) 10474 .setIsPreallocated( 10475 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 10476 } 10477 10478 /// Add a stack map intrinsic call's live variable operands to a stackmap 10479 /// or patchpoint target node's operand list. 10480 /// 10481 /// Constants are converted to TargetConstants purely as an optimization to 10482 /// avoid constant materialization and register allocation. 10483 /// 10484 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 10485 /// generate addess computation nodes, and so FinalizeISel can convert the 10486 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10487 /// address materialization and register allocation, but may also be required 10488 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10489 /// alloca in the entry block, then the runtime may assume that the alloca's 10490 /// StackMap location can be read immediately after compilation and that the 10491 /// location is valid at any point during execution (this is similar to the 10492 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10493 /// only available in a register, then the runtime would need to trap when 10494 /// execution reaches the StackMap in order to read the alloca's location. 10495 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10496 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10497 SelectionDAGBuilder &Builder) { 10498 SelectionDAG &DAG = Builder.DAG; 10499 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10500 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10501 10502 // Things on the stack are pointer-typed, meaning that they are already 10503 // legal and can be emitted directly to target nodes. 10504 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10505 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10506 } else { 10507 // Otherwise emit a target independent node to be legalised. 10508 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10509 } 10510 } 10511 } 10512 10513 /// Lower llvm.experimental.stackmap. 10514 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10515 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10516 // [live variables...]) 10517 10518 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10519 10520 SDValue Chain, InGlue, Callee; 10521 SmallVector<SDValue, 32> Ops; 10522 10523 SDLoc DL = getCurSDLoc(); 10524 Callee = getValue(CI.getCalledOperand()); 10525 10526 // The stackmap intrinsic only records the live variables (the arguments 10527 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10528 // intrinsic, this won't be lowered to a function call. This means we don't 10529 // have to worry about calling conventions and target specific lowering code. 10530 // Instead we perform the call lowering right here. 10531 // 10532 // chain, flag = CALLSEQ_START(chain, 0, 0) 10533 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10534 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10535 // 10536 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10537 InGlue = Chain.getValue(1); 10538 10539 // Add the STACKMAP operands, starting with DAG house-keeping. 10540 Ops.push_back(Chain); 10541 Ops.push_back(InGlue); 10542 10543 // Add the <id>, <numShadowBytes> operands. 10544 // 10545 // These do not require legalisation, and can be emitted directly to target 10546 // constant nodes. 10547 SDValue ID = getValue(CI.getArgOperand(0)); 10548 assert(ID.getValueType() == MVT::i64); 10549 SDValue IDConst = 10550 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10551 Ops.push_back(IDConst); 10552 10553 SDValue Shad = getValue(CI.getArgOperand(1)); 10554 assert(Shad.getValueType() == MVT::i32); 10555 SDValue ShadConst = 10556 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10557 Ops.push_back(ShadConst); 10558 10559 // Add the live variables. 10560 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10561 10562 // Create the STACKMAP node. 10563 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10564 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10565 InGlue = Chain.getValue(1); 10566 10567 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10568 10569 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10570 10571 // Set the root to the target-lowered call chain. 10572 DAG.setRoot(Chain); 10573 10574 // Inform the Frame Information that we have a stackmap in this function. 10575 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10576 } 10577 10578 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10579 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10580 const BasicBlock *EHPadBB) { 10581 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>, 10582 // i32 <numBytes>, 10583 // i8* <target>, 10584 // i32 <numArgs>, 10585 // [Args...], 10586 // [live variables...]) 10587 10588 CallingConv::ID CC = CB.getCallingConv(); 10589 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10590 bool HasDef = !CB.getType()->isVoidTy(); 10591 SDLoc dl = getCurSDLoc(); 10592 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10593 10594 // Handle immediate and symbolic callees. 10595 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10596 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10597 /*isTarget=*/true); 10598 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10599 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10600 SDLoc(SymbolicCallee), 10601 SymbolicCallee->getValueType(0)); 10602 10603 // Get the real number of arguments participating in the call <numArgs> 10604 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10605 unsigned NumArgs = NArgVal->getAsZExtVal(); 10606 10607 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10608 // Intrinsics include all meta-operands up to but not including CC. 10609 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10610 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10611 "Not enough arguments provided to the patchpoint intrinsic"); 10612 10613 // For AnyRegCC the arguments are lowered later on manually. 10614 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10615 Type *ReturnTy = 10616 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10617 10618 TargetLowering::CallLoweringInfo CLI(DAG); 10619 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10620 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10621 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10622 10623 SDNode *CallEnd = Result.second.getNode(); 10624 if (CallEnd->getOpcode() == ISD::EH_LABEL) 10625 CallEnd = CallEnd->getOperand(0).getNode(); 10626 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10627 CallEnd = CallEnd->getOperand(0).getNode(); 10628 10629 /// Get a call instruction from the call sequence chain. 10630 /// Tail calls are not allowed. 10631 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10632 "Expected a callseq node."); 10633 SDNode *Call = CallEnd->getOperand(0).getNode(); 10634 bool HasGlue = Call->getGluedNode(); 10635 10636 // Replace the target specific call node with the patchable intrinsic. 10637 SmallVector<SDValue, 8> Ops; 10638 10639 // Push the chain. 10640 Ops.push_back(*(Call->op_begin())); 10641 10642 // Optionally, push the glue (if any). 10643 if (HasGlue) 10644 Ops.push_back(*(Call->op_end() - 1)); 10645 10646 // Push the register mask info. 10647 if (HasGlue) 10648 Ops.push_back(*(Call->op_end() - 2)); 10649 else 10650 Ops.push_back(*(Call->op_end() - 1)); 10651 10652 // Add the <id> and <numBytes> constants. 10653 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10654 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10655 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10656 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10657 10658 // Add the callee. 10659 Ops.push_back(Callee); 10660 10661 // Adjust <numArgs> to account for any arguments that have been passed on the 10662 // stack instead. 10663 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10664 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10665 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10666 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10667 10668 // Add the calling convention 10669 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10670 10671 // Add the arguments we omitted previously. The register allocator should 10672 // place these in any free register. 10673 if (IsAnyRegCC) 10674 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10675 Ops.push_back(getValue(CB.getArgOperand(i))); 10676 10677 // Push the arguments from the call instruction. 10678 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10679 Ops.append(Call->op_begin() + 2, e); 10680 10681 // Push live variables for the stack map. 10682 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10683 10684 SDVTList NodeTys; 10685 if (IsAnyRegCC && HasDef) { 10686 // Create the return types based on the intrinsic definition 10687 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10688 SmallVector<EVT, 3> ValueVTs; 10689 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10690 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10691 10692 // There is always a chain and a glue type at the end 10693 ValueVTs.push_back(MVT::Other); 10694 ValueVTs.push_back(MVT::Glue); 10695 NodeTys = DAG.getVTList(ValueVTs); 10696 } else 10697 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10698 10699 // Replace the target specific call node with a PATCHPOINT node. 10700 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10701 10702 // Update the NodeMap. 10703 if (HasDef) { 10704 if (IsAnyRegCC) 10705 setValue(&CB, SDValue(PPV.getNode(), 0)); 10706 else 10707 setValue(&CB, Result.first); 10708 } 10709 10710 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10711 // call sequence. Furthermore the location of the chain and glue can change 10712 // when the AnyReg calling convention is used and the intrinsic returns a 10713 // value. 10714 if (IsAnyRegCC && HasDef) { 10715 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10716 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10717 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10718 } else 10719 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10720 DAG.DeleteNode(Call); 10721 10722 // Inform the Frame Information that we have a patchpoint in this function. 10723 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10724 } 10725 10726 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10727 unsigned Intrinsic) { 10728 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10729 SDValue Op1 = getValue(I.getArgOperand(0)); 10730 SDValue Op2; 10731 if (I.arg_size() > 1) 10732 Op2 = getValue(I.getArgOperand(1)); 10733 SDLoc dl = getCurSDLoc(); 10734 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10735 SDValue Res; 10736 SDNodeFlags SDFlags; 10737 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10738 SDFlags.copyFMF(*FPMO); 10739 10740 switch (Intrinsic) { 10741 case Intrinsic::vector_reduce_fadd: 10742 if (SDFlags.hasAllowReassociation()) 10743 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10744 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10745 SDFlags); 10746 else 10747 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10748 break; 10749 case Intrinsic::vector_reduce_fmul: 10750 if (SDFlags.hasAllowReassociation()) 10751 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10752 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10753 SDFlags); 10754 else 10755 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10756 break; 10757 case Intrinsic::vector_reduce_add: 10758 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10759 break; 10760 case Intrinsic::vector_reduce_mul: 10761 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10762 break; 10763 case Intrinsic::vector_reduce_and: 10764 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10765 break; 10766 case Intrinsic::vector_reduce_or: 10767 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10768 break; 10769 case Intrinsic::vector_reduce_xor: 10770 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10771 break; 10772 case Intrinsic::vector_reduce_smax: 10773 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10774 break; 10775 case Intrinsic::vector_reduce_smin: 10776 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10777 break; 10778 case Intrinsic::vector_reduce_umax: 10779 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10780 break; 10781 case Intrinsic::vector_reduce_umin: 10782 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10783 break; 10784 case Intrinsic::vector_reduce_fmax: 10785 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10786 break; 10787 case Intrinsic::vector_reduce_fmin: 10788 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10789 break; 10790 case Intrinsic::vector_reduce_fmaximum: 10791 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10792 break; 10793 case Intrinsic::vector_reduce_fminimum: 10794 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10795 break; 10796 default: 10797 llvm_unreachable("Unhandled vector reduce intrinsic"); 10798 } 10799 setValue(&I, Res); 10800 } 10801 10802 /// Returns an AttributeList representing the attributes applied to the return 10803 /// value of the given call. 10804 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10805 SmallVector<Attribute::AttrKind, 2> Attrs; 10806 if (CLI.RetSExt) 10807 Attrs.push_back(Attribute::SExt); 10808 if (CLI.RetZExt) 10809 Attrs.push_back(Attribute::ZExt); 10810 if (CLI.IsInReg) 10811 Attrs.push_back(Attribute::InReg); 10812 10813 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10814 Attrs); 10815 } 10816 10817 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10818 /// implementation, which just calls LowerCall. 10819 /// FIXME: When all targets are 10820 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10821 std::pair<SDValue, SDValue> 10822 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10823 // Handle the incoming return values from the call. 10824 CLI.Ins.clear(); 10825 Type *OrigRetTy = CLI.RetTy; 10826 SmallVector<EVT, 4> RetTys; 10827 SmallVector<TypeSize, 4> Offsets; 10828 auto &DL = CLI.DAG.getDataLayout(); 10829 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 10830 10831 if (CLI.IsPostTypeLegalization) { 10832 // If we are lowering a libcall after legalization, split the return type. 10833 SmallVector<EVT, 4> OldRetTys; 10834 SmallVector<TypeSize, 4> OldOffsets; 10835 RetTys.swap(OldRetTys); 10836 Offsets.swap(OldOffsets); 10837 10838 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10839 EVT RetVT = OldRetTys[i]; 10840 uint64_t Offset = OldOffsets[i]; 10841 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10842 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10843 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10844 RetTys.append(NumRegs, RegisterVT); 10845 for (unsigned j = 0; j != NumRegs; ++j) 10846 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ)); 10847 } 10848 } 10849 10850 SmallVector<ISD::OutputArg, 4> Outs; 10851 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10852 10853 bool CanLowerReturn = 10854 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10855 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10856 10857 SDValue DemoteStackSlot; 10858 int DemoteStackIdx = -100; 10859 if (!CanLowerReturn) { 10860 // FIXME: equivalent assert? 10861 // assert(!CS.hasInAllocaArgument() && 10862 // "sret demotion is incompatible with inalloca"); 10863 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10864 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10865 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10866 DemoteStackIdx = 10867 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10868 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10869 DL.getAllocaAddrSpace()); 10870 10871 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10872 ArgListEntry Entry; 10873 Entry.Node = DemoteStackSlot; 10874 Entry.Ty = StackSlotPtrType; 10875 Entry.IsSExt = false; 10876 Entry.IsZExt = false; 10877 Entry.IsInReg = false; 10878 Entry.IsSRet = true; 10879 Entry.IsNest = false; 10880 Entry.IsByVal = false; 10881 Entry.IsByRef = false; 10882 Entry.IsReturned = false; 10883 Entry.IsSwiftSelf = false; 10884 Entry.IsSwiftAsync = false; 10885 Entry.IsSwiftError = false; 10886 Entry.IsCFGuardTarget = false; 10887 Entry.Alignment = Alignment; 10888 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10889 CLI.NumFixedArgs += 1; 10890 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10891 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10892 10893 // sret demotion isn't compatible with tail-calls, since the sret argument 10894 // points into the callers stack frame. 10895 CLI.IsTailCall = false; 10896 } else { 10897 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10898 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10899 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10900 ISD::ArgFlagsTy Flags; 10901 if (NeedsRegBlock) { 10902 Flags.setInConsecutiveRegs(); 10903 if (I == RetTys.size() - 1) 10904 Flags.setInConsecutiveRegsLast(); 10905 } 10906 EVT VT = RetTys[I]; 10907 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10908 CLI.CallConv, VT); 10909 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10910 CLI.CallConv, VT); 10911 for (unsigned i = 0; i != NumRegs; ++i) { 10912 ISD::InputArg MyFlags; 10913 MyFlags.Flags = Flags; 10914 MyFlags.VT = RegisterVT; 10915 MyFlags.ArgVT = VT; 10916 MyFlags.Used = CLI.IsReturnValueUsed; 10917 if (CLI.RetTy->isPointerTy()) { 10918 MyFlags.Flags.setPointer(); 10919 MyFlags.Flags.setPointerAddrSpace( 10920 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10921 } 10922 if (CLI.RetSExt) 10923 MyFlags.Flags.setSExt(); 10924 if (CLI.RetZExt) 10925 MyFlags.Flags.setZExt(); 10926 if (CLI.IsInReg) 10927 MyFlags.Flags.setInReg(); 10928 CLI.Ins.push_back(MyFlags); 10929 } 10930 } 10931 } 10932 10933 // We push in swifterror return as the last element of CLI.Ins. 10934 ArgListTy &Args = CLI.getArgs(); 10935 if (supportSwiftError()) { 10936 for (const ArgListEntry &Arg : Args) { 10937 if (Arg.IsSwiftError) { 10938 ISD::InputArg MyFlags; 10939 MyFlags.VT = getPointerTy(DL); 10940 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10941 MyFlags.Flags.setSwiftError(); 10942 CLI.Ins.push_back(MyFlags); 10943 } 10944 } 10945 } 10946 10947 // Handle all of the outgoing arguments. 10948 CLI.Outs.clear(); 10949 CLI.OutVals.clear(); 10950 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10951 SmallVector<EVT, 4> ValueVTs; 10952 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10953 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10954 Type *FinalType = Args[i].Ty; 10955 if (Args[i].IsByVal) 10956 FinalType = Args[i].IndirectType; 10957 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10958 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10959 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10960 ++Value) { 10961 EVT VT = ValueVTs[Value]; 10962 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10963 SDValue Op = SDValue(Args[i].Node.getNode(), 10964 Args[i].Node.getResNo() + Value); 10965 ISD::ArgFlagsTy Flags; 10966 10967 // Certain targets (such as MIPS), may have a different ABI alignment 10968 // for a type depending on the context. Give the target a chance to 10969 // specify the alignment it wants. 10970 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10971 Flags.setOrigAlign(OriginalAlignment); 10972 10973 if (Args[i].Ty->isPointerTy()) { 10974 Flags.setPointer(); 10975 Flags.setPointerAddrSpace( 10976 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10977 } 10978 if (Args[i].IsZExt) 10979 Flags.setZExt(); 10980 if (Args[i].IsSExt) 10981 Flags.setSExt(); 10982 if (Args[i].IsInReg) { 10983 // If we are using vectorcall calling convention, a structure that is 10984 // passed InReg - is surely an HVA 10985 if (CLI.CallConv == CallingConv::X86_VectorCall && 10986 isa<StructType>(FinalType)) { 10987 // The first value of a structure is marked 10988 if (0 == Value) 10989 Flags.setHvaStart(); 10990 Flags.setHva(); 10991 } 10992 // Set InReg Flag 10993 Flags.setInReg(); 10994 } 10995 if (Args[i].IsSRet) 10996 Flags.setSRet(); 10997 if (Args[i].IsSwiftSelf) 10998 Flags.setSwiftSelf(); 10999 if (Args[i].IsSwiftAsync) 11000 Flags.setSwiftAsync(); 11001 if (Args[i].IsSwiftError) 11002 Flags.setSwiftError(); 11003 if (Args[i].IsCFGuardTarget) 11004 Flags.setCFGuardTarget(); 11005 if (Args[i].IsByVal) 11006 Flags.setByVal(); 11007 if (Args[i].IsByRef) 11008 Flags.setByRef(); 11009 if (Args[i].IsPreallocated) { 11010 Flags.setPreallocated(); 11011 // Set the byval flag for CCAssignFn callbacks that don't know about 11012 // preallocated. This way we can know how many bytes we should've 11013 // allocated and how many bytes a callee cleanup function will pop. If 11014 // we port preallocated to more targets, we'll have to add custom 11015 // preallocated handling in the various CC lowering callbacks. 11016 Flags.setByVal(); 11017 } 11018 if (Args[i].IsInAlloca) { 11019 Flags.setInAlloca(); 11020 // Set the byval flag for CCAssignFn callbacks that don't know about 11021 // inalloca. This way we can know how many bytes we should've allocated 11022 // and how many bytes a callee cleanup function will pop. If we port 11023 // inalloca to more targets, we'll have to add custom inalloca handling 11024 // in the various CC lowering callbacks. 11025 Flags.setByVal(); 11026 } 11027 Align MemAlign; 11028 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 11029 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 11030 Flags.setByValSize(FrameSize); 11031 11032 // info is not there but there are cases it cannot get right. 11033 if (auto MA = Args[i].Alignment) 11034 MemAlign = *MA; 11035 else 11036 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 11037 } else if (auto MA = Args[i].Alignment) { 11038 MemAlign = *MA; 11039 } else { 11040 MemAlign = OriginalAlignment; 11041 } 11042 Flags.setMemAlign(MemAlign); 11043 if (Args[i].IsNest) 11044 Flags.setNest(); 11045 if (NeedsRegBlock) 11046 Flags.setInConsecutiveRegs(); 11047 11048 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11049 CLI.CallConv, VT); 11050 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11051 CLI.CallConv, VT); 11052 SmallVector<SDValue, 4> Parts(NumParts); 11053 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 11054 11055 if (Args[i].IsSExt) 11056 ExtendKind = ISD::SIGN_EXTEND; 11057 else if (Args[i].IsZExt) 11058 ExtendKind = ISD::ZERO_EXTEND; 11059 11060 // Conservatively only handle 'returned' on non-vectors that can be lowered, 11061 // for now. 11062 if (Args[i].IsReturned && !Op.getValueType().isVector() && 11063 CanLowerReturn) { 11064 assert((CLI.RetTy == Args[i].Ty || 11065 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 11066 CLI.RetTy->getPointerAddressSpace() == 11067 Args[i].Ty->getPointerAddressSpace())) && 11068 RetTys.size() == NumValues && "unexpected use of 'returned'"); 11069 // Before passing 'returned' to the target lowering code, ensure that 11070 // either the register MVT and the actual EVT are the same size or that 11071 // the return value and argument are extended in the same way; in these 11072 // cases it's safe to pass the argument register value unchanged as the 11073 // return register value (although it's at the target's option whether 11074 // to do so) 11075 // TODO: allow code generation to take advantage of partially preserved 11076 // registers rather than clobbering the entire register when the 11077 // parameter extension method is not compatible with the return 11078 // extension method 11079 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 11080 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 11081 CLI.RetZExt == Args[i].IsZExt)) 11082 Flags.setReturned(); 11083 } 11084 11085 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 11086 CLI.CallConv, ExtendKind); 11087 11088 for (unsigned j = 0; j != NumParts; ++j) { 11089 // if it isn't first piece, alignment must be 1 11090 // For scalable vectors the scalable part is currently handled 11091 // by individual targets, so we just use the known minimum size here. 11092 ISD::OutputArg MyFlags( 11093 Flags, Parts[j].getValueType().getSimpleVT(), VT, 11094 i < CLI.NumFixedArgs, i, 11095 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 11096 if (NumParts > 1 && j == 0) 11097 MyFlags.Flags.setSplit(); 11098 else if (j != 0) { 11099 MyFlags.Flags.setOrigAlign(Align(1)); 11100 if (j == NumParts - 1) 11101 MyFlags.Flags.setSplitEnd(); 11102 } 11103 11104 CLI.Outs.push_back(MyFlags); 11105 CLI.OutVals.push_back(Parts[j]); 11106 } 11107 11108 if (NeedsRegBlock && Value == NumValues - 1) 11109 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 11110 } 11111 } 11112 11113 SmallVector<SDValue, 4> InVals; 11114 CLI.Chain = LowerCall(CLI, InVals); 11115 11116 // Update CLI.InVals to use outside of this function. 11117 CLI.InVals = InVals; 11118 11119 // Verify that the target's LowerCall behaved as expected. 11120 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 11121 "LowerCall didn't return a valid chain!"); 11122 assert((!CLI.IsTailCall || InVals.empty()) && 11123 "LowerCall emitted a return value for a tail call!"); 11124 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 11125 "LowerCall didn't emit the correct number of values!"); 11126 11127 // For a tail call, the return value is merely live-out and there aren't 11128 // any nodes in the DAG representing it. Return a special value to 11129 // indicate that a tail call has been emitted and no more Instructions 11130 // should be processed in the current block. 11131 if (CLI.IsTailCall) { 11132 CLI.DAG.setRoot(CLI.Chain); 11133 return std::make_pair(SDValue(), SDValue()); 11134 } 11135 11136 #ifndef NDEBUG 11137 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 11138 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 11139 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 11140 "LowerCall emitted a value with the wrong type!"); 11141 } 11142 #endif 11143 11144 SmallVector<SDValue, 4> ReturnValues; 11145 if (!CanLowerReturn) { 11146 // The instruction result is the result of loading from the 11147 // hidden sret parameter. 11148 SmallVector<EVT, 1> PVTs; 11149 Type *PtrRetTy = 11150 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 11151 11152 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 11153 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 11154 EVT PtrVT = PVTs[0]; 11155 11156 unsigned NumValues = RetTys.size(); 11157 ReturnValues.resize(NumValues); 11158 SmallVector<SDValue, 4> Chains(NumValues); 11159 11160 // An aggregate return value cannot wrap around the address space, so 11161 // offsets to its parts don't wrap either. 11162 SDNodeFlags Flags; 11163 Flags.setNoUnsignedWrap(true); 11164 11165 MachineFunction &MF = CLI.DAG.getMachineFunction(); 11166 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 11167 for (unsigned i = 0; i < NumValues; ++i) { 11168 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 11169 CLI.DAG.getConstant(Offsets[i], CLI.DL, 11170 PtrVT), Flags); 11171 SDValue L = CLI.DAG.getLoad( 11172 RetTys[i], CLI.DL, CLI.Chain, Add, 11173 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 11174 DemoteStackIdx, Offsets[i]), 11175 HiddenSRetAlign); 11176 ReturnValues[i] = L; 11177 Chains[i] = L.getValue(1); 11178 } 11179 11180 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 11181 } else { 11182 // Collect the legal value parts into potentially illegal values 11183 // that correspond to the original function's return values. 11184 std::optional<ISD::NodeType> AssertOp; 11185 if (CLI.RetSExt) 11186 AssertOp = ISD::AssertSext; 11187 else if (CLI.RetZExt) 11188 AssertOp = ISD::AssertZext; 11189 unsigned CurReg = 0; 11190 for (EVT VT : RetTys) { 11191 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11192 CLI.CallConv, VT); 11193 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11194 CLI.CallConv, VT); 11195 11196 ReturnValues.push_back(getCopyFromParts( 11197 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 11198 CLI.Chain, CLI.CallConv, AssertOp)); 11199 CurReg += NumRegs; 11200 } 11201 11202 // For a function returning void, there is no return value. We can't create 11203 // such a node, so we just return a null return value in that case. In 11204 // that case, nothing will actually look at the value. 11205 if (ReturnValues.empty()) 11206 return std::make_pair(SDValue(), CLI.Chain); 11207 } 11208 11209 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 11210 CLI.DAG.getVTList(RetTys), ReturnValues); 11211 return std::make_pair(Res, CLI.Chain); 11212 } 11213 11214 /// Places new result values for the node in Results (their number 11215 /// and types must exactly match those of the original return values of 11216 /// the node), or leaves Results empty, which indicates that the node is not 11217 /// to be custom lowered after all. 11218 void TargetLowering::LowerOperationWrapper(SDNode *N, 11219 SmallVectorImpl<SDValue> &Results, 11220 SelectionDAG &DAG) const { 11221 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 11222 11223 if (!Res.getNode()) 11224 return; 11225 11226 // If the original node has one result, take the return value from 11227 // LowerOperation as is. It might not be result number 0. 11228 if (N->getNumValues() == 1) { 11229 Results.push_back(Res); 11230 return; 11231 } 11232 11233 // If the original node has multiple results, then the return node should 11234 // have the same number of results. 11235 assert((N->getNumValues() == Res->getNumValues()) && 11236 "Lowering returned the wrong number of results!"); 11237 11238 // Places new result values base on N result number. 11239 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 11240 Results.push_back(Res.getValue(I)); 11241 } 11242 11243 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11244 llvm_unreachable("LowerOperation not implemented for this target!"); 11245 } 11246 11247 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 11248 unsigned Reg, 11249 ISD::NodeType ExtendType) { 11250 SDValue Op = getNonRegisterValue(V); 11251 assert((Op.getOpcode() != ISD::CopyFromReg || 11252 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 11253 "Copy from a reg to the same reg!"); 11254 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 11255 11256 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11257 // If this is an InlineAsm we have to match the registers required, not the 11258 // notional registers required by the type. 11259 11260 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 11261 std::nullopt); // This is not an ABI copy. 11262 SDValue Chain = DAG.getEntryNode(); 11263 11264 if (ExtendType == ISD::ANY_EXTEND) { 11265 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 11266 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 11267 ExtendType = PreferredExtendIt->second; 11268 } 11269 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 11270 PendingExports.push_back(Chain); 11271 } 11272 11273 #include "llvm/CodeGen/SelectionDAGISel.h" 11274 11275 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 11276 /// entry block, return true. This includes arguments used by switches, since 11277 /// the switch may expand into multiple basic blocks. 11278 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 11279 // With FastISel active, we may be splitting blocks, so force creation 11280 // of virtual registers for all non-dead arguments. 11281 if (FastISel) 11282 return A->use_empty(); 11283 11284 const BasicBlock &Entry = A->getParent()->front(); 11285 for (const User *U : A->users()) 11286 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 11287 return false; // Use not in entry block. 11288 11289 return true; 11290 } 11291 11292 using ArgCopyElisionMapTy = 11293 DenseMap<const Argument *, 11294 std::pair<const AllocaInst *, const StoreInst *>>; 11295 11296 /// Scan the entry block of the function in FuncInfo for arguments that look 11297 /// like copies into a local alloca. Record any copied arguments in 11298 /// ArgCopyElisionCandidates. 11299 static void 11300 findArgumentCopyElisionCandidates(const DataLayout &DL, 11301 FunctionLoweringInfo *FuncInfo, 11302 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 11303 // Record the state of every static alloca used in the entry block. Argument 11304 // allocas are all used in the entry block, so we need approximately as many 11305 // entries as we have arguments. 11306 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 11307 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 11308 unsigned NumArgs = FuncInfo->Fn->arg_size(); 11309 StaticAllocas.reserve(NumArgs * 2); 11310 11311 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 11312 if (!V) 11313 return nullptr; 11314 V = V->stripPointerCasts(); 11315 const auto *AI = dyn_cast<AllocaInst>(V); 11316 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 11317 return nullptr; 11318 auto Iter = StaticAllocas.insert({AI, Unknown}); 11319 return &Iter.first->second; 11320 }; 11321 11322 // Look for stores of arguments to static allocas. Look through bitcasts and 11323 // GEPs to handle type coercions, as long as the alloca is fully initialized 11324 // by the store. Any non-store use of an alloca escapes it and any subsequent 11325 // unanalyzed store might write it. 11326 // FIXME: Handle structs initialized with multiple stores. 11327 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 11328 // Look for stores, and handle non-store uses conservatively. 11329 const auto *SI = dyn_cast<StoreInst>(&I); 11330 if (!SI) { 11331 // We will look through cast uses, so ignore them completely. 11332 if (I.isCast()) 11333 continue; 11334 // Ignore debug info and pseudo op intrinsics, they don't escape or store 11335 // to allocas. 11336 if (I.isDebugOrPseudoInst()) 11337 continue; 11338 // This is an unknown instruction. Assume it escapes or writes to all 11339 // static alloca operands. 11340 for (const Use &U : I.operands()) { 11341 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 11342 *Info = StaticAllocaInfo::Clobbered; 11343 } 11344 continue; 11345 } 11346 11347 // If the stored value is a static alloca, mark it as escaped. 11348 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 11349 *Info = StaticAllocaInfo::Clobbered; 11350 11351 // Check if the destination is a static alloca. 11352 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 11353 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 11354 if (!Info) 11355 continue; 11356 const AllocaInst *AI = cast<AllocaInst>(Dst); 11357 11358 // Skip allocas that have been initialized or clobbered. 11359 if (*Info != StaticAllocaInfo::Unknown) 11360 continue; 11361 11362 // Check if the stored value is an argument, and that this store fully 11363 // initializes the alloca. 11364 // If the argument type has padding bits we can't directly forward a pointer 11365 // as the upper bits may contain garbage. 11366 // Don't elide copies from the same argument twice. 11367 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 11368 const auto *Arg = dyn_cast<Argument>(Val); 11369 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 11370 Arg->getType()->isEmptyTy() || 11371 DL.getTypeStoreSize(Arg->getType()) != 11372 DL.getTypeAllocSize(AI->getAllocatedType()) || 11373 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 11374 ArgCopyElisionCandidates.count(Arg)) { 11375 *Info = StaticAllocaInfo::Clobbered; 11376 continue; 11377 } 11378 11379 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 11380 << '\n'); 11381 11382 // Mark this alloca and store for argument copy elision. 11383 *Info = StaticAllocaInfo::Elidable; 11384 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 11385 11386 // Stop scanning if we've seen all arguments. This will happen early in -O0 11387 // builds, which is useful, because -O0 builds have large entry blocks and 11388 // many allocas. 11389 if (ArgCopyElisionCandidates.size() == NumArgs) 11390 break; 11391 } 11392 } 11393 11394 /// Try to elide argument copies from memory into a local alloca. Succeeds if 11395 /// ArgVal is a load from a suitable fixed stack object. 11396 static void tryToElideArgumentCopy( 11397 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 11398 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 11399 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 11400 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 11401 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 11402 // Check if this is a load from a fixed stack object. 11403 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 11404 if (!LNode) 11405 return; 11406 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 11407 if (!FINode) 11408 return; 11409 11410 // Check that the fixed stack object is the right size and alignment. 11411 // Look at the alignment that the user wrote on the alloca instead of looking 11412 // at the stack object. 11413 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 11414 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 11415 const AllocaInst *AI = ArgCopyIter->second.first; 11416 int FixedIndex = FINode->getIndex(); 11417 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 11418 int OldIndex = AllocaIndex; 11419 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 11420 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 11421 LLVM_DEBUG( 11422 dbgs() << " argument copy elision failed due to bad fixed stack " 11423 "object size\n"); 11424 return; 11425 } 11426 Align RequiredAlignment = AI->getAlign(); 11427 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 11428 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 11429 "greater than stack argument alignment (" 11430 << DebugStr(RequiredAlignment) << " vs " 11431 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 11432 return; 11433 } 11434 11435 // Perform the elision. Delete the old stack object and replace its only use 11436 // in the variable info map. Mark the stack object as mutable and aliased. 11437 LLVM_DEBUG({ 11438 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 11439 << " Replacing frame index " << OldIndex << " with " << FixedIndex 11440 << '\n'; 11441 }); 11442 MFI.RemoveStackObject(OldIndex); 11443 MFI.setIsImmutableObjectIndex(FixedIndex, false); 11444 MFI.setIsAliasedObjectIndex(FixedIndex, true); 11445 AllocaIndex = FixedIndex; 11446 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 11447 for (SDValue ArgVal : ArgVals) 11448 Chains.push_back(ArgVal.getValue(1)); 11449 11450 // Avoid emitting code for the store implementing the copy. 11451 const StoreInst *SI = ArgCopyIter->second.second; 11452 ElidedArgCopyInstrs.insert(SI); 11453 11454 // Check for uses of the argument again so that we can avoid exporting ArgVal 11455 // if it is't used by anything other than the store. 11456 for (const Value *U : Arg.users()) { 11457 if (U != SI) { 11458 ArgHasUses = true; 11459 break; 11460 } 11461 } 11462 } 11463 11464 void SelectionDAGISel::LowerArguments(const Function &F) { 11465 SelectionDAG &DAG = SDB->DAG; 11466 SDLoc dl = SDB->getCurSDLoc(); 11467 const DataLayout &DL = DAG.getDataLayout(); 11468 SmallVector<ISD::InputArg, 16> Ins; 11469 11470 // In Naked functions we aren't going to save any registers. 11471 if (F.hasFnAttribute(Attribute::Naked)) 11472 return; 11473 11474 if (!FuncInfo->CanLowerReturn) { 11475 // Put in an sret pointer parameter before all the other parameters. 11476 SmallVector<EVT, 1> ValueVTs; 11477 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11478 PointerType::get(F.getContext(), 11479 DAG.getDataLayout().getAllocaAddrSpace()), 11480 ValueVTs); 11481 11482 // NOTE: Assuming that a pointer will never break down to more than one VT 11483 // or one register. 11484 ISD::ArgFlagsTy Flags; 11485 Flags.setSRet(); 11486 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 11487 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 11488 ISD::InputArg::NoArgIndex, 0); 11489 Ins.push_back(RetArg); 11490 } 11491 11492 // Look for stores of arguments to static allocas. Mark such arguments with a 11493 // flag to ask the target to give us the memory location of that argument if 11494 // available. 11495 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11496 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11497 ArgCopyElisionCandidates); 11498 11499 // Set up the incoming argument description vector. 11500 for (const Argument &Arg : F.args()) { 11501 unsigned ArgNo = Arg.getArgNo(); 11502 SmallVector<EVT, 4> ValueVTs; 11503 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11504 bool isArgValueUsed = !Arg.use_empty(); 11505 unsigned PartBase = 0; 11506 Type *FinalType = Arg.getType(); 11507 if (Arg.hasAttribute(Attribute::ByVal)) 11508 FinalType = Arg.getParamByValType(); 11509 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11510 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11511 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11512 Value != NumValues; ++Value) { 11513 EVT VT = ValueVTs[Value]; 11514 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11515 ISD::ArgFlagsTy Flags; 11516 11517 11518 if (Arg.getType()->isPointerTy()) { 11519 Flags.setPointer(); 11520 Flags.setPointerAddrSpace( 11521 cast<PointerType>(Arg.getType())->getAddressSpace()); 11522 } 11523 if (Arg.hasAttribute(Attribute::ZExt)) 11524 Flags.setZExt(); 11525 if (Arg.hasAttribute(Attribute::SExt)) 11526 Flags.setSExt(); 11527 if (Arg.hasAttribute(Attribute::InReg)) { 11528 // If we are using vectorcall calling convention, a structure that is 11529 // passed InReg - is surely an HVA 11530 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11531 isa<StructType>(Arg.getType())) { 11532 // The first value of a structure is marked 11533 if (0 == Value) 11534 Flags.setHvaStart(); 11535 Flags.setHva(); 11536 } 11537 // Set InReg Flag 11538 Flags.setInReg(); 11539 } 11540 if (Arg.hasAttribute(Attribute::StructRet)) 11541 Flags.setSRet(); 11542 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11543 Flags.setSwiftSelf(); 11544 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11545 Flags.setSwiftAsync(); 11546 if (Arg.hasAttribute(Attribute::SwiftError)) 11547 Flags.setSwiftError(); 11548 if (Arg.hasAttribute(Attribute::ByVal)) 11549 Flags.setByVal(); 11550 if (Arg.hasAttribute(Attribute::ByRef)) 11551 Flags.setByRef(); 11552 if (Arg.hasAttribute(Attribute::InAlloca)) { 11553 Flags.setInAlloca(); 11554 // Set the byval flag for CCAssignFn callbacks that don't know about 11555 // inalloca. This way we can know how many bytes we should've allocated 11556 // and how many bytes a callee cleanup function will pop. If we port 11557 // inalloca to more targets, we'll have to add custom inalloca handling 11558 // in the various CC lowering callbacks. 11559 Flags.setByVal(); 11560 } 11561 if (Arg.hasAttribute(Attribute::Preallocated)) { 11562 Flags.setPreallocated(); 11563 // Set the byval flag for CCAssignFn callbacks that don't know about 11564 // preallocated. This way we can know how many bytes we should've 11565 // allocated and how many bytes a callee cleanup function will pop. If 11566 // we port preallocated to more targets, we'll have to add custom 11567 // preallocated handling in the various CC lowering callbacks. 11568 Flags.setByVal(); 11569 } 11570 11571 // Certain targets (such as MIPS), may have a different ABI alignment 11572 // for a type depending on the context. Give the target a chance to 11573 // specify the alignment it wants. 11574 const Align OriginalAlignment( 11575 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11576 Flags.setOrigAlign(OriginalAlignment); 11577 11578 Align MemAlign; 11579 Type *ArgMemTy = nullptr; 11580 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11581 Flags.isByRef()) { 11582 if (!ArgMemTy) 11583 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11584 11585 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11586 11587 // For in-memory arguments, size and alignment should be passed from FE. 11588 // BE will guess if this info is not there but there are cases it cannot 11589 // get right. 11590 if (auto ParamAlign = Arg.getParamStackAlign()) 11591 MemAlign = *ParamAlign; 11592 else if ((ParamAlign = Arg.getParamAlign())) 11593 MemAlign = *ParamAlign; 11594 else 11595 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11596 if (Flags.isByRef()) 11597 Flags.setByRefSize(MemSize); 11598 else 11599 Flags.setByValSize(MemSize); 11600 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11601 MemAlign = *ParamAlign; 11602 } else { 11603 MemAlign = OriginalAlignment; 11604 } 11605 Flags.setMemAlign(MemAlign); 11606 11607 if (Arg.hasAttribute(Attribute::Nest)) 11608 Flags.setNest(); 11609 if (NeedsRegBlock) 11610 Flags.setInConsecutiveRegs(); 11611 if (ArgCopyElisionCandidates.count(&Arg)) 11612 Flags.setCopyElisionCandidate(); 11613 if (Arg.hasAttribute(Attribute::Returned)) 11614 Flags.setReturned(); 11615 11616 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11617 *CurDAG->getContext(), F.getCallingConv(), VT); 11618 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11619 *CurDAG->getContext(), F.getCallingConv(), VT); 11620 for (unsigned i = 0; i != NumRegs; ++i) { 11621 // For scalable vectors, use the minimum size; individual targets 11622 // are responsible for handling scalable vector arguments and 11623 // return values. 11624 ISD::InputArg MyFlags( 11625 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11626 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11627 if (NumRegs > 1 && i == 0) 11628 MyFlags.Flags.setSplit(); 11629 // if it isn't first piece, alignment must be 1 11630 else if (i > 0) { 11631 MyFlags.Flags.setOrigAlign(Align(1)); 11632 if (i == NumRegs - 1) 11633 MyFlags.Flags.setSplitEnd(); 11634 } 11635 Ins.push_back(MyFlags); 11636 } 11637 if (NeedsRegBlock && Value == NumValues - 1) 11638 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11639 PartBase += VT.getStoreSize().getKnownMinValue(); 11640 } 11641 } 11642 11643 // Call the target to set up the argument values. 11644 SmallVector<SDValue, 8> InVals; 11645 SDValue NewRoot = TLI->LowerFormalArguments( 11646 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11647 11648 // Verify that the target's LowerFormalArguments behaved as expected. 11649 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11650 "LowerFormalArguments didn't return a valid chain!"); 11651 assert(InVals.size() == Ins.size() && 11652 "LowerFormalArguments didn't emit the correct number of values!"); 11653 LLVM_DEBUG({ 11654 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11655 assert(InVals[i].getNode() && 11656 "LowerFormalArguments emitted a null value!"); 11657 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11658 "LowerFormalArguments emitted a value with the wrong type!"); 11659 } 11660 }); 11661 11662 // Update the DAG with the new chain value resulting from argument lowering. 11663 DAG.setRoot(NewRoot); 11664 11665 // Set up the argument values. 11666 unsigned i = 0; 11667 if (!FuncInfo->CanLowerReturn) { 11668 // Create a virtual register for the sret pointer, and put in a copy 11669 // from the sret argument into it. 11670 SmallVector<EVT, 1> ValueVTs; 11671 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11672 PointerType::get(F.getContext(), 11673 DAG.getDataLayout().getAllocaAddrSpace()), 11674 ValueVTs); 11675 MVT VT = ValueVTs[0].getSimpleVT(); 11676 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11677 std::optional<ISD::NodeType> AssertOp; 11678 SDValue ArgValue = 11679 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11680 F.getCallingConv(), AssertOp); 11681 11682 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11683 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11684 Register SRetReg = 11685 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11686 FuncInfo->DemoteRegister = SRetReg; 11687 NewRoot = 11688 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11689 DAG.setRoot(NewRoot); 11690 11691 // i indexes lowered arguments. Bump it past the hidden sret argument. 11692 ++i; 11693 } 11694 11695 SmallVector<SDValue, 4> Chains; 11696 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11697 for (const Argument &Arg : F.args()) { 11698 SmallVector<SDValue, 4> ArgValues; 11699 SmallVector<EVT, 4> ValueVTs; 11700 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11701 unsigned NumValues = ValueVTs.size(); 11702 if (NumValues == 0) 11703 continue; 11704 11705 bool ArgHasUses = !Arg.use_empty(); 11706 11707 // Elide the copying store if the target loaded this argument from a 11708 // suitable fixed stack object. 11709 if (Ins[i].Flags.isCopyElisionCandidate()) { 11710 unsigned NumParts = 0; 11711 for (EVT VT : ValueVTs) 11712 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11713 F.getCallingConv(), VT); 11714 11715 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11716 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11717 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11718 } 11719 11720 // If this argument is unused then remember its value. It is used to generate 11721 // debugging information. 11722 bool isSwiftErrorArg = 11723 TLI->supportSwiftError() && 11724 Arg.hasAttribute(Attribute::SwiftError); 11725 if (!ArgHasUses && !isSwiftErrorArg) { 11726 SDB->setUnusedArgValue(&Arg, InVals[i]); 11727 11728 // Also remember any frame index for use in FastISel. 11729 if (FrameIndexSDNode *FI = 11730 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11731 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11732 } 11733 11734 for (unsigned Val = 0; Val != NumValues; ++Val) { 11735 EVT VT = ValueVTs[Val]; 11736 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11737 F.getCallingConv(), VT); 11738 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11739 *CurDAG->getContext(), F.getCallingConv(), VT); 11740 11741 // Even an apparent 'unused' swifterror argument needs to be returned. So 11742 // we do generate a copy for it that can be used on return from the 11743 // function. 11744 if (ArgHasUses || isSwiftErrorArg) { 11745 std::optional<ISD::NodeType> AssertOp; 11746 if (Arg.hasAttribute(Attribute::SExt)) 11747 AssertOp = ISD::AssertSext; 11748 else if (Arg.hasAttribute(Attribute::ZExt)) 11749 AssertOp = ISD::AssertZext; 11750 11751 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11752 PartVT, VT, nullptr, NewRoot, 11753 F.getCallingConv(), AssertOp)); 11754 } 11755 11756 i += NumParts; 11757 } 11758 11759 // We don't need to do anything else for unused arguments. 11760 if (ArgValues.empty()) 11761 continue; 11762 11763 // Note down frame index. 11764 if (FrameIndexSDNode *FI = 11765 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11766 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11767 11768 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11769 SDB->getCurSDLoc()); 11770 11771 SDB->setValue(&Arg, Res); 11772 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11773 // We want to associate the argument with the frame index, among 11774 // involved operands, that correspond to the lowest address. The 11775 // getCopyFromParts function, called earlier, is swapping the order of 11776 // the operands to BUILD_PAIR depending on endianness. The result of 11777 // that swapping is that the least significant bits of the argument will 11778 // be in the first operand of the BUILD_PAIR node, and the most 11779 // significant bits will be in the second operand. 11780 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11781 if (LoadSDNode *LNode = 11782 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11783 if (FrameIndexSDNode *FI = 11784 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11785 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11786 } 11787 11788 // Analyses past this point are naive and don't expect an assertion. 11789 if (Res.getOpcode() == ISD::AssertZext) 11790 Res = Res.getOperand(0); 11791 11792 // Update the SwiftErrorVRegDefMap. 11793 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11794 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11795 if (Register::isVirtualRegister(Reg)) 11796 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11797 Reg); 11798 } 11799 11800 // If this argument is live outside of the entry block, insert a copy from 11801 // wherever we got it to the vreg that other BB's will reference it as. 11802 if (Res.getOpcode() == ISD::CopyFromReg) { 11803 // If we can, though, try to skip creating an unnecessary vreg. 11804 // FIXME: This isn't very clean... it would be nice to make this more 11805 // general. 11806 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11807 if (Register::isVirtualRegister(Reg)) { 11808 FuncInfo->ValueMap[&Arg] = Reg; 11809 continue; 11810 } 11811 } 11812 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11813 FuncInfo->InitializeRegForValue(&Arg); 11814 SDB->CopyToExportRegsIfNeeded(&Arg); 11815 } 11816 } 11817 11818 if (!Chains.empty()) { 11819 Chains.push_back(NewRoot); 11820 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11821 } 11822 11823 DAG.setRoot(NewRoot); 11824 11825 assert(i == InVals.size() && "Argument register count mismatch!"); 11826 11827 // If any argument copy elisions occurred and we have debug info, update the 11828 // stale frame indices used in the dbg.declare variable info table. 11829 if (!ArgCopyElisionFrameIndexMap.empty()) { 11830 for (MachineFunction::VariableDbgInfo &VI : 11831 MF->getInStackSlotVariableDbgInfo()) { 11832 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11833 if (I != ArgCopyElisionFrameIndexMap.end()) 11834 VI.updateStackSlot(I->second); 11835 } 11836 } 11837 11838 // Finally, if the target has anything special to do, allow it to do so. 11839 emitFunctionEntryCode(); 11840 } 11841 11842 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11843 /// ensure constants are generated when needed. Remember the virtual registers 11844 /// that need to be added to the Machine PHI nodes as input. We cannot just 11845 /// directly add them, because expansion might result in multiple MBB's for one 11846 /// BB. As such, the start of the BB might correspond to a different MBB than 11847 /// the end. 11848 void 11849 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11850 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11851 11852 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11853 11854 // Check PHI nodes in successors that expect a value to be available from this 11855 // block. 11856 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11857 if (!isa<PHINode>(SuccBB->begin())) continue; 11858 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB); 11859 11860 // If this terminator has multiple identical successors (common for 11861 // switches), only handle each succ once. 11862 if (!SuccsHandled.insert(SuccMBB).second) 11863 continue; 11864 11865 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11866 11867 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11868 // nodes and Machine PHI nodes, but the incoming operands have not been 11869 // emitted yet. 11870 for (const PHINode &PN : SuccBB->phis()) { 11871 // Ignore dead phi's. 11872 if (PN.use_empty()) 11873 continue; 11874 11875 // Skip empty types 11876 if (PN.getType()->isEmptyTy()) 11877 continue; 11878 11879 unsigned Reg; 11880 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11881 11882 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11883 unsigned &RegOut = ConstantsOut[C]; 11884 if (RegOut == 0) { 11885 RegOut = FuncInfo.CreateRegs(C); 11886 // We need to zero/sign extend ConstantInt phi operands to match 11887 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11888 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11889 if (auto *CI = dyn_cast<ConstantInt>(C)) 11890 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11891 : ISD::ZERO_EXTEND; 11892 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11893 } 11894 Reg = RegOut; 11895 } else { 11896 DenseMap<const Value *, Register>::iterator I = 11897 FuncInfo.ValueMap.find(PHIOp); 11898 if (I != FuncInfo.ValueMap.end()) 11899 Reg = I->second; 11900 else { 11901 assert(isa<AllocaInst>(PHIOp) && 11902 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11903 "Didn't codegen value into a register!??"); 11904 Reg = FuncInfo.CreateRegs(PHIOp); 11905 CopyValueToVirtualRegister(PHIOp, Reg); 11906 } 11907 } 11908 11909 // Remember that this register needs to added to the machine PHI node as 11910 // the input for this MBB. 11911 SmallVector<EVT, 4> ValueVTs; 11912 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11913 for (EVT VT : ValueVTs) { 11914 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11915 for (unsigned i = 0; i != NumRegisters; ++i) 11916 FuncInfo.PHINodesToUpdate.push_back( 11917 std::make_pair(&*MBBI++, Reg + i)); 11918 Reg += NumRegisters; 11919 } 11920 } 11921 } 11922 11923 ConstantsOut.clear(); 11924 } 11925 11926 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11927 MachineFunction::iterator I(MBB); 11928 if (++I == FuncInfo.MF->end()) 11929 return nullptr; 11930 return &*I; 11931 } 11932 11933 /// During lowering new call nodes can be created (such as memset, etc.). 11934 /// Those will become new roots of the current DAG, but complications arise 11935 /// when they are tail calls. In such cases, the call lowering will update 11936 /// the root, but the builder still needs to know that a tail call has been 11937 /// lowered in order to avoid generating an additional return. 11938 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11939 // If the node is null, we do have a tail call. 11940 if (MaybeTC.getNode() != nullptr) 11941 DAG.setRoot(MaybeTC); 11942 else 11943 HasTailCall = true; 11944 } 11945 11946 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11947 MachineBasicBlock *SwitchMBB, 11948 MachineBasicBlock *DefaultMBB) { 11949 MachineFunction *CurMF = FuncInfo.MF; 11950 MachineBasicBlock *NextMBB = nullptr; 11951 MachineFunction::iterator BBI(W.MBB); 11952 if (++BBI != FuncInfo.MF->end()) 11953 NextMBB = &*BBI; 11954 11955 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11956 11957 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11958 11959 if (Size == 2 && W.MBB == SwitchMBB) { 11960 // If any two of the cases has the same destination, and if one value 11961 // is the same as the other, but has one bit unset that the other has set, 11962 // use bit manipulation to do two compares at once. For example: 11963 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11964 // TODO: This could be extended to merge any 2 cases in switches with 3 11965 // cases. 11966 // TODO: Handle cases where W.CaseBB != SwitchBB. 11967 CaseCluster &Small = *W.FirstCluster; 11968 CaseCluster &Big = *W.LastCluster; 11969 11970 if (Small.Low == Small.High && Big.Low == Big.High && 11971 Small.MBB == Big.MBB) { 11972 const APInt &SmallValue = Small.Low->getValue(); 11973 const APInt &BigValue = Big.Low->getValue(); 11974 11975 // Check that there is only one bit different. 11976 APInt CommonBit = BigValue ^ SmallValue; 11977 if (CommonBit.isPowerOf2()) { 11978 SDValue CondLHS = getValue(Cond); 11979 EVT VT = CondLHS.getValueType(); 11980 SDLoc DL = getCurSDLoc(); 11981 11982 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11983 DAG.getConstant(CommonBit, DL, VT)); 11984 SDValue Cond = DAG.getSetCC( 11985 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11986 ISD::SETEQ); 11987 11988 // Update successor info. 11989 // Both Small and Big will jump to Small.BB, so we sum up the 11990 // probabilities. 11991 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11992 if (BPI) 11993 addSuccessorWithProb( 11994 SwitchMBB, DefaultMBB, 11995 // The default destination is the first successor in IR. 11996 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11997 else 11998 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11999 12000 // Insert the true branch. 12001 SDValue BrCond = 12002 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 12003 DAG.getBasicBlock(Small.MBB)); 12004 // Insert the false branch. 12005 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 12006 DAG.getBasicBlock(DefaultMBB)); 12007 12008 DAG.setRoot(BrCond); 12009 return; 12010 } 12011 } 12012 } 12013 12014 if (TM.getOptLevel() != CodeGenOptLevel::None) { 12015 // Here, we order cases by probability so the most likely case will be 12016 // checked first. However, two clusters can have the same probability in 12017 // which case their relative ordering is non-deterministic. So we use Low 12018 // as a tie-breaker as clusters are guaranteed to never overlap. 12019 llvm::sort(W.FirstCluster, W.LastCluster + 1, 12020 [](const CaseCluster &a, const CaseCluster &b) { 12021 return a.Prob != b.Prob ? 12022 a.Prob > b.Prob : 12023 a.Low->getValue().slt(b.Low->getValue()); 12024 }); 12025 12026 // Rearrange the case blocks so that the last one falls through if possible 12027 // without changing the order of probabilities. 12028 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 12029 --I; 12030 if (I->Prob > W.LastCluster->Prob) 12031 break; 12032 if (I->Kind == CC_Range && I->MBB == NextMBB) { 12033 std::swap(*I, *W.LastCluster); 12034 break; 12035 } 12036 } 12037 } 12038 12039 // Compute total probability. 12040 BranchProbability DefaultProb = W.DefaultProb; 12041 BranchProbability UnhandledProbs = DefaultProb; 12042 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 12043 UnhandledProbs += I->Prob; 12044 12045 MachineBasicBlock *CurMBB = W.MBB; 12046 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 12047 bool FallthroughUnreachable = false; 12048 MachineBasicBlock *Fallthrough; 12049 if (I == W.LastCluster) { 12050 // For the last cluster, fall through to the default destination. 12051 Fallthrough = DefaultMBB; 12052 FallthroughUnreachable = isa<UnreachableInst>( 12053 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 12054 } else { 12055 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 12056 CurMF->insert(BBI, Fallthrough); 12057 // Put Cond in a virtual register to make it available from the new blocks. 12058 ExportFromCurrentBlock(Cond); 12059 } 12060 UnhandledProbs -= I->Prob; 12061 12062 switch (I->Kind) { 12063 case CC_JumpTable: { 12064 // FIXME: Optimize away range check based on pivot comparisons. 12065 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 12066 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 12067 12068 // The jump block hasn't been inserted yet; insert it here. 12069 MachineBasicBlock *JumpMBB = JT->MBB; 12070 CurMF->insert(BBI, JumpMBB); 12071 12072 auto JumpProb = I->Prob; 12073 auto FallthroughProb = UnhandledProbs; 12074 12075 // If the default statement is a target of the jump table, we evenly 12076 // distribute the default probability to successors of CurMBB. Also 12077 // update the probability on the edge from JumpMBB to Fallthrough. 12078 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 12079 SE = JumpMBB->succ_end(); 12080 SI != SE; ++SI) { 12081 if (*SI == DefaultMBB) { 12082 JumpProb += DefaultProb / 2; 12083 FallthroughProb -= DefaultProb / 2; 12084 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 12085 JumpMBB->normalizeSuccProbs(); 12086 break; 12087 } 12088 } 12089 12090 // If the default clause is unreachable, propagate that knowledge into 12091 // JTH->FallthroughUnreachable which will use it to suppress the range 12092 // check. 12093 // 12094 // However, don't do this if we're doing branch target enforcement, 12095 // because a table branch _without_ a range check can be a tempting JOP 12096 // gadget - out-of-bounds inputs that are impossible in correct 12097 // execution become possible again if an attacker can influence the 12098 // control flow. So if an attacker doesn't already have a BTI bypass 12099 // available, we don't want them to be able to get one out of this 12100 // table branch. 12101 if (FallthroughUnreachable) { 12102 Function &CurFunc = CurMF->getFunction(); 12103 if (!CurFunc.hasFnAttribute("branch-target-enforcement")) 12104 JTH->FallthroughUnreachable = true; 12105 } 12106 12107 if (!JTH->FallthroughUnreachable) 12108 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 12109 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 12110 CurMBB->normalizeSuccProbs(); 12111 12112 // The jump table header will be inserted in our current block, do the 12113 // range check, and fall through to our fallthrough block. 12114 JTH->HeaderBB = CurMBB; 12115 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 12116 12117 // If we're in the right place, emit the jump table header right now. 12118 if (CurMBB == SwitchMBB) { 12119 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 12120 JTH->Emitted = true; 12121 } 12122 break; 12123 } 12124 case CC_BitTests: { 12125 // FIXME: Optimize away range check based on pivot comparisons. 12126 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 12127 12128 // The bit test blocks haven't been inserted yet; insert them here. 12129 for (BitTestCase &BTC : BTB->Cases) 12130 CurMF->insert(BBI, BTC.ThisBB); 12131 12132 // Fill in fields of the BitTestBlock. 12133 BTB->Parent = CurMBB; 12134 BTB->Default = Fallthrough; 12135 12136 BTB->DefaultProb = UnhandledProbs; 12137 // If the cases in bit test don't form a contiguous range, we evenly 12138 // distribute the probability on the edge to Fallthrough to two 12139 // successors of CurMBB. 12140 if (!BTB->ContiguousRange) { 12141 BTB->Prob += DefaultProb / 2; 12142 BTB->DefaultProb -= DefaultProb / 2; 12143 } 12144 12145 if (FallthroughUnreachable) 12146 BTB->FallthroughUnreachable = true; 12147 12148 // If we're in the right place, emit the bit test header right now. 12149 if (CurMBB == SwitchMBB) { 12150 visitBitTestHeader(*BTB, SwitchMBB); 12151 BTB->Emitted = true; 12152 } 12153 break; 12154 } 12155 case CC_Range: { 12156 const Value *RHS, *LHS, *MHS; 12157 ISD::CondCode CC; 12158 if (I->Low == I->High) { 12159 // Check Cond == I->Low. 12160 CC = ISD::SETEQ; 12161 LHS = Cond; 12162 RHS=I->Low; 12163 MHS = nullptr; 12164 } else { 12165 // Check I->Low <= Cond <= I->High. 12166 CC = ISD::SETLE; 12167 LHS = I->Low; 12168 MHS = Cond; 12169 RHS = I->High; 12170 } 12171 12172 // If Fallthrough is unreachable, fold away the comparison. 12173 if (FallthroughUnreachable) 12174 CC = ISD::SETTRUE; 12175 12176 // The false probability is the sum of all unhandled cases. 12177 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 12178 getCurSDLoc(), I->Prob, UnhandledProbs); 12179 12180 if (CurMBB == SwitchMBB) 12181 visitSwitchCase(CB, SwitchMBB); 12182 else 12183 SL->SwitchCases.push_back(CB); 12184 12185 break; 12186 } 12187 } 12188 CurMBB = Fallthrough; 12189 } 12190 } 12191 12192 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 12193 const SwitchWorkListItem &W, 12194 Value *Cond, 12195 MachineBasicBlock *SwitchMBB) { 12196 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 12197 "Clusters not sorted?"); 12198 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 12199 12200 auto [LastLeft, FirstRight, LeftProb, RightProb] = 12201 SL->computeSplitWorkItemInfo(W); 12202 12203 // Use the first element on the right as pivot since we will make less-than 12204 // comparisons against it. 12205 CaseClusterIt PivotCluster = FirstRight; 12206 assert(PivotCluster > W.FirstCluster); 12207 assert(PivotCluster <= W.LastCluster); 12208 12209 CaseClusterIt FirstLeft = W.FirstCluster; 12210 CaseClusterIt LastRight = W.LastCluster; 12211 12212 const ConstantInt *Pivot = PivotCluster->Low; 12213 12214 // New blocks will be inserted immediately after the current one. 12215 MachineFunction::iterator BBI(W.MBB); 12216 ++BBI; 12217 12218 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 12219 // we can branch to its destination directly if it's squeezed exactly in 12220 // between the known lower bound and Pivot - 1. 12221 MachineBasicBlock *LeftMBB; 12222 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 12223 FirstLeft->Low == W.GE && 12224 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 12225 LeftMBB = FirstLeft->MBB; 12226 } else { 12227 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12228 FuncInfo.MF->insert(BBI, LeftMBB); 12229 WorkList.push_back( 12230 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 12231 // Put Cond in a virtual register to make it available from the new blocks. 12232 ExportFromCurrentBlock(Cond); 12233 } 12234 12235 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 12236 // single cluster, RHS.Low == Pivot, and we can branch to its destination 12237 // directly if RHS.High equals the current upper bound. 12238 MachineBasicBlock *RightMBB; 12239 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 12240 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 12241 RightMBB = FirstRight->MBB; 12242 } else { 12243 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12244 FuncInfo.MF->insert(BBI, RightMBB); 12245 WorkList.push_back( 12246 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 12247 // Put Cond in a virtual register to make it available from the new blocks. 12248 ExportFromCurrentBlock(Cond); 12249 } 12250 12251 // Create the CaseBlock record that will be used to lower the branch. 12252 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 12253 getCurSDLoc(), LeftProb, RightProb); 12254 12255 if (W.MBB == SwitchMBB) 12256 visitSwitchCase(CB, SwitchMBB); 12257 else 12258 SL->SwitchCases.push_back(CB); 12259 } 12260 12261 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 12262 // from the swith statement. 12263 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 12264 BranchProbability PeeledCaseProb) { 12265 if (PeeledCaseProb == BranchProbability::getOne()) 12266 return BranchProbability::getZero(); 12267 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 12268 12269 uint32_t Numerator = CaseProb.getNumerator(); 12270 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 12271 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 12272 } 12273 12274 // Try to peel the top probability case if it exceeds the threshold. 12275 // Return current MachineBasicBlock for the switch statement if the peeling 12276 // does not occur. 12277 // If the peeling is performed, return the newly created MachineBasicBlock 12278 // for the peeled switch statement. Also update Clusters to remove the peeled 12279 // case. PeeledCaseProb is the BranchProbability for the peeled case. 12280 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 12281 const SwitchInst &SI, CaseClusterVector &Clusters, 12282 BranchProbability &PeeledCaseProb) { 12283 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12284 // Don't perform if there is only one cluster or optimizing for size. 12285 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 12286 TM.getOptLevel() == CodeGenOptLevel::None || 12287 SwitchMBB->getParent()->getFunction().hasMinSize()) 12288 return SwitchMBB; 12289 12290 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 12291 unsigned PeeledCaseIndex = 0; 12292 bool SwitchPeeled = false; 12293 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 12294 CaseCluster &CC = Clusters[Index]; 12295 if (CC.Prob < TopCaseProb) 12296 continue; 12297 TopCaseProb = CC.Prob; 12298 PeeledCaseIndex = Index; 12299 SwitchPeeled = true; 12300 } 12301 if (!SwitchPeeled) 12302 return SwitchMBB; 12303 12304 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 12305 << TopCaseProb << "\n"); 12306 12307 // Record the MBB for the peeled switch statement. 12308 MachineFunction::iterator BBI(SwitchMBB); 12309 ++BBI; 12310 MachineBasicBlock *PeeledSwitchMBB = 12311 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 12312 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 12313 12314 ExportFromCurrentBlock(SI.getCondition()); 12315 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 12316 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 12317 nullptr, nullptr, TopCaseProb.getCompl()}; 12318 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 12319 12320 Clusters.erase(PeeledCaseIt); 12321 for (CaseCluster &CC : Clusters) { 12322 LLVM_DEBUG( 12323 dbgs() << "Scale the probablity for one cluster, before scaling: " 12324 << CC.Prob << "\n"); 12325 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 12326 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 12327 } 12328 PeeledCaseProb = TopCaseProb; 12329 return PeeledSwitchMBB; 12330 } 12331 12332 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 12333 // Extract cases from the switch. 12334 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12335 CaseClusterVector Clusters; 12336 Clusters.reserve(SI.getNumCases()); 12337 for (auto I : SI.cases()) { 12338 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor()); 12339 const ConstantInt *CaseVal = I.getCaseValue(); 12340 BranchProbability Prob = 12341 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 12342 : BranchProbability(1, SI.getNumCases() + 1); 12343 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 12344 } 12345 12346 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest()); 12347 12348 // Cluster adjacent cases with the same destination. We do this at all 12349 // optimization levels because it's cheap to do and will make codegen faster 12350 // if there are many clusters. 12351 sortAndRangeify(Clusters); 12352 12353 // The branch probablity of the peeled case. 12354 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 12355 MachineBasicBlock *PeeledSwitchMBB = 12356 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 12357 12358 // If there is only the default destination, jump there directly. 12359 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12360 if (Clusters.empty()) { 12361 assert(PeeledSwitchMBB == SwitchMBB); 12362 SwitchMBB->addSuccessor(DefaultMBB); 12363 if (DefaultMBB != NextBlock(SwitchMBB)) { 12364 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 12365 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 12366 } 12367 return; 12368 } 12369 12370 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 12371 DAG.getBFI()); 12372 SL->findBitTestClusters(Clusters, &SI); 12373 12374 LLVM_DEBUG({ 12375 dbgs() << "Case clusters: "; 12376 for (const CaseCluster &C : Clusters) { 12377 if (C.Kind == CC_JumpTable) 12378 dbgs() << "JT:"; 12379 if (C.Kind == CC_BitTests) 12380 dbgs() << "BT:"; 12381 12382 C.Low->getValue().print(dbgs(), true); 12383 if (C.Low != C.High) { 12384 dbgs() << '-'; 12385 C.High->getValue().print(dbgs(), true); 12386 } 12387 dbgs() << ' '; 12388 } 12389 dbgs() << '\n'; 12390 }); 12391 12392 assert(!Clusters.empty()); 12393 SwitchWorkList WorkList; 12394 CaseClusterIt First = Clusters.begin(); 12395 CaseClusterIt Last = Clusters.end() - 1; 12396 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 12397 // Scale the branchprobability for DefaultMBB if the peel occurs and 12398 // DefaultMBB is not replaced. 12399 if (PeeledCaseProb != BranchProbability::getZero() && 12400 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest())) 12401 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 12402 WorkList.push_back( 12403 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 12404 12405 while (!WorkList.empty()) { 12406 SwitchWorkListItem W = WorkList.pop_back_val(); 12407 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 12408 12409 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 12410 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 12411 // For optimized builds, lower large range as a balanced binary tree. 12412 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 12413 continue; 12414 } 12415 12416 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 12417 } 12418 } 12419 12420 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 12421 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12422 auto DL = getCurSDLoc(); 12423 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12424 setValue(&I, DAG.getStepVector(DL, ResultVT)); 12425 } 12426 12427 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 12428 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12429 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12430 12431 SDLoc DL = getCurSDLoc(); 12432 SDValue V = getValue(I.getOperand(0)); 12433 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 12434 12435 if (VT.isScalableVector()) { 12436 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 12437 return; 12438 } 12439 12440 // Use VECTOR_SHUFFLE for the fixed-length vector 12441 // to maintain existing behavior. 12442 SmallVector<int, 8> Mask; 12443 unsigned NumElts = VT.getVectorMinNumElements(); 12444 for (unsigned i = 0; i != NumElts; ++i) 12445 Mask.push_back(NumElts - 1 - i); 12446 12447 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 12448 } 12449 12450 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 12451 auto DL = getCurSDLoc(); 12452 SDValue InVec = getValue(I.getOperand(0)); 12453 EVT OutVT = 12454 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 12455 12456 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 12457 12458 // ISD Node needs the input vectors split into two equal parts 12459 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12460 DAG.getVectorIdxConstant(0, DL)); 12461 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12462 DAG.getVectorIdxConstant(OutNumElts, DL)); 12463 12464 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12465 // legalisation and combines. 12466 if (OutVT.isFixedLengthVector()) { 12467 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12468 createStrideMask(0, 2, OutNumElts)); 12469 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12470 createStrideMask(1, 2, OutNumElts)); 12471 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 12472 setValue(&I, Res); 12473 return; 12474 } 12475 12476 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12477 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12478 setValue(&I, Res); 12479 } 12480 12481 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12482 auto DL = getCurSDLoc(); 12483 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12484 SDValue InVec0 = getValue(I.getOperand(0)); 12485 SDValue InVec1 = getValue(I.getOperand(1)); 12486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12487 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12488 12489 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12490 // legalisation and combines. 12491 if (OutVT.isFixedLengthVector()) { 12492 unsigned NumElts = InVT.getVectorMinNumElements(); 12493 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12494 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12495 createInterleaveMask(NumElts, 2))); 12496 return; 12497 } 12498 12499 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12500 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12501 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12502 Res.getValue(1)); 12503 setValue(&I, Res); 12504 } 12505 12506 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12507 SmallVector<EVT, 4> ValueVTs; 12508 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12509 ValueVTs); 12510 unsigned NumValues = ValueVTs.size(); 12511 if (NumValues == 0) return; 12512 12513 SmallVector<SDValue, 4> Values(NumValues); 12514 SDValue Op = getValue(I.getOperand(0)); 12515 12516 for (unsigned i = 0; i != NumValues; ++i) 12517 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12518 SDValue(Op.getNode(), Op.getResNo() + i)); 12519 12520 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12521 DAG.getVTList(ValueVTs), Values)); 12522 } 12523 12524 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12525 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12526 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12527 12528 SDLoc DL = getCurSDLoc(); 12529 SDValue V1 = getValue(I.getOperand(0)); 12530 SDValue V2 = getValue(I.getOperand(1)); 12531 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12532 12533 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12534 if (VT.isScalableVector()) { 12535 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12536 DAG.getVectorIdxConstant(Imm, DL))); 12537 return; 12538 } 12539 12540 unsigned NumElts = VT.getVectorNumElements(); 12541 12542 uint64_t Idx = (NumElts + Imm) % NumElts; 12543 12544 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12545 SmallVector<int, 8> Mask; 12546 for (unsigned i = 0; i < NumElts; ++i) 12547 Mask.push_back(Idx + i); 12548 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12549 } 12550 12551 // Consider the following MIR after SelectionDAG, which produces output in 12552 // phyregs in the first case or virtregs in the second case. 12553 // 12554 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12555 // %5:gr32 = COPY $ebx 12556 // %6:gr32 = COPY $edx 12557 // %1:gr32 = COPY %6:gr32 12558 // %0:gr32 = COPY %5:gr32 12559 // 12560 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12561 // %1:gr32 = COPY %6:gr32 12562 // %0:gr32 = COPY %5:gr32 12563 // 12564 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12565 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12566 // 12567 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12568 // to a single virtreg (such as %0). The remaining outputs monotonically 12569 // increase in virtreg number from there. If a callbr has no outputs, then it 12570 // should not have a corresponding callbr landingpad; in fact, the callbr 12571 // landingpad would not even be able to refer to such a callbr. 12572 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12573 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12574 // There is definitely at least one copy. 12575 assert(MI->getOpcode() == TargetOpcode::COPY && 12576 "start of copy chain MUST be COPY"); 12577 Reg = MI->getOperand(1).getReg(); 12578 MI = MRI.def_begin(Reg)->getParent(); 12579 // There may be an optional second copy. 12580 if (MI->getOpcode() == TargetOpcode::COPY) { 12581 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12582 Reg = MI->getOperand(1).getReg(); 12583 assert(Reg.isPhysical() && "expected COPY of physical register"); 12584 MI = MRI.def_begin(Reg)->getParent(); 12585 } 12586 // The start of the chain must be an INLINEASM_BR. 12587 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12588 "end of copy chain MUST be INLINEASM_BR"); 12589 return Reg; 12590 } 12591 12592 // We must do this walk rather than the simpler 12593 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12594 // otherwise we will end up with copies of virtregs only valid along direct 12595 // edges. 12596 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12597 SmallVector<EVT, 8> ResultVTs; 12598 SmallVector<SDValue, 8> ResultValues; 12599 const auto *CBR = 12600 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12601 12602 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12603 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12604 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12605 12606 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12607 SDValue Chain = DAG.getRoot(); 12608 12609 // Re-parse the asm constraints string. 12610 TargetLowering::AsmOperandInfoVector TargetConstraints = 12611 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12612 for (auto &T : TargetConstraints) { 12613 SDISelAsmOperandInfo OpInfo(T); 12614 if (OpInfo.Type != InlineAsm::isOutput) 12615 continue; 12616 12617 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12618 // individual constraint. 12619 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12620 12621 switch (OpInfo.ConstraintType) { 12622 case TargetLowering::C_Register: 12623 case TargetLowering::C_RegisterClass: { 12624 // Fill in OpInfo.AssignedRegs.Regs. 12625 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12626 12627 // getRegistersForValue may produce 1 to many registers based on whether 12628 // the OpInfo.ConstraintVT is legal on the target or not. 12629 for (unsigned &Reg : OpInfo.AssignedRegs.Regs) { 12630 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12631 if (Register::isPhysicalRegister(OriginalDef)) 12632 FuncInfo.MBB->addLiveIn(OriginalDef); 12633 // Update the assigned registers to use the original defs. 12634 Reg = OriginalDef; 12635 } 12636 12637 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12638 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12639 ResultValues.push_back(V); 12640 ResultVTs.push_back(OpInfo.ConstraintVT); 12641 break; 12642 } 12643 case TargetLowering::C_Other: { 12644 SDValue Flag; 12645 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12646 OpInfo, DAG); 12647 ++InitialDef; 12648 ResultValues.push_back(V); 12649 ResultVTs.push_back(OpInfo.ConstraintVT); 12650 break; 12651 } 12652 default: 12653 break; 12654 } 12655 } 12656 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12657 DAG.getVTList(ResultVTs), ResultValues); 12658 setValue(&I, V); 12659 } 12660