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/RuntimeLibcalls.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/Metadata.h" 84 #include "llvm/IR/Module.h" 85 #include "llvm/IR/Operator.h" 86 #include "llvm/IR/PatternMatch.h" 87 #include "llvm/IR/Statepoint.h" 88 #include "llvm/IR/Type.h" 89 #include "llvm/IR/User.h" 90 #include "llvm/IR/Value.h" 91 #include "llvm/MC/MCContext.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/InstructionCost.h" 98 #include "llvm/Support/MathExtras.h" 99 #include "llvm/Support/raw_ostream.h" 100 #include "llvm/Target/TargetIntrinsicInfo.h" 101 #include "llvm/Target/TargetMachine.h" 102 #include "llvm/Target/TargetOptions.h" 103 #include "llvm/TargetParser/Triple.h" 104 #include "llvm/Transforms/Utils/Local.h" 105 #include <cstddef> 106 #include <iterator> 107 #include <limits> 108 #include <optional> 109 #include <tuple> 110 111 using namespace llvm; 112 using namespace PatternMatch; 113 using namespace SwitchCG; 114 115 #define DEBUG_TYPE "isel" 116 117 /// LimitFloatPrecision - Generate low-precision inline sequences for 118 /// some float libcalls (6, 8 or 12 bits). 119 static unsigned LimitFloatPrecision; 120 121 static cl::opt<bool> 122 InsertAssertAlign("insert-assert-align", cl::init(true), 123 cl::desc("Insert the experimental `assertalign` node."), 124 cl::ReallyHidden); 125 126 static cl::opt<unsigned, true> 127 LimitFPPrecision("limit-float-precision", 128 cl::desc("Generate low-precision inline sequences " 129 "for some float libcalls"), 130 cl::location(LimitFloatPrecision), cl::Hidden, 131 cl::init(0)); 132 133 static cl::opt<unsigned> SwitchPeelThreshold( 134 "switch-peel-threshold", cl::Hidden, cl::init(66), 135 cl::desc("Set the case probability threshold for peeling the case from a " 136 "switch statement. A value greater than 100 will void this " 137 "optimization")); 138 139 // Limit the width of DAG chains. This is important in general to prevent 140 // DAG-based analysis from blowing up. For example, alias analysis and 141 // load clustering may not complete in reasonable time. It is difficult to 142 // recognize and avoid this situation within each individual analysis, and 143 // future analyses are likely to have the same behavior. Limiting DAG width is 144 // the safe approach and will be especially important with global DAGs. 145 // 146 // MaxParallelChains default is arbitrarily high to avoid affecting 147 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 148 // sequence over this should have been converted to llvm.memcpy by the 149 // frontend. It is easy to induce this behavior with .ll code such as: 150 // %buffer = alloca [4096 x i8] 151 // %data = load [4096 x i8]* %argPtr 152 // store [4096 x i8] %data, [4096 x i8]* %buffer 153 static const unsigned MaxParallelChains = 64; 154 155 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 156 const SDValue *Parts, unsigned NumParts, 157 MVT PartVT, EVT ValueVT, const Value *V, 158 SDValue InChain, 159 std::optional<CallingConv::ID> CC); 160 161 /// getCopyFromParts - Create a value that contains the specified legal parts 162 /// combined into the value they represent. If the parts combine to a type 163 /// larger than ValueVT then AssertOp can be used to specify whether the extra 164 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 165 /// (ISD::AssertSext). 166 static SDValue 167 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 168 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 169 SDValue InChain, 170 std::optional<CallingConv::ID> CC = std::nullopt, 171 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 172 // Let the target assemble the parts if it wants to 173 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 174 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 175 PartVT, ValueVT, CC)) 176 return Val; 177 178 if (ValueVT.isVector()) 179 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 180 InChain, CC); 181 182 assert(NumParts > 0 && "No parts to assemble!"); 183 SDValue Val = Parts[0]; 184 185 if (NumParts > 1) { 186 // Assemble the value from multiple parts. 187 if (ValueVT.isInteger()) { 188 unsigned PartBits = PartVT.getSizeInBits(); 189 unsigned ValueBits = ValueVT.getSizeInBits(); 190 191 // Assemble the power of 2 part. 192 unsigned RoundParts = llvm::bit_floor(NumParts); 193 unsigned RoundBits = PartBits * RoundParts; 194 EVT RoundVT = RoundBits == ValueBits ? 195 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 196 SDValue Lo, Hi; 197 198 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 199 200 if (RoundParts > 2) { 201 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V, 202 InChain); 203 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2, 204 PartVT, HalfVT, V, InChain); 205 } else { 206 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 207 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 208 } 209 210 if (DAG.getDataLayout().isBigEndian()) 211 std::swap(Lo, Hi); 212 213 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 214 215 if (RoundParts < NumParts) { 216 // Assemble the trailing non-power-of-2 part. 217 unsigned OddParts = NumParts - RoundParts; 218 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 219 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 220 OddVT, V, InChain, CC); 221 222 // Combine the round and odd parts. 223 Lo = Val; 224 if (DAG.getDataLayout().isBigEndian()) 225 std::swap(Lo, Hi); 226 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 227 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 228 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 229 DAG.getConstant(Lo.getValueSizeInBits(), DL, 230 TLI.getShiftAmountTy( 231 TotalVT, DAG.getDataLayout()))); 232 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 233 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 234 } 235 } else if (PartVT.isFloatingPoint()) { 236 // FP split into multiple FP parts (for ppcf128) 237 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 238 "Unexpected split"); 239 SDValue Lo, Hi; 240 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 241 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 242 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 243 std::swap(Lo, Hi); 244 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 245 } else { 246 // FP split into integer parts (soft fp) 247 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 248 !PartVT.isVector() && "Unexpected split"); 249 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 250 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, 251 InChain, CC); 252 } 253 } 254 255 // There is now one part, held in Val. Correct it to match ValueVT. 256 // PartEVT is the type of the register class that holds the value. 257 // ValueVT is the type of the inline asm operation. 258 EVT PartEVT = Val.getValueType(); 259 260 if (PartEVT == ValueVT) 261 return Val; 262 263 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 264 ValueVT.bitsLT(PartEVT)) { 265 // For an FP value in an integer part, we need to truncate to the right 266 // width first. 267 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 268 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 269 } 270 271 // Handle types that have the same size. 272 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 273 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 274 275 // Handle types with different sizes. 276 if (PartEVT.isInteger() && ValueVT.isInteger()) { 277 if (ValueVT.bitsLT(PartEVT)) { 278 // For a truncate, see if we have any information to 279 // indicate whether the truncated bits will always be 280 // zero or sign-extension. 281 if (AssertOp) 282 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 283 DAG.getValueType(ValueVT)); 284 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 285 } 286 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 287 } 288 289 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 290 // FP_ROUND's are always exact here. 291 if (ValueVT.bitsLT(Val.getValueType())) { 292 293 SDValue NoChange = 294 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 295 296 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr( 297 llvm::Attribute::StrictFP)) { 298 return DAG.getNode(ISD::STRICT_FP_ROUND, DL, 299 DAG.getVTList(ValueVT, MVT::Other), InChain, Val, 300 NoChange); 301 } 302 303 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange); 304 } 305 306 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 307 } 308 309 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 310 // then truncating. 311 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 312 ValueVT.bitsLT(PartEVT)) { 313 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 314 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 315 } 316 317 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 318 } 319 320 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 321 const Twine &ErrMsg) { 322 const Instruction *I = dyn_cast_or_null<Instruction>(V); 323 if (!V) 324 return Ctx.emitError(ErrMsg); 325 326 const char *AsmError = ", possible invalid constraint for vector type"; 327 if (const CallInst *CI = dyn_cast<CallInst>(I)) 328 if (CI->isInlineAsm()) 329 return Ctx.emitError(I, ErrMsg + AsmError); 330 331 return Ctx.emitError(I, ErrMsg); 332 } 333 334 /// getCopyFromPartsVector - Create a value that contains the specified legal 335 /// parts combined into the value they represent. If the parts combine to a 336 /// type larger than ValueVT then AssertOp can be used to specify whether the 337 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 338 /// ValueVT (ISD::AssertSext). 339 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 340 const SDValue *Parts, unsigned NumParts, 341 MVT PartVT, EVT ValueVT, const Value *V, 342 SDValue InChain, 343 std::optional<CallingConv::ID> CallConv) { 344 assert(ValueVT.isVector() && "Not a vector value"); 345 assert(NumParts > 0 && "No parts to assemble!"); 346 const bool IsABIRegCopy = CallConv.has_value(); 347 348 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 349 SDValue Val = Parts[0]; 350 351 // Handle a multi-element vector. 352 if (NumParts > 1) { 353 EVT IntermediateVT; 354 MVT RegisterVT; 355 unsigned NumIntermediates; 356 unsigned NumRegs; 357 358 if (IsABIRegCopy) { 359 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 360 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 361 NumIntermediates, RegisterVT); 362 } else { 363 NumRegs = 364 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 365 NumIntermediates, RegisterVT); 366 } 367 368 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 369 NumParts = NumRegs; // Silence a compiler warning. 370 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 371 assert(RegisterVT.getSizeInBits() == 372 Parts[0].getSimpleValueType().getSizeInBits() && 373 "Part type sizes don't match!"); 374 375 // Assemble the parts into intermediate operands. 376 SmallVector<SDValue, 8> Ops(NumIntermediates); 377 if (NumIntermediates == NumParts) { 378 // If the register was not expanded, truncate or copy the value, 379 // as appropriate. 380 for (unsigned i = 0; i != NumParts; ++i) 381 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT, 382 V, InChain, CallConv); 383 } else if (NumParts > 0) { 384 // If the intermediate type was expanded, build the intermediate 385 // operands from the parts. 386 assert(NumParts % NumIntermediates == 0 && 387 "Must expand into a divisible number of parts!"); 388 unsigned Factor = NumParts / NumIntermediates; 389 for (unsigned i = 0; i != NumIntermediates; ++i) 390 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT, 391 IntermediateVT, V, InChain, CallConv); 392 } 393 394 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 395 // intermediate operands. 396 EVT BuiltVectorTy = 397 IntermediateVT.isVector() 398 ? EVT::getVectorVT( 399 *DAG.getContext(), IntermediateVT.getScalarType(), 400 IntermediateVT.getVectorElementCount() * NumParts) 401 : EVT::getVectorVT(*DAG.getContext(), 402 IntermediateVT.getScalarType(), 403 NumIntermediates); 404 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 405 : ISD::BUILD_VECTOR, 406 DL, BuiltVectorTy, Ops); 407 } 408 409 // There is now one part, held in Val. Correct it to match ValueVT. 410 EVT PartEVT = Val.getValueType(); 411 412 if (PartEVT == ValueVT) 413 return Val; 414 415 if (PartEVT.isVector()) { 416 // Vector/Vector bitcast. 417 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 420 // If the parts vector has more elements than the value vector, then we 421 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 422 // Extract the elements we want. 423 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 424 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 425 ValueVT.getVectorElementCount().getKnownMinValue()) && 426 (PartEVT.getVectorElementCount().isScalable() == 427 ValueVT.getVectorElementCount().isScalable()) && 428 "Cannot narrow, it would be a lossy transformation"); 429 PartEVT = 430 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 431 ValueVT.getVectorElementCount()); 432 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 433 DAG.getVectorIdxConstant(0, DL)); 434 if (PartEVT == ValueVT) 435 return Val; 436 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 437 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 438 439 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 440 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 441 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 442 } 443 444 // Promoted vector extract 445 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 446 } 447 448 // Trivial bitcast if the types are the same size and the destination 449 // vector type is legal. 450 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 451 TLI.isTypeLegal(ValueVT)) 452 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 453 454 if (ValueVT.getVectorNumElements() != 1) { 455 // Certain ABIs require that vectors are passed as integers. For vectors 456 // are the same size, this is an obvious bitcast. 457 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 458 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 459 } else if (ValueVT.bitsLT(PartEVT)) { 460 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 462 // Drop the extra bits. 463 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 464 return DAG.getBitcast(ValueVT, Val); 465 } 466 467 diagnosePossiblyInvalidConstraint( 468 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 469 return DAG.getUNDEF(ValueVT); 470 } 471 472 // Handle cases such as i8 -> <1 x i1> 473 EVT ValueSVT = ValueVT.getVectorElementType(); 474 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 475 unsigned ValueSize = ValueSVT.getSizeInBits(); 476 if (ValueSize == PartEVT.getSizeInBits()) { 477 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 478 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 479 // It's possible a scalar floating point type gets softened to integer and 480 // then promoted to a larger integer. If PartEVT is the larger integer 481 // we need to truncate it and then bitcast to the FP type. 482 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 483 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 484 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 485 Val = DAG.getBitcast(ValueSVT, Val); 486 } else { 487 Val = ValueVT.isFloatingPoint() 488 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 489 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 490 } 491 } 492 493 return DAG.getBuildVector(ValueVT, DL, Val); 494 } 495 496 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 497 SDValue Val, SDValue *Parts, unsigned NumParts, 498 MVT PartVT, const Value *V, 499 std::optional<CallingConv::ID> CallConv); 500 501 /// getCopyToParts - Create a series of nodes that contain the specified value 502 /// split into legal parts. If the parts contain more bits than Val, then, for 503 /// integers, ExtendKind can be used to specify how to generate the extra bits. 504 static void 505 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 506 unsigned NumParts, MVT PartVT, const Value *V, 507 std::optional<CallingConv::ID> CallConv = std::nullopt, 508 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 509 // Let the target split the parts if it wants to 510 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 511 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 512 CallConv)) 513 return; 514 EVT ValueVT = Val.getValueType(); 515 516 // Handle the vector case separately. 517 if (ValueVT.isVector()) 518 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 519 CallConv); 520 521 unsigned OrigNumParts = NumParts; 522 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 523 "Copying to an illegal type!"); 524 525 if (NumParts == 0) 526 return; 527 528 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 529 EVT PartEVT = PartVT; 530 if (PartEVT == ValueVT) { 531 assert(NumParts == 1 && "No-op copy with multiple parts!"); 532 Parts[0] = Val; 533 return; 534 } 535 536 unsigned PartBits = PartVT.getSizeInBits(); 537 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 538 // If the parts cover more bits than the value has, promote the value. 539 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 540 assert(NumParts == 1 && "Do not know what to promote to!"); 541 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 542 } else { 543 if (ValueVT.isFloatingPoint()) { 544 // FP values need to be bitcast, then extended if they are being put 545 // into a larger container. 546 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 547 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 548 } 549 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 550 ValueVT.isInteger() && 551 "Unknown mismatch!"); 552 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 553 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 554 if (PartVT == MVT::x86mmx) 555 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 556 } 557 } else if (PartBits == ValueVT.getSizeInBits()) { 558 // Different types of the same size. 559 assert(NumParts == 1 && PartEVT != ValueVT); 560 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 561 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 562 // If the parts cover less bits than value has, truncate the value. 563 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 564 ValueVT.isInteger() && 565 "Unknown mismatch!"); 566 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 567 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 568 if (PartVT == MVT::x86mmx) 569 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 570 } 571 572 // The value may have changed - recompute ValueVT. 573 ValueVT = Val.getValueType(); 574 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 575 "Failed to tile the value with PartVT!"); 576 577 if (NumParts == 1) { 578 if (PartEVT != ValueVT) { 579 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 580 "scalar-to-vector conversion failed"); 581 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 582 } 583 584 Parts[0] = Val; 585 return; 586 } 587 588 // Expand the value into multiple parts. 589 if (NumParts & (NumParts - 1)) { 590 // The number of parts is not a power of 2. Split off and copy the tail. 591 assert(PartVT.isInteger() && ValueVT.isInteger() && 592 "Do not know what to expand to!"); 593 unsigned RoundParts = llvm::bit_floor(NumParts); 594 unsigned RoundBits = RoundParts * PartBits; 595 unsigned OddParts = NumParts - RoundParts; 596 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 597 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 598 599 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 600 CallConv); 601 602 if (DAG.getDataLayout().isBigEndian()) 603 // The odd parts were reversed by getCopyToParts - unreverse them. 604 std::reverse(Parts + RoundParts, Parts + NumParts); 605 606 NumParts = RoundParts; 607 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 608 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 609 } 610 611 // The number of parts is a power of 2. Repeatedly bisect the value using 612 // EXTRACT_ELEMENT. 613 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 614 EVT::getIntegerVT(*DAG.getContext(), 615 ValueVT.getSizeInBits()), 616 Val); 617 618 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 619 for (unsigned i = 0; i < NumParts; i += StepSize) { 620 unsigned ThisBits = StepSize * PartBits / 2; 621 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 622 SDValue &Part0 = Parts[i]; 623 SDValue &Part1 = Parts[i+StepSize/2]; 624 625 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 626 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 627 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 628 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 629 630 if (ThisBits == PartBits && ThisVT != PartVT) { 631 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 632 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 633 } 634 } 635 } 636 637 if (DAG.getDataLayout().isBigEndian()) 638 std::reverse(Parts, Parts + OrigNumParts); 639 } 640 641 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 642 const SDLoc &DL, EVT PartVT) { 643 if (!PartVT.isVector()) 644 return SDValue(); 645 646 EVT ValueVT = Val.getValueType(); 647 EVT PartEVT = PartVT.getVectorElementType(); 648 EVT ValueEVT = ValueVT.getVectorElementType(); 649 ElementCount PartNumElts = PartVT.getVectorElementCount(); 650 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 651 652 // We only support widening vectors with equivalent element types and 653 // fixed/scalable properties. If a target needs to widen a fixed-length type 654 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 655 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 656 PartNumElts.isScalable() != ValueNumElts.isScalable()) 657 return SDValue(); 658 659 // Have a try for bf16 because some targets share its ABI with fp16. 660 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 661 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 662 "Cannot widen to illegal type"); 663 Val = DAG.getNode(ISD::BITCAST, DL, 664 ValueVT.changeVectorElementType(MVT::f16), Val); 665 } else if (PartEVT != ValueEVT) { 666 return SDValue(); 667 } 668 669 // Widening a scalable vector to another scalable vector is done by inserting 670 // the vector into a larger undef one. 671 if (PartNumElts.isScalable()) 672 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 673 Val, DAG.getVectorIdxConstant(0, DL)); 674 675 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 676 // undef elements. 677 SmallVector<SDValue, 16> Ops; 678 DAG.ExtractVectorElements(Val, Ops); 679 SDValue EltUndef = DAG.getUNDEF(PartEVT); 680 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 681 682 // FIXME: Use CONCAT for 2x -> 4x. 683 return DAG.getBuildVector(PartVT, DL, Ops); 684 } 685 686 /// getCopyToPartsVector - Create a series of nodes that contain the specified 687 /// value split into legal parts. 688 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 689 SDValue Val, SDValue *Parts, unsigned NumParts, 690 MVT PartVT, const Value *V, 691 std::optional<CallingConv::ID> CallConv) { 692 EVT ValueVT = Val.getValueType(); 693 assert(ValueVT.isVector() && "Not a vector"); 694 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 695 const bool IsABIRegCopy = CallConv.has_value(); 696 697 if (NumParts == 1) { 698 EVT PartEVT = PartVT; 699 if (PartEVT == ValueVT) { 700 // Nothing to do. 701 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 702 // Bitconvert vector->vector case. 703 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 704 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 705 Val = Widened; 706 } else if (PartVT.isVector() && 707 PartEVT.getVectorElementType().bitsGE( 708 ValueVT.getVectorElementType()) && 709 PartEVT.getVectorElementCount() == 710 ValueVT.getVectorElementCount()) { 711 712 // Promoted vector extract 713 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 714 } else if (PartEVT.isVector() && 715 PartEVT.getVectorElementType() != 716 ValueVT.getVectorElementType() && 717 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 718 TargetLowering::TypeWidenVector) { 719 // Combination of widening and promotion. 720 EVT WidenVT = 721 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 722 PartVT.getVectorElementCount()); 723 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 724 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 725 } else { 726 // Don't extract an integer from a float vector. This can happen if the 727 // FP type gets softened to integer and then promoted. The promotion 728 // prevents it from being picked up by the earlier bitcast case. 729 if (ValueVT.getVectorElementCount().isScalar() && 730 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 731 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 732 DAG.getVectorIdxConstant(0, DL)); 733 } else { 734 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 735 assert(PartVT.getFixedSizeInBits() > ValueSize && 736 "lossy conversion of vector to scalar type"); 737 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 738 Val = DAG.getBitcast(IntermediateType, Val); 739 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 740 } 741 } 742 743 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 744 Parts[0] = Val; 745 return; 746 } 747 748 // Handle a multi-element vector. 749 EVT IntermediateVT; 750 MVT RegisterVT; 751 unsigned NumIntermediates; 752 unsigned NumRegs; 753 if (IsABIRegCopy) { 754 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 755 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 756 RegisterVT); 757 } else { 758 NumRegs = 759 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 760 NumIntermediates, RegisterVT); 761 } 762 763 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 764 NumParts = NumRegs; // Silence a compiler warning. 765 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 766 767 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 768 "Mixing scalable and fixed vectors when copying in parts"); 769 770 std::optional<ElementCount> DestEltCnt; 771 772 if (IntermediateVT.isVector()) 773 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 774 else 775 DestEltCnt = ElementCount::getFixed(NumIntermediates); 776 777 EVT BuiltVectorTy = EVT::getVectorVT( 778 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 779 780 if (ValueVT == BuiltVectorTy) { 781 // Nothing to do. 782 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 783 // Bitconvert vector->vector case. 784 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 785 } else { 786 if (BuiltVectorTy.getVectorElementType().bitsGT( 787 ValueVT.getVectorElementType())) { 788 // Integer promotion. 789 ValueVT = EVT::getVectorVT(*DAG.getContext(), 790 BuiltVectorTy.getVectorElementType(), 791 ValueVT.getVectorElementCount()); 792 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 793 } 794 795 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 796 Val = Widened; 797 } 798 } 799 800 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 801 802 // Split the vector into intermediate operands. 803 SmallVector<SDValue, 8> Ops(NumIntermediates); 804 for (unsigned i = 0; i != NumIntermediates; ++i) { 805 if (IntermediateVT.isVector()) { 806 // This does something sensible for scalable vectors - see the 807 // definition of EXTRACT_SUBVECTOR for further details. 808 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 809 Ops[i] = 810 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 811 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 812 } else { 813 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 814 DAG.getVectorIdxConstant(i, DL)); 815 } 816 } 817 818 // Split the intermediate operands into legal parts. 819 if (NumParts == NumIntermediates) { 820 // If the register was not expanded, promote or copy the value, 821 // as appropriate. 822 for (unsigned i = 0; i != NumParts; ++i) 823 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 824 } else if (NumParts > 0) { 825 // If the intermediate type was expanded, split each the value into 826 // legal parts. 827 assert(NumIntermediates != 0 && "division by zero"); 828 assert(NumParts % NumIntermediates == 0 && 829 "Must expand into a divisible number of parts!"); 830 unsigned Factor = NumParts / NumIntermediates; 831 for (unsigned i = 0; i != NumIntermediates; ++i) 832 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 833 CallConv); 834 } 835 } 836 837 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 838 EVT valuevt, std::optional<CallingConv::ID> CC) 839 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 840 RegCount(1, regs.size()), CallConv(CC) {} 841 842 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 843 const DataLayout &DL, unsigned Reg, Type *Ty, 844 std::optional<CallingConv::ID> CC) { 845 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 846 847 CallConv = CC; 848 849 for (EVT ValueVT : ValueVTs) { 850 unsigned NumRegs = 851 isABIMangled() 852 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 853 : TLI.getNumRegisters(Context, ValueVT); 854 MVT RegisterVT = 855 isABIMangled() 856 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 857 : TLI.getRegisterType(Context, ValueVT); 858 for (unsigned i = 0; i != NumRegs; ++i) 859 Regs.push_back(Reg + i); 860 RegVTs.push_back(RegisterVT); 861 RegCount.push_back(NumRegs); 862 Reg += NumRegs; 863 } 864 } 865 866 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 867 FunctionLoweringInfo &FuncInfo, 868 const SDLoc &dl, SDValue &Chain, 869 SDValue *Glue, const Value *V) const { 870 // A Value with type {} or [0 x %t] needs no registers. 871 if (ValueVTs.empty()) 872 return SDValue(); 873 874 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 875 876 // Assemble the legal parts into the final values. 877 SmallVector<SDValue, 4> Values(ValueVTs.size()); 878 SmallVector<SDValue, 8> Parts; 879 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 880 // Copy the legal parts from the registers. 881 EVT ValueVT = ValueVTs[Value]; 882 unsigned NumRegs = RegCount[Value]; 883 MVT RegisterVT = isABIMangled() 884 ? TLI.getRegisterTypeForCallingConv( 885 *DAG.getContext(), *CallConv, RegVTs[Value]) 886 : RegVTs[Value]; 887 888 Parts.resize(NumRegs); 889 for (unsigned i = 0; i != NumRegs; ++i) { 890 SDValue P; 891 if (!Glue) { 892 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 893 } else { 894 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 895 *Glue = P.getValue(2); 896 } 897 898 Chain = P.getValue(1); 899 Parts[i] = P; 900 901 // If the source register was virtual and if we know something about it, 902 // add an assert node. 903 if (!Register::isVirtualRegister(Regs[Part + i]) || 904 !RegisterVT.isInteger()) 905 continue; 906 907 const FunctionLoweringInfo::LiveOutInfo *LOI = 908 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 909 if (!LOI) 910 continue; 911 912 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 913 unsigned NumSignBits = LOI->NumSignBits; 914 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 915 916 if (NumZeroBits == RegSize) { 917 // The current value is a zero. 918 // Explicitly express that as it would be easier for 919 // optimizations to kick in. 920 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 921 continue; 922 } 923 924 // FIXME: We capture more information than the dag can represent. For 925 // now, just use the tightest assertzext/assertsext possible. 926 bool isSExt; 927 EVT FromVT(MVT::Other); 928 if (NumZeroBits) { 929 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 930 isSExt = false; 931 } else if (NumSignBits > 1) { 932 FromVT = 933 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 934 isSExt = true; 935 } else { 936 continue; 937 } 938 // Add an assertion node. 939 assert(FromVT != MVT::Other); 940 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 941 RegisterVT, P, DAG.getValueType(FromVT)); 942 } 943 944 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 945 RegisterVT, ValueVT, V, Chain, CallConv); 946 Part += NumRegs; 947 Parts.clear(); 948 } 949 950 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 951 } 952 953 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 954 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 955 const Value *V, 956 ISD::NodeType PreferredExtendType) const { 957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 958 ISD::NodeType ExtendKind = PreferredExtendType; 959 960 // Get the list of the values's legal parts. 961 unsigned NumRegs = Regs.size(); 962 SmallVector<SDValue, 8> Parts(NumRegs); 963 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 964 unsigned NumParts = RegCount[Value]; 965 966 MVT RegisterVT = isABIMangled() 967 ? TLI.getRegisterTypeForCallingConv( 968 *DAG.getContext(), *CallConv, RegVTs[Value]) 969 : RegVTs[Value]; 970 971 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 972 ExtendKind = ISD::ZERO_EXTEND; 973 974 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 975 NumParts, RegisterVT, V, CallConv, ExtendKind); 976 Part += NumParts; 977 } 978 979 // Copy the parts into the registers. 980 SmallVector<SDValue, 8> Chains(NumRegs); 981 for (unsigned i = 0; i != NumRegs; ++i) { 982 SDValue Part; 983 if (!Glue) { 984 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 985 } else { 986 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 987 *Glue = Part.getValue(1); 988 } 989 990 Chains[i] = Part.getValue(0); 991 } 992 993 if (NumRegs == 1 || Glue) 994 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 995 // flagged to it. That is the CopyToReg nodes and the user are considered 996 // a single scheduling unit. If we create a TokenFactor and return it as 997 // chain, then the TokenFactor is both a predecessor (operand) of the 998 // user as well as a successor (the TF operands are flagged to the user). 999 // c1, f1 = CopyToReg 1000 // c2, f2 = CopyToReg 1001 // c3 = TokenFactor c1, c2 1002 // ... 1003 // = op c3, ..., f2 1004 Chain = Chains[NumRegs-1]; 1005 else 1006 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 1007 } 1008 1009 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 1010 unsigned MatchingIdx, const SDLoc &dl, 1011 SelectionDAG &DAG, 1012 std::vector<SDValue> &Ops) const { 1013 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1014 1015 InlineAsm::Flag Flag(Code, Regs.size()); 1016 if (HasMatching) 1017 Flag.setMatchingOp(MatchingIdx); 1018 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1019 // Put the register class of the virtual registers in the flag word. That 1020 // way, later passes can recompute register class constraints for inline 1021 // assembly as well as normal instructions. 1022 // Don't do this for tied operands that can use the regclass information 1023 // from the def. 1024 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1025 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1026 Flag.setRegClass(RC->getID()); 1027 } 1028 1029 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1030 Ops.push_back(Res); 1031 1032 if (Code == InlineAsm::Kind::Clobber) { 1033 // Clobbers should always have a 1:1 mapping with registers, and may 1034 // reference registers that have illegal (e.g. vector) types. Hence, we 1035 // shouldn't try to apply any sort of splitting logic to them. 1036 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1037 "No 1:1 mapping from clobbers to regs?"); 1038 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1039 (void)SP; 1040 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1041 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1042 assert( 1043 (Regs[I] != SP || 1044 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1045 "If we clobbered the stack pointer, MFI should know about it."); 1046 } 1047 return; 1048 } 1049 1050 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1051 MVT RegisterVT = RegVTs[Value]; 1052 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1053 RegisterVT); 1054 for (unsigned i = 0; i != NumRegs; ++i) { 1055 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1056 unsigned TheReg = Regs[Reg++]; 1057 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1058 } 1059 } 1060 } 1061 1062 SmallVector<std::pair<unsigned, TypeSize>, 4> 1063 RegsForValue::getRegsAndSizes() const { 1064 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1065 unsigned I = 0; 1066 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1067 unsigned RegCount = std::get<0>(CountAndVT); 1068 MVT RegisterVT = std::get<1>(CountAndVT); 1069 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1070 for (unsigned E = I + RegCount; I != E; ++I) 1071 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1072 } 1073 return OutVec; 1074 } 1075 1076 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1077 AssumptionCache *ac, 1078 const TargetLibraryInfo *li) { 1079 AA = aa; 1080 AC = ac; 1081 GFI = gfi; 1082 LibInfo = li; 1083 Context = DAG.getContext(); 1084 LPadToCallSiteMap.clear(); 1085 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1086 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1087 *DAG.getMachineFunction().getFunction().getParent()); 1088 } 1089 1090 void SelectionDAGBuilder::clear() { 1091 NodeMap.clear(); 1092 UnusedArgNodeMap.clear(); 1093 PendingLoads.clear(); 1094 PendingExports.clear(); 1095 PendingConstrainedFP.clear(); 1096 PendingConstrainedFPStrict.clear(); 1097 CurInst = nullptr; 1098 HasTailCall = false; 1099 SDNodeOrder = LowestSDNodeOrder; 1100 StatepointLowering.clear(); 1101 } 1102 1103 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1104 DanglingDebugInfoMap.clear(); 1105 } 1106 1107 // Update DAG root to include dependencies on Pending chains. 1108 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1109 SDValue Root = DAG.getRoot(); 1110 1111 if (Pending.empty()) 1112 return Root; 1113 1114 // Add current root to PendingChains, unless we already indirectly 1115 // depend on it. 1116 if (Root.getOpcode() != ISD::EntryToken) { 1117 unsigned i = 0, e = Pending.size(); 1118 for (; i != e; ++i) { 1119 assert(Pending[i].getNode()->getNumOperands() > 1); 1120 if (Pending[i].getNode()->getOperand(0) == Root) 1121 break; // Don't add the root if we already indirectly depend on it. 1122 } 1123 1124 if (i == e) 1125 Pending.push_back(Root); 1126 } 1127 1128 if (Pending.size() == 1) 1129 Root = Pending[0]; 1130 else 1131 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1132 1133 DAG.setRoot(Root); 1134 Pending.clear(); 1135 return Root; 1136 } 1137 1138 SDValue SelectionDAGBuilder::getMemoryRoot() { 1139 return updateRoot(PendingLoads); 1140 } 1141 1142 SDValue SelectionDAGBuilder::getRoot() { 1143 // Chain up all pending constrained intrinsics together with all 1144 // pending loads, by simply appending them to PendingLoads and 1145 // then calling getMemoryRoot(). 1146 PendingLoads.reserve(PendingLoads.size() + 1147 PendingConstrainedFP.size() + 1148 PendingConstrainedFPStrict.size()); 1149 PendingLoads.append(PendingConstrainedFP.begin(), 1150 PendingConstrainedFP.end()); 1151 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1152 PendingConstrainedFPStrict.end()); 1153 PendingConstrainedFP.clear(); 1154 PendingConstrainedFPStrict.clear(); 1155 return getMemoryRoot(); 1156 } 1157 1158 SDValue SelectionDAGBuilder::getControlRoot() { 1159 // We need to emit pending fpexcept.strict constrained intrinsics, 1160 // so append them to the PendingExports list. 1161 PendingExports.append(PendingConstrainedFPStrict.begin(), 1162 PendingConstrainedFPStrict.end()); 1163 PendingConstrainedFPStrict.clear(); 1164 return updateRoot(PendingExports); 1165 } 1166 1167 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1168 DILocalVariable *Variable, 1169 DIExpression *Expression, 1170 DebugLoc DL) { 1171 assert(Variable && "Missing variable"); 1172 1173 // Check if address has undef value. 1174 if (!Address || isa<UndefValue>(Address) || 1175 (Address->use_empty() && !isa<Argument>(Address))) { 1176 LLVM_DEBUG( 1177 dbgs() 1178 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1179 return; 1180 } 1181 1182 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1183 1184 SDValue &N = NodeMap[Address]; 1185 if (!N.getNode() && isa<Argument>(Address)) 1186 // Check unused arguments map. 1187 N = UnusedArgNodeMap[Address]; 1188 SDDbgValue *SDV; 1189 if (N.getNode()) { 1190 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1191 Address = BCI->getOperand(0); 1192 // Parameters are handled specially. 1193 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1194 if (IsParameter && FINode) { 1195 // Byval parameter. We have a frame index at this point. 1196 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1197 /*IsIndirect*/ true, DL, SDNodeOrder); 1198 } else if (isa<Argument>(Address)) { 1199 // Address is an argument, so try to emit its dbg value using 1200 // virtual register info from the FuncInfo.ValueMap. 1201 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1202 FuncArgumentDbgValueKind::Declare, N); 1203 return; 1204 } else { 1205 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1206 true, DL, SDNodeOrder); 1207 } 1208 DAG.AddDbgValue(SDV, IsParameter); 1209 } else { 1210 // If Address is an argument then try to emit its dbg value using 1211 // virtual register info from the FuncInfo.ValueMap. 1212 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1213 FuncArgumentDbgValueKind::Declare, N)) { 1214 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1215 << " (could not emit func-arg dbg_value)\n"); 1216 } 1217 } 1218 return; 1219 } 1220 1221 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1222 // Add SDDbgValue nodes for any var locs here. Do so before updating 1223 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1224 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1225 // Add SDDbgValue nodes for any var locs here. Do so before updating 1226 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1227 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1228 It != End; ++It) { 1229 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1230 dropDanglingDebugInfo(Var, It->Expr); 1231 if (It->Values.isKillLocation(It->Expr)) { 1232 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1233 continue; 1234 } 1235 SmallVector<Value *> Values(It->Values.location_ops()); 1236 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1237 It->Values.hasArgList())) { 1238 SmallVector<Value *, 4> Vals; 1239 for (Value *V : It->Values.location_ops()) 1240 Vals.push_back(V); 1241 addDanglingDebugInfo(Vals, 1242 FnVarLocs->getDILocalVariable(It->VariableID), 1243 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1244 } 1245 } 1246 } 1247 1248 // We must skip DbgVariableRecords if they've already been processed above as 1249 // we have just emitted the debug values resulting from assignment tracking 1250 // analysis, making any existing DbgVariableRecords redundant (and probably 1251 // less correct). We still need to process DbgLabelRecords. This does sink 1252 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't 1253 // be important as it does so deterministcally and ordering between 1254 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR 1255 // printing). 1256 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs(); 1257 // Is there is any debug-info attached to this instruction, in the form of 1258 // DbgRecord non-instruction debug-info records. 1259 for (DbgRecord &DR : I.getDbgRecordRange()) { 1260 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 1261 assert(DLR->getLabel() && "Missing label"); 1262 SDDbgLabel *SDV = 1263 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder); 1264 DAG.AddDbgLabel(SDV); 1265 continue; 1266 } 1267 1268 if (SkipDbgVariableRecords) 1269 continue; 1270 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 1271 DILocalVariable *Variable = DVR.getVariable(); 1272 DIExpression *Expression = DVR.getExpression(); 1273 dropDanglingDebugInfo(Variable, Expression); 1274 1275 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) { 1276 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR)) 1277 continue; 1278 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR 1279 << "\n"); 1280 handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression, 1281 DVR.getDebugLoc()); 1282 continue; 1283 } 1284 1285 // A DbgVariableRecord with no locations is a kill location. 1286 SmallVector<Value *, 4> Values(DVR.location_ops()); 1287 if (Values.empty()) { 1288 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1289 SDNodeOrder); 1290 continue; 1291 } 1292 1293 // A DbgVariableRecord with an undef or absent location is also a kill 1294 // location. 1295 if (llvm::any_of(Values, 1296 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1297 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1298 SDNodeOrder); 1299 continue; 1300 } 1301 1302 bool IsVariadic = DVR.hasArgList(); 1303 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(), 1304 SDNodeOrder, IsVariadic)) { 1305 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1306 DVR.getDebugLoc(), SDNodeOrder); 1307 } 1308 } 1309 } 1310 1311 void SelectionDAGBuilder::visit(const Instruction &I) { 1312 visitDbgInfo(I); 1313 1314 // Set up outgoing PHI node register values before emitting the terminator. 1315 if (I.isTerminator()) { 1316 HandlePHINodesInSuccessorBlocks(I.getParent()); 1317 } 1318 1319 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1320 if (!isa<DbgInfoIntrinsic>(I)) 1321 ++SDNodeOrder; 1322 1323 CurInst = &I; 1324 1325 // Set inserted listener only if required. 1326 bool NodeInserted = false; 1327 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1328 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1329 if (PCSectionsMD) { 1330 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1331 DAG, [&](SDNode *) { NodeInserted = true; }); 1332 } 1333 1334 visit(I.getOpcode(), I); 1335 1336 if (!I.isTerminator() && !HasTailCall && 1337 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1338 CopyToExportRegsIfNeeded(&I); 1339 1340 // Handle metadata. 1341 if (PCSectionsMD) { 1342 auto It = NodeMap.find(&I); 1343 if (It != NodeMap.end()) { 1344 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1345 } else if (NodeInserted) { 1346 // This should not happen; if it does, don't let it go unnoticed so we can 1347 // fix it. Relevant visit*() function is probably missing a setValue(). 1348 errs() << "warning: loosing !pcsections metadata [" 1349 << I.getModule()->getName() << "]\n"; 1350 LLVM_DEBUG(I.dump()); 1351 assert(false); 1352 } 1353 } 1354 1355 CurInst = nullptr; 1356 } 1357 1358 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1359 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1360 } 1361 1362 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1363 // Note: this doesn't use InstVisitor, because it has to work with 1364 // ConstantExpr's in addition to instructions. 1365 switch (Opcode) { 1366 default: llvm_unreachable("Unknown instruction type encountered!"); 1367 // Build the switch statement using the Instruction.def file. 1368 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1369 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1370 #include "llvm/IR/Instruction.def" 1371 } 1372 } 1373 1374 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1375 DILocalVariable *Variable, 1376 DebugLoc DL, unsigned Order, 1377 SmallVectorImpl<Value *> &Values, 1378 DIExpression *Expression) { 1379 // For variadic dbg_values we will now insert an undef. 1380 // FIXME: We can potentially recover these! 1381 SmallVector<SDDbgOperand, 2> Locs; 1382 for (const Value *V : Values) { 1383 auto *Undef = UndefValue::get(V->getType()); 1384 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1385 } 1386 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1387 /*IsIndirect=*/false, DL, Order, 1388 /*IsVariadic=*/true); 1389 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1390 return true; 1391 } 1392 1393 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1394 DILocalVariable *Var, 1395 DIExpression *Expr, 1396 bool IsVariadic, DebugLoc DL, 1397 unsigned Order) { 1398 if (IsVariadic) { 1399 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1400 return; 1401 } 1402 // TODO: Dangling debug info will eventually either be resolved or produce 1403 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1404 // between the original dbg.value location and its resolved DBG_VALUE, 1405 // which we should ideally fill with an extra Undef DBG_VALUE. 1406 assert(Values.size() == 1); 1407 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1408 } 1409 1410 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1411 const DIExpression *Expr) { 1412 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1413 DIVariable *DanglingVariable = DDI.getVariable(); 1414 DIExpression *DanglingExpr = DDI.getExpression(); 1415 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1416 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1417 << printDDI(nullptr, DDI) << "\n"); 1418 return true; 1419 } 1420 return false; 1421 }; 1422 1423 for (auto &DDIMI : DanglingDebugInfoMap) { 1424 DanglingDebugInfoVector &DDIV = DDIMI.second; 1425 1426 // If debug info is to be dropped, run it through final checks to see 1427 // whether it can be salvaged. 1428 for (auto &DDI : DDIV) 1429 if (isMatchingDbgValue(DDI)) 1430 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1431 1432 erase_if(DDIV, isMatchingDbgValue); 1433 } 1434 } 1435 1436 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1437 // generate the debug data structures now that we've seen its definition. 1438 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1439 SDValue Val) { 1440 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1441 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1442 return; 1443 1444 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1445 for (auto &DDI : DDIV) { 1446 DebugLoc DL = DDI.getDebugLoc(); 1447 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1448 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1449 DILocalVariable *Variable = DDI.getVariable(); 1450 DIExpression *Expr = DDI.getExpression(); 1451 assert(Variable->isValidLocationForIntrinsic(DL) && 1452 "Expected inlined-at fields to agree"); 1453 SDDbgValue *SDV; 1454 if (Val.getNode()) { 1455 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1456 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1457 // we couldn't resolve it directly when examining the DbgValue intrinsic 1458 // in the first place we should not be more successful here). Unless we 1459 // have some test case that prove this to be correct we should avoid 1460 // calling EmitFuncArgumentDbgValue here. 1461 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1462 FuncArgumentDbgValueKind::Value, Val)) { 1463 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1464 << printDDI(V, DDI) << "\n"); 1465 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1466 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1467 // inserted after the definition of Val when emitting the instructions 1468 // after ISel. An alternative could be to teach 1469 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1470 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1471 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1472 << ValSDNodeOrder << "\n"); 1473 SDV = getDbgValue(Val, Variable, Expr, DL, 1474 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1475 DAG.AddDbgValue(SDV, false); 1476 } else 1477 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1478 << printDDI(V, DDI) 1479 << " in EmitFuncArgumentDbgValue\n"); 1480 } else { 1481 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1482 << "\n"); 1483 auto Undef = UndefValue::get(V->getType()); 1484 auto SDV = 1485 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1486 DAG.AddDbgValue(SDV, false); 1487 } 1488 } 1489 DDIV.clear(); 1490 } 1491 1492 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1493 DanglingDebugInfo &DDI) { 1494 // TODO: For the variadic implementation, instead of only checking the fail 1495 // state of `handleDebugValue`, we need know specifically which values were 1496 // invalid, so that we attempt to salvage only those values when processing 1497 // a DIArgList. 1498 const Value *OrigV = V; 1499 DILocalVariable *Var = DDI.getVariable(); 1500 DIExpression *Expr = DDI.getExpression(); 1501 DebugLoc DL = DDI.getDebugLoc(); 1502 unsigned SDOrder = DDI.getSDNodeOrder(); 1503 1504 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1505 // that DW_OP_stack_value is desired. 1506 bool StackValue = true; 1507 1508 // Can this Value can be encoded without any further work? 1509 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1510 return; 1511 1512 // Attempt to salvage back through as many instructions as possible. Bail if 1513 // a non-instruction is seen, such as a constant expression or global 1514 // variable. FIXME: Further work could recover those too. 1515 while (isa<Instruction>(V)) { 1516 const Instruction &VAsInst = *cast<const Instruction>(V); 1517 // Temporary "0", awaiting real implementation. 1518 SmallVector<uint64_t, 16> Ops; 1519 SmallVector<Value *, 4> AdditionalValues; 1520 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1521 Expr->getNumLocationOperands(), Ops, 1522 AdditionalValues); 1523 // If we cannot salvage any further, and haven't yet found a suitable debug 1524 // expression, bail out. 1525 if (!V) 1526 break; 1527 1528 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1529 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1530 // here for variadic dbg_values, remove that condition. 1531 if (!AdditionalValues.empty()) 1532 break; 1533 1534 // New value and expr now represent this debuginfo. 1535 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1536 1537 // Some kind of simplification occurred: check whether the operand of the 1538 // salvaged debug expression can be encoded in this DAG. 1539 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1540 LLVM_DEBUG( 1541 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1542 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1543 return; 1544 } 1545 } 1546 1547 // This was the final opportunity to salvage this debug information, and it 1548 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1549 // any earlier variable location. 1550 assert(OrigV && "V shouldn't be null"); 1551 auto *Undef = UndefValue::get(OrigV->getType()); 1552 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1553 DAG.AddDbgValue(SDV, false); 1554 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1555 << printDDI(OrigV, DDI) << "\n"); 1556 } 1557 1558 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1559 DIExpression *Expr, 1560 DebugLoc DbgLoc, 1561 unsigned Order) { 1562 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1563 DIExpression *NewExpr = 1564 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1565 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1566 /*IsVariadic*/ false); 1567 } 1568 1569 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1570 DILocalVariable *Var, 1571 DIExpression *Expr, DebugLoc DbgLoc, 1572 unsigned Order, bool IsVariadic) { 1573 if (Values.empty()) 1574 return true; 1575 1576 // Filter EntryValue locations out early. 1577 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1578 return true; 1579 1580 SmallVector<SDDbgOperand> LocationOps; 1581 SmallVector<SDNode *> Dependencies; 1582 for (const Value *V : Values) { 1583 // Constant value. 1584 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1585 isa<ConstantPointerNull>(V)) { 1586 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1587 continue; 1588 } 1589 1590 // Look through IntToPtr constants. 1591 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1592 if (CE->getOpcode() == Instruction::IntToPtr) { 1593 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1594 continue; 1595 } 1596 1597 // If the Value is a frame index, we can create a FrameIndex debug value 1598 // without relying on the DAG at all. 1599 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1600 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1601 if (SI != FuncInfo.StaticAllocaMap.end()) { 1602 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1603 continue; 1604 } 1605 } 1606 1607 // Do not use getValue() in here; we don't want to generate code at 1608 // this point if it hasn't been done yet. 1609 SDValue N = NodeMap[V]; 1610 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1611 N = UnusedArgNodeMap[V]; 1612 if (N.getNode()) { 1613 // Only emit func arg dbg value for non-variadic dbg.values for now. 1614 if (!IsVariadic && 1615 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1616 FuncArgumentDbgValueKind::Value, N)) 1617 return true; 1618 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1619 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1620 // describe stack slot locations. 1621 // 1622 // Consider "int x = 0; int *px = &x;". There are two kinds of 1623 // interesting debug values here after optimization: 1624 // 1625 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1626 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1627 // 1628 // Both describe the direct values of their associated variables. 1629 Dependencies.push_back(N.getNode()); 1630 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1631 continue; 1632 } 1633 LocationOps.emplace_back( 1634 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1635 continue; 1636 } 1637 1638 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1639 // Special rules apply for the first dbg.values of parameter variables in a 1640 // function. Identify them by the fact they reference Argument Values, that 1641 // they're parameters, and they are parameters of the current function. We 1642 // need to let them dangle until they get an SDNode. 1643 bool IsParamOfFunc = 1644 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1645 if (IsParamOfFunc) 1646 return false; 1647 1648 // The value is not used in this block yet (or it would have an SDNode). 1649 // We still want the value to appear for the user if possible -- if it has 1650 // an associated VReg, we can refer to that instead. 1651 auto VMI = FuncInfo.ValueMap.find(V); 1652 if (VMI != FuncInfo.ValueMap.end()) { 1653 unsigned Reg = VMI->second; 1654 // If this is a PHI node, it may be split up into several MI PHI nodes 1655 // (in FunctionLoweringInfo::set). 1656 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1657 V->getType(), std::nullopt); 1658 if (RFV.occupiesMultipleRegs()) { 1659 // FIXME: We could potentially support variadic dbg_values here. 1660 if (IsVariadic) 1661 return false; 1662 unsigned Offset = 0; 1663 unsigned BitsToDescribe = 0; 1664 if (auto VarSize = Var->getSizeInBits()) 1665 BitsToDescribe = *VarSize; 1666 if (auto Fragment = Expr->getFragmentInfo()) 1667 BitsToDescribe = Fragment->SizeInBits; 1668 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1669 // Bail out if all bits are described already. 1670 if (Offset >= BitsToDescribe) 1671 break; 1672 // TODO: handle scalable vectors. 1673 unsigned RegisterSize = RegAndSize.second; 1674 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1675 ? BitsToDescribe - Offset 1676 : RegisterSize; 1677 auto FragmentExpr = DIExpression::createFragmentExpression( 1678 Expr, Offset, FragmentSize); 1679 if (!FragmentExpr) 1680 continue; 1681 SDDbgValue *SDV = DAG.getVRegDbgValue( 1682 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1683 DAG.AddDbgValue(SDV, false); 1684 Offset += RegisterSize; 1685 } 1686 return true; 1687 } 1688 // We can use simple vreg locations for variadic dbg_values as well. 1689 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1690 continue; 1691 } 1692 // We failed to create a SDDbgOperand for V. 1693 return false; 1694 } 1695 1696 // We have created a SDDbgOperand for each Value in Values. 1697 // Should use Order instead of SDNodeOrder? 1698 assert(!LocationOps.empty()); 1699 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1700 /*IsIndirect=*/false, DbgLoc, 1701 SDNodeOrder, IsVariadic); 1702 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1703 return true; 1704 } 1705 1706 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1707 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1708 for (auto &Pair : DanglingDebugInfoMap) 1709 for (auto &DDI : Pair.second) 1710 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1711 clearDanglingDebugInfo(); 1712 } 1713 1714 /// getCopyFromRegs - If there was virtual register allocated for the value V 1715 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1716 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1717 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1718 SDValue Result; 1719 1720 if (It != FuncInfo.ValueMap.end()) { 1721 Register InReg = It->second; 1722 1723 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1724 DAG.getDataLayout(), InReg, Ty, 1725 std::nullopt); // This is not an ABI copy. 1726 SDValue Chain = DAG.getEntryNode(); 1727 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1728 V); 1729 resolveDanglingDebugInfo(V, Result); 1730 } 1731 1732 return Result; 1733 } 1734 1735 /// getValue - Return an SDValue for the given Value. 1736 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1737 // If we already have an SDValue for this value, use it. It's important 1738 // to do this first, so that we don't create a CopyFromReg if we already 1739 // have a regular SDValue. 1740 SDValue &N = NodeMap[V]; 1741 if (N.getNode()) return N; 1742 1743 // If there's a virtual register allocated and initialized for this 1744 // value, use it. 1745 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1746 return copyFromReg; 1747 1748 // Otherwise create a new SDValue and remember it. 1749 SDValue Val = getValueImpl(V); 1750 NodeMap[V] = Val; 1751 resolveDanglingDebugInfo(V, Val); 1752 return Val; 1753 } 1754 1755 /// getNonRegisterValue - Return an SDValue for the given Value, but 1756 /// don't look in FuncInfo.ValueMap for a virtual register. 1757 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1758 // If we already have an SDValue for this value, use it. 1759 SDValue &N = NodeMap[V]; 1760 if (N.getNode()) { 1761 if (isIntOrFPConstant(N)) { 1762 // Remove the debug location from the node as the node is about to be used 1763 // in a location which may differ from the original debug location. This 1764 // is relevant to Constant and ConstantFP nodes because they can appear 1765 // as constant expressions inside PHI nodes. 1766 N->setDebugLoc(DebugLoc()); 1767 } 1768 return N; 1769 } 1770 1771 // Otherwise create a new SDValue and remember it. 1772 SDValue Val = getValueImpl(V); 1773 NodeMap[V] = Val; 1774 resolveDanglingDebugInfo(V, Val); 1775 return Val; 1776 } 1777 1778 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1779 /// Create an SDValue for the given value. 1780 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1781 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1782 1783 if (const Constant *C = dyn_cast<Constant>(V)) { 1784 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1785 1786 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1787 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1788 1789 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1790 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1791 1792 if (isa<ConstantPointerNull>(C)) { 1793 unsigned AS = V->getType()->getPointerAddressSpace(); 1794 return DAG.getConstant(0, getCurSDLoc(), 1795 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1796 } 1797 1798 if (match(C, m_VScale())) 1799 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1800 1801 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1802 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1803 1804 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1805 return DAG.getUNDEF(VT); 1806 1807 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1808 visit(CE->getOpcode(), *CE); 1809 SDValue N1 = NodeMap[V]; 1810 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1811 return N1; 1812 } 1813 1814 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1815 SmallVector<SDValue, 4> Constants; 1816 for (const Use &U : C->operands()) { 1817 SDNode *Val = getValue(U).getNode(); 1818 // If the operand is an empty aggregate, there are no values. 1819 if (!Val) continue; 1820 // Add each leaf value from the operand to the Constants list 1821 // to form a flattened list of all the values. 1822 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1823 Constants.push_back(SDValue(Val, i)); 1824 } 1825 1826 return DAG.getMergeValues(Constants, getCurSDLoc()); 1827 } 1828 1829 if (const ConstantDataSequential *CDS = 1830 dyn_cast<ConstantDataSequential>(C)) { 1831 SmallVector<SDValue, 4> Ops; 1832 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1833 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1834 // Add each leaf value from the operand to the Constants list 1835 // to form a flattened list of all the values. 1836 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1837 Ops.push_back(SDValue(Val, i)); 1838 } 1839 1840 if (isa<ArrayType>(CDS->getType())) 1841 return DAG.getMergeValues(Ops, getCurSDLoc()); 1842 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1843 } 1844 1845 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1846 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1847 "Unknown struct or array constant!"); 1848 1849 SmallVector<EVT, 4> ValueVTs; 1850 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1851 unsigned NumElts = ValueVTs.size(); 1852 if (NumElts == 0) 1853 return SDValue(); // empty struct 1854 SmallVector<SDValue, 4> Constants(NumElts); 1855 for (unsigned i = 0; i != NumElts; ++i) { 1856 EVT EltVT = ValueVTs[i]; 1857 if (isa<UndefValue>(C)) 1858 Constants[i] = DAG.getUNDEF(EltVT); 1859 else if (EltVT.isFloatingPoint()) 1860 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1861 else 1862 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1863 } 1864 1865 return DAG.getMergeValues(Constants, getCurSDLoc()); 1866 } 1867 1868 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1869 return DAG.getBlockAddress(BA, VT); 1870 1871 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1872 return getValue(Equiv->getGlobalValue()); 1873 1874 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1875 return getValue(NC->getGlobalValue()); 1876 1877 if (VT == MVT::aarch64svcount) { 1878 assert(C->isNullValue() && "Can only zero this target type!"); 1879 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1880 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1881 } 1882 1883 VectorType *VecTy = cast<VectorType>(V->getType()); 1884 1885 // Now that we know the number and type of the elements, get that number of 1886 // elements into the Ops array based on what kind of constant it is. 1887 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1888 SmallVector<SDValue, 16> Ops; 1889 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1890 for (unsigned i = 0; i != NumElements; ++i) 1891 Ops.push_back(getValue(CV->getOperand(i))); 1892 1893 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1894 } 1895 1896 if (isa<ConstantAggregateZero>(C)) { 1897 EVT EltVT = 1898 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1899 1900 SDValue Op; 1901 if (EltVT.isFloatingPoint()) 1902 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1903 else 1904 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1905 1906 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1907 } 1908 1909 llvm_unreachable("Unknown vector constant"); 1910 } 1911 1912 // If this is a static alloca, generate it as the frameindex instead of 1913 // computation. 1914 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1915 DenseMap<const AllocaInst*, int>::iterator SI = 1916 FuncInfo.StaticAllocaMap.find(AI); 1917 if (SI != FuncInfo.StaticAllocaMap.end()) 1918 return DAG.getFrameIndex( 1919 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1920 } 1921 1922 // If this is an instruction which fast-isel has deferred, select it now. 1923 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1924 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1925 1926 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1927 Inst->getType(), std::nullopt); 1928 SDValue Chain = DAG.getEntryNode(); 1929 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1930 } 1931 1932 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1933 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1934 1935 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1936 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1937 1938 llvm_unreachable("Can't get register for value!"); 1939 } 1940 1941 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1942 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1943 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1944 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1945 bool IsSEH = isAsynchronousEHPersonality(Pers); 1946 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1947 if (!IsSEH) 1948 CatchPadMBB->setIsEHScopeEntry(); 1949 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1950 if (IsMSVCCXX || IsCoreCLR) 1951 CatchPadMBB->setIsEHFuncletEntry(); 1952 } 1953 1954 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1955 // Update machine-CFG edge. 1956 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1957 FuncInfo.MBB->addSuccessor(TargetMBB); 1958 TargetMBB->setIsEHCatchretTarget(true); 1959 DAG.getMachineFunction().setHasEHCatchret(true); 1960 1961 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1962 bool IsSEH = isAsynchronousEHPersonality(Pers); 1963 if (IsSEH) { 1964 // If this is not a fall-through branch or optimizations are switched off, 1965 // emit the branch. 1966 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1967 TM.getOptLevel() == CodeGenOptLevel::None) 1968 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1969 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1970 return; 1971 } 1972 1973 // Figure out the funclet membership for the catchret's successor. 1974 // This will be used by the FuncletLayout pass to determine how to order the 1975 // BB's. 1976 // A 'catchret' returns to the outer scope's color. 1977 Value *ParentPad = I.getCatchSwitchParentPad(); 1978 const BasicBlock *SuccessorColor; 1979 if (isa<ConstantTokenNone>(ParentPad)) 1980 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1981 else 1982 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1983 assert(SuccessorColor && "No parent funclet for catchret!"); 1984 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1985 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1986 1987 // Create the terminator node. 1988 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1989 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1990 DAG.getBasicBlock(SuccessorColorMBB)); 1991 DAG.setRoot(Ret); 1992 } 1993 1994 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1995 // Don't emit any special code for the cleanuppad instruction. It just marks 1996 // the start of an EH scope/funclet. 1997 FuncInfo.MBB->setIsEHScopeEntry(); 1998 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1999 if (Pers != EHPersonality::Wasm_CXX) { 2000 FuncInfo.MBB->setIsEHFuncletEntry(); 2001 FuncInfo.MBB->setIsCleanupFuncletEntry(); 2002 } 2003 } 2004 2005 // In wasm EH, even though a catchpad may not catch an exception if a tag does 2006 // not match, it is OK to add only the first unwind destination catchpad to the 2007 // successors, because there will be at least one invoke instruction within the 2008 // catch scope that points to the next unwind destination, if one exists, so 2009 // CFGSort cannot mess up with BB sorting order. 2010 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 2011 // call within them, and catchpads only consisting of 'catch (...)' have a 2012 // '__cxa_end_catch' call within them, both of which generate invokes in case 2013 // the next unwind destination exists, i.e., the next unwind destination is not 2014 // the caller.) 2015 // 2016 // Having at most one EH pad successor is also simpler and helps later 2017 // transformations. 2018 // 2019 // For example, 2020 // current: 2021 // invoke void @foo to ... unwind label %catch.dispatch 2022 // catch.dispatch: 2023 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2024 // catch.start: 2025 // ... 2026 // ... in this BB or some other child BB dominated by this BB there will be an 2027 // invoke that points to 'next' BB as an unwind destination 2028 // 2029 // next: ; We don't need to add this to 'current' BB's successor 2030 // ... 2031 static void findWasmUnwindDestinations( 2032 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2033 BranchProbability Prob, 2034 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2035 &UnwindDests) { 2036 while (EHPadBB) { 2037 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2038 if (isa<CleanupPadInst>(Pad)) { 2039 // Stop on cleanup pads. 2040 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2041 UnwindDests.back().first->setIsEHScopeEntry(); 2042 break; 2043 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2044 // Add the catchpad handlers to the possible destinations. We don't 2045 // continue to the unwind destination of the catchswitch for wasm. 2046 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2047 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2048 UnwindDests.back().first->setIsEHScopeEntry(); 2049 } 2050 break; 2051 } else { 2052 continue; 2053 } 2054 } 2055 } 2056 2057 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2058 /// many places it could ultimately go. In the IR, we have a single unwind 2059 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2060 /// This function skips over imaginary basic blocks that hold catchswitch 2061 /// instructions, and finds all the "real" machine 2062 /// basic block destinations. As those destinations may not be successors of 2063 /// EHPadBB, here we also calculate the edge probability to those destinations. 2064 /// The passed-in Prob is the edge probability to EHPadBB. 2065 static void findUnwindDestinations( 2066 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2067 BranchProbability Prob, 2068 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2069 &UnwindDests) { 2070 EHPersonality Personality = 2071 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2072 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2073 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2074 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2075 bool IsSEH = isAsynchronousEHPersonality(Personality); 2076 2077 if (IsWasmCXX) { 2078 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2079 assert(UnwindDests.size() <= 1 && 2080 "There should be at most one unwind destination for wasm"); 2081 return; 2082 } 2083 2084 while (EHPadBB) { 2085 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2086 BasicBlock *NewEHPadBB = nullptr; 2087 if (isa<LandingPadInst>(Pad)) { 2088 // Stop on landingpads. They are not funclets. 2089 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2090 break; 2091 } else if (isa<CleanupPadInst>(Pad)) { 2092 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2093 // personalities. 2094 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2095 UnwindDests.back().first->setIsEHScopeEntry(); 2096 UnwindDests.back().first->setIsEHFuncletEntry(); 2097 break; 2098 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2099 // Add the catchpad handlers to the possible destinations. 2100 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2101 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2102 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2103 if (IsMSVCCXX || IsCoreCLR) 2104 UnwindDests.back().first->setIsEHFuncletEntry(); 2105 if (!IsSEH) 2106 UnwindDests.back().first->setIsEHScopeEntry(); 2107 } 2108 NewEHPadBB = CatchSwitch->getUnwindDest(); 2109 } else { 2110 continue; 2111 } 2112 2113 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2114 if (BPI && NewEHPadBB) 2115 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2116 EHPadBB = NewEHPadBB; 2117 } 2118 } 2119 2120 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2121 // Update successor info. 2122 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2123 auto UnwindDest = I.getUnwindDest(); 2124 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2125 BranchProbability UnwindDestProb = 2126 (BPI && UnwindDest) 2127 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2128 : BranchProbability::getZero(); 2129 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2130 for (auto &UnwindDest : UnwindDests) { 2131 UnwindDest.first->setIsEHPad(); 2132 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2133 } 2134 FuncInfo.MBB->normalizeSuccProbs(); 2135 2136 // Create the terminator node. 2137 SDValue Ret = 2138 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2139 DAG.setRoot(Ret); 2140 } 2141 2142 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2143 report_fatal_error("visitCatchSwitch not yet implemented!"); 2144 } 2145 2146 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2147 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2148 auto &DL = DAG.getDataLayout(); 2149 SDValue Chain = getControlRoot(); 2150 SmallVector<ISD::OutputArg, 8> Outs; 2151 SmallVector<SDValue, 8> OutVals; 2152 2153 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2154 // lower 2155 // 2156 // %val = call <ty> @llvm.experimental.deoptimize() 2157 // ret <ty> %val 2158 // 2159 // differently. 2160 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2161 LowerDeoptimizingReturn(); 2162 return; 2163 } 2164 2165 if (!FuncInfo.CanLowerReturn) { 2166 unsigned DemoteReg = FuncInfo.DemoteRegister; 2167 const Function *F = I.getParent()->getParent(); 2168 2169 // Emit a store of the return value through the virtual register. 2170 // Leave Outs empty so that LowerReturn won't try to load return 2171 // registers the usual way. 2172 SmallVector<EVT, 1> PtrValueVTs; 2173 ComputeValueVTs(TLI, DL, 2174 PointerType::get(F->getContext(), 2175 DAG.getDataLayout().getAllocaAddrSpace()), 2176 PtrValueVTs); 2177 2178 SDValue RetPtr = 2179 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2180 SDValue RetOp = getValue(I.getOperand(0)); 2181 2182 SmallVector<EVT, 4> ValueVTs, MemVTs; 2183 SmallVector<uint64_t, 4> Offsets; 2184 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2185 &Offsets, 0); 2186 unsigned NumValues = ValueVTs.size(); 2187 2188 SmallVector<SDValue, 4> Chains(NumValues); 2189 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2190 for (unsigned i = 0; i != NumValues; ++i) { 2191 // An aggregate return value cannot wrap around the address space, so 2192 // offsets to its parts don't wrap either. 2193 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2194 TypeSize::getFixed(Offsets[i])); 2195 2196 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2197 if (MemVTs[i] != ValueVTs[i]) 2198 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2199 Chains[i] = DAG.getStore( 2200 Chain, getCurSDLoc(), Val, 2201 // FIXME: better loc info would be nice. 2202 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2203 commonAlignment(BaseAlign, Offsets[i])); 2204 } 2205 2206 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2207 MVT::Other, Chains); 2208 } else if (I.getNumOperands() != 0) { 2209 SmallVector<EVT, 4> ValueVTs; 2210 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2211 unsigned NumValues = ValueVTs.size(); 2212 if (NumValues) { 2213 SDValue RetOp = getValue(I.getOperand(0)); 2214 2215 const Function *F = I.getParent()->getParent(); 2216 2217 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2218 I.getOperand(0)->getType(), F->getCallingConv(), 2219 /*IsVarArg*/ false, DL); 2220 2221 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2222 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2223 ExtendKind = ISD::SIGN_EXTEND; 2224 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2225 ExtendKind = ISD::ZERO_EXTEND; 2226 2227 LLVMContext &Context = F->getContext(); 2228 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2229 2230 for (unsigned j = 0; j != NumValues; ++j) { 2231 EVT VT = ValueVTs[j]; 2232 2233 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2234 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2235 2236 CallingConv::ID CC = F->getCallingConv(); 2237 2238 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2239 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2240 SmallVector<SDValue, 4> Parts(NumParts); 2241 getCopyToParts(DAG, getCurSDLoc(), 2242 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2243 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2244 2245 // 'inreg' on function refers to return value 2246 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2247 if (RetInReg) 2248 Flags.setInReg(); 2249 2250 if (I.getOperand(0)->getType()->isPointerTy()) { 2251 Flags.setPointer(); 2252 Flags.setPointerAddrSpace( 2253 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2254 } 2255 2256 if (NeedsRegBlock) { 2257 Flags.setInConsecutiveRegs(); 2258 if (j == NumValues - 1) 2259 Flags.setInConsecutiveRegsLast(); 2260 } 2261 2262 // Propagate extension type if any 2263 if (ExtendKind == ISD::SIGN_EXTEND) 2264 Flags.setSExt(); 2265 else if (ExtendKind == ISD::ZERO_EXTEND) 2266 Flags.setZExt(); 2267 2268 for (unsigned i = 0; i < NumParts; ++i) { 2269 Outs.push_back(ISD::OutputArg(Flags, 2270 Parts[i].getValueType().getSimpleVT(), 2271 VT, /*isfixed=*/true, 0, 0)); 2272 OutVals.push_back(Parts[i]); 2273 } 2274 } 2275 } 2276 } 2277 2278 // Push in swifterror virtual register as the last element of Outs. This makes 2279 // sure swifterror virtual register will be returned in the swifterror 2280 // physical register. 2281 const Function *F = I.getParent()->getParent(); 2282 if (TLI.supportSwiftError() && 2283 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2284 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2285 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2286 Flags.setSwiftError(); 2287 Outs.push_back(ISD::OutputArg( 2288 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2289 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2290 // Create SDNode for the swifterror virtual register. 2291 OutVals.push_back( 2292 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2293 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2294 EVT(TLI.getPointerTy(DL)))); 2295 } 2296 2297 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2298 CallingConv::ID CallConv = 2299 DAG.getMachineFunction().getFunction().getCallingConv(); 2300 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2301 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2302 2303 // Verify that the target's LowerReturn behaved as expected. 2304 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2305 "LowerReturn didn't return a valid chain!"); 2306 2307 // Update the DAG with the new chain value resulting from return lowering. 2308 DAG.setRoot(Chain); 2309 } 2310 2311 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2312 /// created for it, emit nodes to copy the value into the virtual 2313 /// registers. 2314 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2315 // Skip empty types 2316 if (V->getType()->isEmptyTy()) 2317 return; 2318 2319 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2320 if (VMI != FuncInfo.ValueMap.end()) { 2321 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2322 "Unused value assigned virtual registers!"); 2323 CopyValueToVirtualRegister(V, VMI->second); 2324 } 2325 } 2326 2327 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2328 /// the current basic block, add it to ValueMap now so that we'll get a 2329 /// CopyTo/FromReg. 2330 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2331 // No need to export constants. 2332 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2333 2334 // Already exported? 2335 if (FuncInfo.isExportedInst(V)) return; 2336 2337 Register Reg = FuncInfo.InitializeRegForValue(V); 2338 CopyValueToVirtualRegister(V, Reg); 2339 } 2340 2341 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2342 const BasicBlock *FromBB) { 2343 // The operands of the setcc have to be in this block. We don't know 2344 // how to export them from some other block. 2345 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2346 // Can export from current BB. 2347 if (VI->getParent() == FromBB) 2348 return true; 2349 2350 // Is already exported, noop. 2351 return FuncInfo.isExportedInst(V); 2352 } 2353 2354 // If this is an argument, we can export it if the BB is the entry block or 2355 // if it is already exported. 2356 if (isa<Argument>(V)) { 2357 if (FromBB->isEntryBlock()) 2358 return true; 2359 2360 // Otherwise, can only export this if it is already exported. 2361 return FuncInfo.isExportedInst(V); 2362 } 2363 2364 // Otherwise, constants can always be exported. 2365 return true; 2366 } 2367 2368 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2369 BranchProbability 2370 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2371 const MachineBasicBlock *Dst) const { 2372 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2373 const BasicBlock *SrcBB = Src->getBasicBlock(); 2374 const BasicBlock *DstBB = Dst->getBasicBlock(); 2375 if (!BPI) { 2376 // If BPI is not available, set the default probability as 1 / N, where N is 2377 // the number of successors. 2378 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2379 return BranchProbability(1, SuccSize); 2380 } 2381 return BPI->getEdgeProbability(SrcBB, DstBB); 2382 } 2383 2384 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2385 MachineBasicBlock *Dst, 2386 BranchProbability Prob) { 2387 if (!FuncInfo.BPI) 2388 Src->addSuccessorWithoutProb(Dst); 2389 else { 2390 if (Prob.isUnknown()) 2391 Prob = getEdgeProbability(Src, Dst); 2392 Src->addSuccessor(Dst, Prob); 2393 } 2394 } 2395 2396 static bool InBlock(const Value *V, const BasicBlock *BB) { 2397 if (const Instruction *I = dyn_cast<Instruction>(V)) 2398 return I->getParent() == BB; 2399 return true; 2400 } 2401 2402 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2403 /// This function emits a branch and is used at the leaves of an OR or an 2404 /// AND operator tree. 2405 void 2406 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2407 MachineBasicBlock *TBB, 2408 MachineBasicBlock *FBB, 2409 MachineBasicBlock *CurBB, 2410 MachineBasicBlock *SwitchBB, 2411 BranchProbability TProb, 2412 BranchProbability FProb, 2413 bool InvertCond) { 2414 const BasicBlock *BB = CurBB->getBasicBlock(); 2415 2416 // If the leaf of the tree is a comparison, merge the condition into 2417 // the caseblock. 2418 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2419 // The operands of the cmp have to be in this block. We don't know 2420 // how to export them from some other block. If this is the first block 2421 // of the sequence, no exporting is needed. 2422 if (CurBB == SwitchBB || 2423 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2424 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2425 ISD::CondCode Condition; 2426 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2427 ICmpInst::Predicate Pred = 2428 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2429 Condition = getICmpCondCode(Pred); 2430 } else { 2431 const FCmpInst *FC = cast<FCmpInst>(Cond); 2432 FCmpInst::Predicate Pred = 2433 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2434 Condition = getFCmpCondCode(Pred); 2435 if (TM.Options.NoNaNsFPMath) 2436 Condition = getFCmpCodeWithoutNaN(Condition); 2437 } 2438 2439 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2440 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2441 SL->SwitchCases.push_back(CB); 2442 return; 2443 } 2444 } 2445 2446 // Create a CaseBlock record representing this branch. 2447 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2448 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2449 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2450 SL->SwitchCases.push_back(CB); 2451 } 2452 2453 // Collect dependencies on V recursively. This is used for the cost analysis in 2454 // `shouldKeepJumpConditionsTogether`. 2455 static bool collectInstructionDeps( 2456 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V, 2457 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr, 2458 unsigned Depth = 0) { 2459 // Return false if we have an incomplete count. 2460 if (Depth >= SelectionDAG::MaxRecursionDepth) 2461 return false; 2462 2463 auto *I = dyn_cast<Instruction>(V); 2464 if (I == nullptr) 2465 return true; 2466 2467 if (Necessary != nullptr) { 2468 // This instruction is necessary for the other side of the condition so 2469 // don't count it. 2470 if (Necessary->contains(I)) 2471 return true; 2472 } 2473 2474 // Already added this dep. 2475 if (!Deps->try_emplace(I, false).second) 2476 return true; 2477 2478 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx) 2479 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary, 2480 Depth + 1)) 2481 return false; 2482 return true; 2483 } 2484 2485 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether( 2486 const FunctionLoweringInfo &FuncInfo, const BranchInst &I, 2487 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, 2488 TargetLoweringBase::CondMergingParams Params) const { 2489 if (I.getNumSuccessors() != 2) 2490 return false; 2491 2492 if (!I.isConditional()) 2493 return false; 2494 2495 if (Params.BaseCost < 0) 2496 return false; 2497 2498 // Baseline cost. 2499 InstructionCost CostThresh = Params.BaseCost; 2500 2501 BranchProbabilityInfo *BPI = nullptr; 2502 if (Params.LikelyBias || Params.UnlikelyBias) 2503 BPI = FuncInfo.BPI; 2504 if (BPI != nullptr) { 2505 // See if we are either likely to get an early out or compute both lhs/rhs 2506 // of the condition. 2507 BasicBlock *IfFalse = I.getSuccessor(0); 2508 BasicBlock *IfTrue = I.getSuccessor(1); 2509 2510 std::optional<bool> Likely; 2511 if (BPI->isEdgeHot(I.getParent(), IfTrue)) 2512 Likely = true; 2513 else if (BPI->isEdgeHot(I.getParent(), IfFalse)) 2514 Likely = false; 2515 2516 if (Likely) { 2517 if (Opc == (*Likely ? Instruction::And : Instruction::Or)) 2518 // Its likely we will have to compute both lhs and rhs of condition 2519 CostThresh += Params.LikelyBias; 2520 else { 2521 if (Params.UnlikelyBias < 0) 2522 return false; 2523 // Its likely we will get an early out. 2524 CostThresh -= Params.UnlikelyBias; 2525 } 2526 } 2527 } 2528 2529 if (CostThresh <= 0) 2530 return false; 2531 2532 // Collect "all" instructions that lhs condition is dependent on. 2533 // Use map for stable iteration (to avoid non-determanism of iteration of 2534 // SmallPtrSet). The `bool` value is just a dummy. 2535 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps; 2536 collectInstructionDeps(&LhsDeps, Lhs); 2537 // Collect "all" instructions that rhs condition is dependent on AND are 2538 // dependencies of lhs. This gives us an estimate on which instructions we 2539 // stand to save by splitting the condition. 2540 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps)) 2541 return false; 2542 // Add the compare instruction itself unless its a dependency on the LHS. 2543 if (const auto *RhsI = dyn_cast<Instruction>(Rhs)) 2544 if (!LhsDeps.contains(RhsI)) 2545 RhsDeps.try_emplace(RhsI, false); 2546 2547 const auto &TLI = DAG.getTargetLoweringInfo(); 2548 const auto &TTI = 2549 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 2550 2551 InstructionCost CostOfIncluding = 0; 2552 // See if this instruction will need to computed independently of whether RHS 2553 // is. 2554 Value *BrCond = I.getCondition(); 2555 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) { 2556 for (const auto *U : Ins->users()) { 2557 // If user is independent of RHS calculation we don't need to count it. 2558 if (auto *UIns = dyn_cast<Instruction>(U)) 2559 if (UIns != BrCond && !RhsDeps.contains(UIns)) 2560 return false; 2561 } 2562 return true; 2563 }; 2564 2565 // Prune instructions from RHS Deps that are dependencies of unrelated 2566 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly 2567 // arbitrary and just meant to cap the how much time we spend in the pruning 2568 // loop. Its highly unlikely to come into affect. 2569 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth; 2570 // Stop after a certain point. No incorrectness from including too many 2571 // instructions. 2572 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) { 2573 const Instruction *ToDrop = nullptr; 2574 for (const auto &InsPair : RhsDeps) { 2575 if (!ShouldCountInsn(InsPair.first)) { 2576 ToDrop = InsPair.first; 2577 break; 2578 } 2579 } 2580 if (ToDrop == nullptr) 2581 break; 2582 RhsDeps.erase(ToDrop); 2583 } 2584 2585 for (const auto &InsPair : RhsDeps) { 2586 // Finally accumulate latency that we can only attribute to computing the 2587 // RHS condition. Use latency because we are essentially trying to calculate 2588 // the cost of the dependency chain. 2589 // Possible TODO: We could try to estimate ILP and make this more precise. 2590 CostOfIncluding += 2591 TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency); 2592 2593 if (CostOfIncluding > CostThresh) 2594 return false; 2595 } 2596 return true; 2597 } 2598 2599 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2600 MachineBasicBlock *TBB, 2601 MachineBasicBlock *FBB, 2602 MachineBasicBlock *CurBB, 2603 MachineBasicBlock *SwitchBB, 2604 Instruction::BinaryOps Opc, 2605 BranchProbability TProb, 2606 BranchProbability FProb, 2607 bool InvertCond) { 2608 // Skip over not part of the tree and remember to invert op and operands at 2609 // next level. 2610 Value *NotCond; 2611 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2612 InBlock(NotCond, CurBB->getBasicBlock())) { 2613 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2614 !InvertCond); 2615 return; 2616 } 2617 2618 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2619 const Value *BOpOp0, *BOpOp1; 2620 // Compute the effective opcode for Cond, taking into account whether it needs 2621 // to be inverted, e.g. 2622 // and (not (or A, B)), C 2623 // gets lowered as 2624 // and (and (not A, not B), C) 2625 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2626 if (BOp) { 2627 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2628 ? Instruction::And 2629 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2630 ? Instruction::Or 2631 : (Instruction::BinaryOps)0); 2632 if (InvertCond) { 2633 if (BOpc == Instruction::And) 2634 BOpc = Instruction::Or; 2635 else if (BOpc == Instruction::Or) 2636 BOpc = Instruction::And; 2637 } 2638 } 2639 2640 // If this node is not part of the or/and tree, emit it as a branch. 2641 // Note that all nodes in the tree should have same opcode. 2642 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2643 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2644 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2645 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2646 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2647 TProb, FProb, InvertCond); 2648 return; 2649 } 2650 2651 // Create TmpBB after CurBB. 2652 MachineFunction::iterator BBI(CurBB); 2653 MachineFunction &MF = DAG.getMachineFunction(); 2654 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2655 CurBB->getParent()->insert(++BBI, TmpBB); 2656 2657 if (Opc == Instruction::Or) { 2658 // Codegen X | Y as: 2659 // BB1: 2660 // jmp_if_X TBB 2661 // jmp TmpBB 2662 // TmpBB: 2663 // jmp_if_Y TBB 2664 // jmp FBB 2665 // 2666 2667 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2668 // The requirement is that 2669 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2670 // = TrueProb for original BB. 2671 // Assuming the original probabilities are A and B, one choice is to set 2672 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2673 // A/(1+B) and 2B/(1+B). This choice assumes that 2674 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2675 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2676 // TmpBB, but the math is more complicated. 2677 2678 auto NewTrueProb = TProb / 2; 2679 auto NewFalseProb = TProb / 2 + FProb; 2680 // Emit the LHS condition. 2681 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2682 NewFalseProb, InvertCond); 2683 2684 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2685 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2686 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2687 // Emit the RHS condition into TmpBB. 2688 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2689 Probs[1], InvertCond); 2690 } else { 2691 assert(Opc == Instruction::And && "Unknown merge op!"); 2692 // Codegen X & Y as: 2693 // BB1: 2694 // jmp_if_X TmpBB 2695 // jmp FBB 2696 // TmpBB: 2697 // jmp_if_Y TBB 2698 // jmp FBB 2699 // 2700 // This requires creation of TmpBB after CurBB. 2701 2702 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2703 // The requirement is that 2704 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2705 // = FalseProb for original BB. 2706 // Assuming the original probabilities are A and B, one choice is to set 2707 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2708 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2709 // TrueProb for BB1 * FalseProb for TmpBB. 2710 2711 auto NewTrueProb = TProb + FProb / 2; 2712 auto NewFalseProb = FProb / 2; 2713 // Emit the LHS condition. 2714 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2715 NewFalseProb, InvertCond); 2716 2717 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2718 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2719 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2720 // Emit the RHS condition into TmpBB. 2721 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2722 Probs[1], InvertCond); 2723 } 2724 } 2725 2726 /// If the set of cases should be emitted as a series of branches, return true. 2727 /// If we should emit this as a bunch of and/or'd together conditions, return 2728 /// false. 2729 bool 2730 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2731 if (Cases.size() != 2) return true; 2732 2733 // If this is two comparisons of the same values or'd or and'd together, they 2734 // will get folded into a single comparison, so don't emit two blocks. 2735 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2736 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2737 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2738 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2739 return false; 2740 } 2741 2742 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2743 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2744 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2745 Cases[0].CC == Cases[1].CC && 2746 isa<Constant>(Cases[0].CmpRHS) && 2747 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2748 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2749 return false; 2750 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2751 return false; 2752 } 2753 2754 return true; 2755 } 2756 2757 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2758 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2759 2760 // Update machine-CFG edges. 2761 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2762 2763 if (I.isUnconditional()) { 2764 // Update machine-CFG edges. 2765 BrMBB->addSuccessor(Succ0MBB); 2766 2767 // If this is not a fall-through branch or optimizations are switched off, 2768 // emit the branch. 2769 if (Succ0MBB != NextBlock(BrMBB) || 2770 TM.getOptLevel() == CodeGenOptLevel::None) { 2771 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2772 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2773 setValue(&I, Br); 2774 DAG.setRoot(Br); 2775 } 2776 2777 return; 2778 } 2779 2780 // If this condition is one of the special cases we handle, do special stuff 2781 // now. 2782 const Value *CondVal = I.getCondition(); 2783 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2784 2785 // If this is a series of conditions that are or'd or and'd together, emit 2786 // this as a sequence of branches instead of setcc's with and/or operations. 2787 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2788 // unpredictable branches, and vector extracts because those jumps are likely 2789 // expensive for any target), this should improve performance. 2790 // For example, instead of something like: 2791 // cmp A, B 2792 // C = seteq 2793 // cmp D, E 2794 // F = setle 2795 // or C, F 2796 // jnz foo 2797 // Emit: 2798 // cmp A, B 2799 // je foo 2800 // cmp D, E 2801 // jle foo 2802 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2803 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2804 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2805 Value *Vec; 2806 const Value *BOp0, *BOp1; 2807 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2808 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2809 Opcode = Instruction::And; 2810 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2811 Opcode = Instruction::Or; 2812 2813 if (Opcode && 2814 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2815 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) && 2816 !shouldKeepJumpConditionsTogether( 2817 FuncInfo, I, Opcode, BOp0, BOp1, 2818 DAG.getTargetLoweringInfo().getJumpConditionMergingParams( 2819 Opcode, BOp0, BOp1))) { 2820 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2821 getEdgeProbability(BrMBB, Succ0MBB), 2822 getEdgeProbability(BrMBB, Succ1MBB), 2823 /*InvertCond=*/false); 2824 // If the compares in later blocks need to use values not currently 2825 // exported from this block, export them now. This block should always 2826 // be the first entry. 2827 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2828 2829 // Allow some cases to be rejected. 2830 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2831 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2832 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2833 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2834 } 2835 2836 // Emit the branch for this block. 2837 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2838 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2839 return; 2840 } 2841 2842 // Okay, we decided not to do this, remove any inserted MBB's and clear 2843 // SwitchCases. 2844 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2845 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2846 2847 SL->SwitchCases.clear(); 2848 } 2849 } 2850 2851 // Create a CaseBlock record representing this branch. 2852 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2853 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2854 2855 // Use visitSwitchCase to actually insert the fast branch sequence for this 2856 // cond branch. 2857 visitSwitchCase(CB, BrMBB); 2858 } 2859 2860 /// visitSwitchCase - Emits the necessary code to represent a single node in 2861 /// the binary search tree resulting from lowering a switch instruction. 2862 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2863 MachineBasicBlock *SwitchBB) { 2864 SDValue Cond; 2865 SDValue CondLHS = getValue(CB.CmpLHS); 2866 SDLoc dl = CB.DL; 2867 2868 if (CB.CC == ISD::SETTRUE) { 2869 // Branch or fall through to TrueBB. 2870 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2871 SwitchBB->normalizeSuccProbs(); 2872 if (CB.TrueBB != NextBlock(SwitchBB)) { 2873 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2874 DAG.getBasicBlock(CB.TrueBB))); 2875 } 2876 return; 2877 } 2878 2879 auto &TLI = DAG.getTargetLoweringInfo(); 2880 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2881 2882 // Build the setcc now. 2883 if (!CB.CmpMHS) { 2884 // Fold "(X == true)" to X and "(X == false)" to !X to 2885 // handle common cases produced by branch lowering. 2886 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2887 CB.CC == ISD::SETEQ) 2888 Cond = CondLHS; 2889 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2890 CB.CC == ISD::SETEQ) { 2891 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2892 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2893 } else { 2894 SDValue CondRHS = getValue(CB.CmpRHS); 2895 2896 // If a pointer's DAG type is larger than its memory type then the DAG 2897 // values are zero-extended. This breaks signed comparisons so truncate 2898 // back to the underlying type before doing the compare. 2899 if (CondLHS.getValueType() != MemVT) { 2900 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2901 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2902 } 2903 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2904 } 2905 } else { 2906 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2907 2908 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2909 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2910 2911 SDValue CmpOp = getValue(CB.CmpMHS); 2912 EVT VT = CmpOp.getValueType(); 2913 2914 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2915 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2916 ISD::SETLE); 2917 } else { 2918 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2919 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2920 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2921 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2922 } 2923 } 2924 2925 // Update successor info 2926 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2927 // TrueBB and FalseBB are always different unless the incoming IR is 2928 // degenerate. This only happens when running llc on weird IR. 2929 if (CB.TrueBB != CB.FalseBB) 2930 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2931 SwitchBB->normalizeSuccProbs(); 2932 2933 // If the lhs block is the next block, invert the condition so that we can 2934 // fall through to the lhs instead of the rhs block. 2935 if (CB.TrueBB == NextBlock(SwitchBB)) { 2936 std::swap(CB.TrueBB, CB.FalseBB); 2937 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2938 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2939 } 2940 2941 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2942 MVT::Other, getControlRoot(), Cond, 2943 DAG.getBasicBlock(CB.TrueBB)); 2944 2945 setValue(CurInst, BrCond); 2946 2947 // Insert the false branch. Do this even if it's a fall through branch, 2948 // this makes it easier to do DAG optimizations which require inverting 2949 // the branch condition. 2950 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2951 DAG.getBasicBlock(CB.FalseBB)); 2952 2953 DAG.setRoot(BrCond); 2954 } 2955 2956 /// visitJumpTable - Emit JumpTable node in the current MBB 2957 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2958 // Emit the code for the jump table 2959 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2960 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2961 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2962 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2963 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2964 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2965 Index.getValue(1), Table, Index); 2966 DAG.setRoot(BrJumpTable); 2967 } 2968 2969 /// visitJumpTableHeader - This function emits necessary code to produce index 2970 /// in the JumpTable from switch case. 2971 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2972 JumpTableHeader &JTH, 2973 MachineBasicBlock *SwitchBB) { 2974 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2975 const SDLoc &dl = *JT.SL; 2976 2977 // Subtract the lowest switch case value from the value being switched on. 2978 SDValue SwitchOp = getValue(JTH.SValue); 2979 EVT VT = SwitchOp.getValueType(); 2980 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2981 DAG.getConstant(JTH.First, dl, VT)); 2982 2983 // The SDNode we just created, which holds the value being switched on minus 2984 // the smallest case value, needs to be copied to a virtual register so it 2985 // can be used as an index into the jump table in a subsequent basic block. 2986 // This value may be smaller or larger than the target's pointer type, and 2987 // therefore require extension or truncating. 2988 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2989 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2990 2991 unsigned JumpTableReg = 2992 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2993 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2994 JumpTableReg, SwitchOp); 2995 JT.Reg = JumpTableReg; 2996 2997 if (!JTH.FallthroughUnreachable) { 2998 // Emit the range check for the jump table, and branch to the default block 2999 // for the switch statement if the value being switched on exceeds the 3000 // largest case in the switch. 3001 SDValue CMP = DAG.getSetCC( 3002 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3003 Sub.getValueType()), 3004 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 3005 3006 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3007 MVT::Other, CopyTo, CMP, 3008 DAG.getBasicBlock(JT.Default)); 3009 3010 // Avoid emitting unnecessary branches to the next block. 3011 if (JT.MBB != NextBlock(SwitchBB)) 3012 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 3013 DAG.getBasicBlock(JT.MBB)); 3014 3015 DAG.setRoot(BrCond); 3016 } else { 3017 // Avoid emitting unnecessary branches to the next block. 3018 if (JT.MBB != NextBlock(SwitchBB)) 3019 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 3020 DAG.getBasicBlock(JT.MBB))); 3021 else 3022 DAG.setRoot(CopyTo); 3023 } 3024 } 3025 3026 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 3027 /// variable if there exists one. 3028 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 3029 SDValue &Chain) { 3030 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3031 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3032 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3033 MachineFunction &MF = DAG.getMachineFunction(); 3034 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 3035 MachineSDNode *Node = 3036 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 3037 if (Global) { 3038 MachinePointerInfo MPInfo(Global); 3039 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 3040 MachineMemOperand::MODereferenceable; 3041 MachineMemOperand *MemRef = MF.getMachineMemOperand( 3042 MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8), 3043 DAG.getEVTAlign(PtrTy)); 3044 DAG.setNodeMemRefs(Node, {MemRef}); 3045 } 3046 if (PtrTy != PtrMemTy) 3047 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 3048 return SDValue(Node, 0); 3049 } 3050 3051 /// Codegen a new tail for a stack protector check ParentMBB which has had its 3052 /// tail spliced into a stack protector check success bb. 3053 /// 3054 /// For a high level explanation of how this fits into the stack protector 3055 /// generation see the comment on the declaration of class 3056 /// StackProtectorDescriptor. 3057 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 3058 MachineBasicBlock *ParentBB) { 3059 3060 // First create the loads to the guard/stack slot for the comparison. 3061 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3062 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3063 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3064 3065 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 3066 int FI = MFI.getStackProtectorIndex(); 3067 3068 SDValue Guard; 3069 SDLoc dl = getCurSDLoc(); 3070 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 3071 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 3072 Align Align = 3073 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 3074 3075 // Generate code to load the content of the guard slot. 3076 SDValue GuardVal = DAG.getLoad( 3077 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 3078 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 3079 MachineMemOperand::MOVolatile); 3080 3081 if (TLI.useStackGuardXorFP()) 3082 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 3083 3084 // Retrieve guard check function, nullptr if instrumentation is inlined. 3085 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 3086 // The target provides a guard check function to validate the guard value. 3087 // Generate a call to that function with the content of the guard slot as 3088 // argument. 3089 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 3090 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 3091 3092 TargetLowering::ArgListTy Args; 3093 TargetLowering::ArgListEntry Entry; 3094 Entry.Node = GuardVal; 3095 Entry.Ty = FnTy->getParamType(0); 3096 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 3097 Entry.IsInReg = true; 3098 Args.push_back(Entry); 3099 3100 TargetLowering::CallLoweringInfo CLI(DAG); 3101 CLI.setDebugLoc(getCurSDLoc()) 3102 .setChain(DAG.getEntryNode()) 3103 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 3104 getValue(GuardCheckFn), std::move(Args)); 3105 3106 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 3107 DAG.setRoot(Result.second); 3108 return; 3109 } 3110 3111 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 3112 // Otherwise, emit a volatile load to retrieve the stack guard value. 3113 SDValue Chain = DAG.getEntryNode(); 3114 if (TLI.useLoadStackGuardNode()) { 3115 Guard = getLoadStackGuard(DAG, dl, Chain); 3116 } else { 3117 const Value *IRGuard = TLI.getSDagStackGuard(M); 3118 SDValue GuardPtr = getValue(IRGuard); 3119 3120 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 3121 MachinePointerInfo(IRGuard, 0), Align, 3122 MachineMemOperand::MOVolatile); 3123 } 3124 3125 // Perform the comparison via a getsetcc. 3126 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 3127 *DAG.getContext(), 3128 Guard.getValueType()), 3129 Guard, GuardVal, ISD::SETNE); 3130 3131 // If the guard/stackslot do not equal, branch to failure MBB. 3132 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3133 MVT::Other, GuardVal.getOperand(0), 3134 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 3135 // Otherwise branch to success MBB. 3136 SDValue Br = DAG.getNode(ISD::BR, dl, 3137 MVT::Other, BrCond, 3138 DAG.getBasicBlock(SPD.getSuccessMBB())); 3139 3140 DAG.setRoot(Br); 3141 } 3142 3143 /// Codegen the failure basic block for a stack protector check. 3144 /// 3145 /// A failure stack protector machine basic block consists simply of a call to 3146 /// __stack_chk_fail(). 3147 /// 3148 /// For a high level explanation of how this fits into the stack protector 3149 /// generation see the comment on the declaration of class 3150 /// StackProtectorDescriptor. 3151 void 3152 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 3153 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3154 TargetLowering::MakeLibCallOptions CallOptions; 3155 CallOptions.setDiscardResult(true); 3156 SDValue Chain = 3157 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 3158 std::nullopt, CallOptions, getCurSDLoc()) 3159 .second; 3160 // On PS4/PS5, the "return address" must still be within the calling 3161 // function, even if it's at the very end, so emit an explicit TRAP here. 3162 // Passing 'true' for doesNotReturn above won't generate the trap for us. 3163 if (TM.getTargetTriple().isPS()) 3164 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3165 // WebAssembly needs an unreachable instruction after a non-returning call, 3166 // because the function return type can be different from __stack_chk_fail's 3167 // return type (void). 3168 if (TM.getTargetTriple().isWasm()) 3169 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3170 3171 DAG.setRoot(Chain); 3172 } 3173 3174 /// visitBitTestHeader - This function emits necessary code to produce value 3175 /// suitable for "bit tests" 3176 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3177 MachineBasicBlock *SwitchBB) { 3178 SDLoc dl = getCurSDLoc(); 3179 3180 // Subtract the minimum value. 3181 SDValue SwitchOp = getValue(B.SValue); 3182 EVT VT = SwitchOp.getValueType(); 3183 SDValue RangeSub = 3184 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3185 3186 // Determine the type of the test operands. 3187 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3188 bool UsePtrType = false; 3189 if (!TLI.isTypeLegal(VT)) { 3190 UsePtrType = true; 3191 } else { 3192 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3193 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3194 // Switch table case range are encoded into series of masks. 3195 // Just use pointer type, it's guaranteed to fit. 3196 UsePtrType = true; 3197 break; 3198 } 3199 } 3200 SDValue Sub = RangeSub; 3201 if (UsePtrType) { 3202 VT = TLI.getPointerTy(DAG.getDataLayout()); 3203 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3204 } 3205 3206 B.RegVT = VT.getSimpleVT(); 3207 B.Reg = FuncInfo.CreateReg(B.RegVT); 3208 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3209 3210 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3211 3212 if (!B.FallthroughUnreachable) 3213 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3214 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3215 SwitchBB->normalizeSuccProbs(); 3216 3217 SDValue Root = CopyTo; 3218 if (!B.FallthroughUnreachable) { 3219 // Conditional branch to the default block. 3220 SDValue RangeCmp = DAG.getSetCC(dl, 3221 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3222 RangeSub.getValueType()), 3223 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3224 ISD::SETUGT); 3225 3226 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3227 DAG.getBasicBlock(B.Default)); 3228 } 3229 3230 // Avoid emitting unnecessary branches to the next block. 3231 if (MBB != NextBlock(SwitchBB)) 3232 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3233 3234 DAG.setRoot(Root); 3235 } 3236 3237 /// visitBitTestCase - this function produces one "bit test" 3238 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3239 MachineBasicBlock* NextMBB, 3240 BranchProbability BranchProbToNext, 3241 unsigned Reg, 3242 BitTestCase &B, 3243 MachineBasicBlock *SwitchBB) { 3244 SDLoc dl = getCurSDLoc(); 3245 MVT VT = BB.RegVT; 3246 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3247 SDValue Cmp; 3248 unsigned PopCount = llvm::popcount(B.Mask); 3249 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3250 if (PopCount == 1) { 3251 // Testing for a single bit; just compare the shift count with what it 3252 // would need to be to shift a 1 bit in that position. 3253 Cmp = DAG.getSetCC( 3254 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3255 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3256 ISD::SETEQ); 3257 } else if (PopCount == BB.Range) { 3258 // There is only one zero bit in the range, test for it directly. 3259 Cmp = DAG.getSetCC( 3260 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3261 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3262 } else { 3263 // Make desired shift 3264 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3265 DAG.getConstant(1, dl, VT), ShiftOp); 3266 3267 // Emit bit tests and jumps 3268 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3269 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3270 Cmp = DAG.getSetCC( 3271 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3272 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3273 } 3274 3275 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3276 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3277 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3278 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3279 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3280 // one as they are relative probabilities (and thus work more like weights), 3281 // and hence we need to normalize them to let the sum of them become one. 3282 SwitchBB->normalizeSuccProbs(); 3283 3284 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3285 MVT::Other, getControlRoot(), 3286 Cmp, DAG.getBasicBlock(B.TargetBB)); 3287 3288 // Avoid emitting unnecessary branches to the next block. 3289 if (NextMBB != NextBlock(SwitchBB)) 3290 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3291 DAG.getBasicBlock(NextMBB)); 3292 3293 DAG.setRoot(BrAnd); 3294 } 3295 3296 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3297 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3298 3299 // Retrieve successors. Look through artificial IR level blocks like 3300 // catchswitch for successors. 3301 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3302 const BasicBlock *EHPadBB = I.getSuccessor(1); 3303 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3304 3305 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3306 // have to do anything here to lower funclet bundles. 3307 assert(!I.hasOperandBundlesOtherThan( 3308 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3309 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3310 LLVMContext::OB_cfguardtarget, 3311 LLVMContext::OB_clang_arc_attachedcall}) && 3312 "Cannot lower invokes with arbitrary operand bundles yet!"); 3313 3314 const Value *Callee(I.getCalledOperand()); 3315 const Function *Fn = dyn_cast<Function>(Callee); 3316 if (isa<InlineAsm>(Callee)) 3317 visitInlineAsm(I, EHPadBB); 3318 else if (Fn && Fn->isIntrinsic()) { 3319 switch (Fn->getIntrinsicID()) { 3320 default: 3321 llvm_unreachable("Cannot invoke this intrinsic"); 3322 case Intrinsic::donothing: 3323 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3324 case Intrinsic::seh_try_begin: 3325 case Intrinsic::seh_scope_begin: 3326 case Intrinsic::seh_try_end: 3327 case Intrinsic::seh_scope_end: 3328 if (EHPadMBB) 3329 // a block referenced by EH table 3330 // so dtor-funclet not removed by opts 3331 EHPadMBB->setMachineBlockAddressTaken(); 3332 break; 3333 case Intrinsic::experimental_patchpoint_void: 3334 case Intrinsic::experimental_patchpoint: 3335 visitPatchpoint(I, EHPadBB); 3336 break; 3337 case Intrinsic::experimental_gc_statepoint: 3338 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3339 break; 3340 case Intrinsic::wasm_rethrow: { 3341 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3342 // special because it can be invoked, so we manually lower it to a DAG 3343 // node here. 3344 SmallVector<SDValue, 8> Ops; 3345 Ops.push_back(getRoot()); // inchain 3346 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3347 Ops.push_back( 3348 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3349 TLI.getPointerTy(DAG.getDataLayout()))); 3350 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3351 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3352 break; 3353 } 3354 } 3355 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3356 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3357 // Eventually we will support lowering the @llvm.experimental.deoptimize 3358 // intrinsic, and right now there are no plans to support other intrinsics 3359 // with deopt state. 3360 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3361 } else { 3362 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3363 } 3364 3365 // If the value of the invoke is used outside of its defining block, make it 3366 // available as a virtual register. 3367 // We already took care of the exported value for the statepoint instruction 3368 // during call to the LowerStatepoint. 3369 if (!isa<GCStatepointInst>(I)) { 3370 CopyToExportRegsIfNeeded(&I); 3371 } 3372 3373 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3374 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3375 BranchProbability EHPadBBProb = 3376 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3377 : BranchProbability::getZero(); 3378 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3379 3380 // Update successor info. 3381 addSuccessorWithProb(InvokeMBB, Return); 3382 for (auto &UnwindDest : UnwindDests) { 3383 UnwindDest.first->setIsEHPad(); 3384 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3385 } 3386 InvokeMBB->normalizeSuccProbs(); 3387 3388 // Drop into normal successor. 3389 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3390 DAG.getBasicBlock(Return))); 3391 } 3392 3393 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3394 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3395 3396 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3397 // have to do anything here to lower funclet bundles. 3398 assert(!I.hasOperandBundlesOtherThan( 3399 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3400 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3401 3402 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3403 visitInlineAsm(I); 3404 CopyToExportRegsIfNeeded(&I); 3405 3406 // Retrieve successors. 3407 SmallPtrSet<BasicBlock *, 8> Dests; 3408 Dests.insert(I.getDefaultDest()); 3409 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3410 3411 // Update successor info. 3412 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3413 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3414 BasicBlock *Dest = I.getIndirectDest(i); 3415 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3416 Target->setIsInlineAsmBrIndirectTarget(); 3417 Target->setMachineBlockAddressTaken(); 3418 Target->setLabelMustBeEmitted(); 3419 // Don't add duplicate machine successors. 3420 if (Dests.insert(Dest).second) 3421 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3422 } 3423 CallBrMBB->normalizeSuccProbs(); 3424 3425 // Drop into default successor. 3426 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3427 MVT::Other, getControlRoot(), 3428 DAG.getBasicBlock(Return))); 3429 } 3430 3431 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3432 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3433 } 3434 3435 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3436 assert(FuncInfo.MBB->isEHPad() && 3437 "Call to landingpad not in landing pad!"); 3438 3439 // If there aren't registers to copy the values into (e.g., during SjLj 3440 // exceptions), then don't bother to create these DAG nodes. 3441 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3442 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3443 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3444 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3445 return; 3446 3447 // If landingpad's return type is token type, we don't create DAG nodes 3448 // for its exception pointer and selector value. The extraction of exception 3449 // pointer or selector value from token type landingpads is not currently 3450 // supported. 3451 if (LP.getType()->isTokenTy()) 3452 return; 3453 3454 SmallVector<EVT, 2> ValueVTs; 3455 SDLoc dl = getCurSDLoc(); 3456 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3457 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3458 3459 // Get the two live-in registers as SDValues. The physregs have already been 3460 // copied into virtual registers. 3461 SDValue Ops[2]; 3462 if (FuncInfo.ExceptionPointerVirtReg) { 3463 Ops[0] = DAG.getZExtOrTrunc( 3464 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3465 FuncInfo.ExceptionPointerVirtReg, 3466 TLI.getPointerTy(DAG.getDataLayout())), 3467 dl, ValueVTs[0]); 3468 } else { 3469 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3470 } 3471 Ops[1] = DAG.getZExtOrTrunc( 3472 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3473 FuncInfo.ExceptionSelectorVirtReg, 3474 TLI.getPointerTy(DAG.getDataLayout())), 3475 dl, ValueVTs[1]); 3476 3477 // Merge into one. 3478 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3479 DAG.getVTList(ValueVTs), Ops); 3480 setValue(&LP, Res); 3481 } 3482 3483 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3484 MachineBasicBlock *Last) { 3485 // Update JTCases. 3486 for (JumpTableBlock &JTB : SL->JTCases) 3487 if (JTB.first.HeaderBB == First) 3488 JTB.first.HeaderBB = Last; 3489 3490 // Update BitTestCases. 3491 for (BitTestBlock &BTB : SL->BitTestCases) 3492 if (BTB.Parent == First) 3493 BTB.Parent = Last; 3494 } 3495 3496 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3497 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3498 3499 // Update machine-CFG edges with unique successors. 3500 SmallSet<BasicBlock*, 32> Done; 3501 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3502 BasicBlock *BB = I.getSuccessor(i); 3503 bool Inserted = Done.insert(BB).second; 3504 if (!Inserted) 3505 continue; 3506 3507 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3508 addSuccessorWithProb(IndirectBrMBB, Succ); 3509 } 3510 IndirectBrMBB->normalizeSuccProbs(); 3511 3512 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3513 MVT::Other, getControlRoot(), 3514 getValue(I.getAddress()))); 3515 } 3516 3517 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3518 if (!DAG.getTarget().Options.TrapUnreachable) 3519 return; 3520 3521 // We may be able to ignore unreachable behind a noreturn call. 3522 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3523 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) { 3524 if (Call->doesNotReturn()) 3525 return; 3526 } 3527 } 3528 3529 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3530 } 3531 3532 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3533 SDNodeFlags Flags; 3534 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3535 Flags.copyFMF(*FPOp); 3536 3537 SDValue Op = getValue(I.getOperand(0)); 3538 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3539 Op, Flags); 3540 setValue(&I, UnNodeValue); 3541 } 3542 3543 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3544 SDNodeFlags Flags; 3545 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3546 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3547 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3548 } 3549 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3550 Flags.setExact(ExactOp->isExact()); 3551 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3552 Flags.setDisjoint(DisjointOp->isDisjoint()); 3553 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3554 Flags.copyFMF(*FPOp); 3555 3556 SDValue Op1 = getValue(I.getOperand(0)); 3557 SDValue Op2 = getValue(I.getOperand(1)); 3558 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3559 Op1, Op2, Flags); 3560 setValue(&I, BinNodeValue); 3561 } 3562 3563 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3564 SDValue Op1 = getValue(I.getOperand(0)); 3565 SDValue Op2 = getValue(I.getOperand(1)); 3566 3567 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3568 Op1.getValueType(), DAG.getDataLayout()); 3569 3570 // Coerce the shift amount to the right type if we can. This exposes the 3571 // truncate or zext to optimization early. 3572 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3573 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3574 "Unexpected shift type"); 3575 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3576 } 3577 3578 bool nuw = false; 3579 bool nsw = false; 3580 bool exact = false; 3581 3582 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3583 3584 if (const OverflowingBinaryOperator *OFBinOp = 3585 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3586 nuw = OFBinOp->hasNoUnsignedWrap(); 3587 nsw = OFBinOp->hasNoSignedWrap(); 3588 } 3589 if (const PossiblyExactOperator *ExactOp = 3590 dyn_cast<const PossiblyExactOperator>(&I)) 3591 exact = ExactOp->isExact(); 3592 } 3593 SDNodeFlags Flags; 3594 Flags.setExact(exact); 3595 Flags.setNoSignedWrap(nsw); 3596 Flags.setNoUnsignedWrap(nuw); 3597 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3598 Flags); 3599 setValue(&I, Res); 3600 } 3601 3602 void SelectionDAGBuilder::visitSDiv(const User &I) { 3603 SDValue Op1 = getValue(I.getOperand(0)); 3604 SDValue Op2 = getValue(I.getOperand(1)); 3605 3606 SDNodeFlags Flags; 3607 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3608 cast<PossiblyExactOperator>(&I)->isExact()); 3609 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3610 Op2, Flags)); 3611 } 3612 3613 void SelectionDAGBuilder::visitICmp(const User &I) { 3614 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3615 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3616 predicate = IC->getPredicate(); 3617 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3618 predicate = ICmpInst::Predicate(IC->getPredicate()); 3619 SDValue Op1 = getValue(I.getOperand(0)); 3620 SDValue Op2 = getValue(I.getOperand(1)); 3621 ISD::CondCode Opcode = getICmpCondCode(predicate); 3622 3623 auto &TLI = DAG.getTargetLoweringInfo(); 3624 EVT MemVT = 3625 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3626 3627 // If a pointer's DAG type is larger than its memory type then the DAG values 3628 // are zero-extended. This breaks signed comparisons so truncate back to the 3629 // underlying type before doing the compare. 3630 if (Op1.getValueType() != MemVT) { 3631 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3632 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3633 } 3634 3635 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3636 I.getType()); 3637 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3638 } 3639 3640 void SelectionDAGBuilder::visitFCmp(const User &I) { 3641 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3642 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3643 predicate = FC->getPredicate(); 3644 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3645 predicate = FCmpInst::Predicate(FC->getPredicate()); 3646 SDValue Op1 = getValue(I.getOperand(0)); 3647 SDValue Op2 = getValue(I.getOperand(1)); 3648 3649 ISD::CondCode Condition = getFCmpCondCode(predicate); 3650 auto *FPMO = cast<FPMathOperator>(&I); 3651 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3652 Condition = getFCmpCodeWithoutNaN(Condition); 3653 3654 SDNodeFlags Flags; 3655 Flags.copyFMF(*FPMO); 3656 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3657 3658 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3659 I.getType()); 3660 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3661 } 3662 3663 // Check if the condition of the select has one use or two users that are both 3664 // selects with the same condition. 3665 static bool hasOnlySelectUsers(const Value *Cond) { 3666 return llvm::all_of(Cond->users(), [](const Value *V) { 3667 return isa<SelectInst>(V); 3668 }); 3669 } 3670 3671 void SelectionDAGBuilder::visitSelect(const User &I) { 3672 SmallVector<EVT, 4> ValueVTs; 3673 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3674 ValueVTs); 3675 unsigned NumValues = ValueVTs.size(); 3676 if (NumValues == 0) return; 3677 3678 SmallVector<SDValue, 4> Values(NumValues); 3679 SDValue Cond = getValue(I.getOperand(0)); 3680 SDValue LHSVal = getValue(I.getOperand(1)); 3681 SDValue RHSVal = getValue(I.getOperand(2)); 3682 SmallVector<SDValue, 1> BaseOps(1, Cond); 3683 ISD::NodeType OpCode = 3684 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3685 3686 bool IsUnaryAbs = false; 3687 bool Negate = false; 3688 3689 SDNodeFlags Flags; 3690 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3691 Flags.copyFMF(*FPOp); 3692 3693 Flags.setUnpredictable( 3694 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3695 3696 // Min/max matching is only viable if all output VTs are the same. 3697 if (all_equal(ValueVTs)) { 3698 EVT VT = ValueVTs[0]; 3699 LLVMContext &Ctx = *DAG.getContext(); 3700 auto &TLI = DAG.getTargetLoweringInfo(); 3701 3702 // We care about the legality of the operation after it has been type 3703 // legalized. 3704 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3705 VT = TLI.getTypeToTransformTo(Ctx, VT); 3706 3707 // If the vselect is legal, assume we want to leave this as a vector setcc + 3708 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3709 // min/max is legal on the scalar type. 3710 bool UseScalarMinMax = VT.isVector() && 3711 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3712 3713 // ValueTracking's select pattern matching does not account for -0.0, 3714 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3715 // -0.0 is less than +0.0. 3716 Value *LHS, *RHS; 3717 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3718 ISD::NodeType Opc = ISD::DELETED_NODE; 3719 switch (SPR.Flavor) { 3720 case SPF_UMAX: Opc = ISD::UMAX; break; 3721 case SPF_UMIN: Opc = ISD::UMIN; break; 3722 case SPF_SMAX: Opc = ISD::SMAX; break; 3723 case SPF_SMIN: Opc = ISD::SMIN; break; 3724 case SPF_FMINNUM: 3725 switch (SPR.NaNBehavior) { 3726 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3727 case SPNB_RETURNS_NAN: break; 3728 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3729 case SPNB_RETURNS_ANY: 3730 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3731 (UseScalarMinMax && 3732 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3733 Opc = ISD::FMINNUM; 3734 break; 3735 } 3736 break; 3737 case SPF_FMAXNUM: 3738 switch (SPR.NaNBehavior) { 3739 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3740 case SPNB_RETURNS_NAN: break; 3741 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3742 case SPNB_RETURNS_ANY: 3743 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3744 (UseScalarMinMax && 3745 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3746 Opc = ISD::FMAXNUM; 3747 break; 3748 } 3749 break; 3750 case SPF_NABS: 3751 Negate = true; 3752 [[fallthrough]]; 3753 case SPF_ABS: 3754 IsUnaryAbs = true; 3755 Opc = ISD::ABS; 3756 break; 3757 default: break; 3758 } 3759 3760 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3761 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3762 (UseScalarMinMax && 3763 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3764 // If the underlying comparison instruction is used by any other 3765 // instruction, the consumed instructions won't be destroyed, so it is 3766 // not profitable to convert to a min/max. 3767 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3768 OpCode = Opc; 3769 LHSVal = getValue(LHS); 3770 RHSVal = getValue(RHS); 3771 BaseOps.clear(); 3772 } 3773 3774 if (IsUnaryAbs) { 3775 OpCode = Opc; 3776 LHSVal = getValue(LHS); 3777 BaseOps.clear(); 3778 } 3779 } 3780 3781 if (IsUnaryAbs) { 3782 for (unsigned i = 0; i != NumValues; ++i) { 3783 SDLoc dl = getCurSDLoc(); 3784 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3785 Values[i] = 3786 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3787 if (Negate) 3788 Values[i] = DAG.getNegative(Values[i], dl, VT); 3789 } 3790 } else { 3791 for (unsigned i = 0; i != NumValues; ++i) { 3792 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3793 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3794 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3795 Values[i] = DAG.getNode( 3796 OpCode, getCurSDLoc(), 3797 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3798 } 3799 } 3800 3801 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3802 DAG.getVTList(ValueVTs), Values)); 3803 } 3804 3805 void SelectionDAGBuilder::visitTrunc(const User &I) { 3806 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3807 SDValue N = getValue(I.getOperand(0)); 3808 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3809 I.getType()); 3810 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3811 } 3812 3813 void SelectionDAGBuilder::visitZExt(const User &I) { 3814 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3815 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3816 SDValue N = getValue(I.getOperand(0)); 3817 auto &TLI = DAG.getTargetLoweringInfo(); 3818 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3819 3820 SDNodeFlags Flags; 3821 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3822 Flags.setNonNeg(PNI->hasNonNeg()); 3823 3824 // Eagerly use nonneg information to canonicalize towards sign_extend if 3825 // that is the target's preference. 3826 // TODO: Let the target do this later. 3827 if (Flags.hasNonNeg() && 3828 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3829 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3830 return; 3831 } 3832 3833 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3834 } 3835 3836 void SelectionDAGBuilder::visitSExt(const User &I) { 3837 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3838 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3839 SDValue N = getValue(I.getOperand(0)); 3840 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3841 I.getType()); 3842 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3843 } 3844 3845 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3846 // FPTrunc is never a no-op cast, no need to check 3847 SDValue N = getValue(I.getOperand(0)); 3848 SDLoc dl = getCurSDLoc(); 3849 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3850 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3851 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3852 DAG.getTargetConstant( 3853 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3854 } 3855 3856 void SelectionDAGBuilder::visitFPExt(const User &I) { 3857 // FPExt is never a no-op cast, no need to check 3858 SDValue N = getValue(I.getOperand(0)); 3859 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3860 I.getType()); 3861 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3862 } 3863 3864 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3865 // FPToUI is never a no-op cast, no need to check 3866 SDValue N = getValue(I.getOperand(0)); 3867 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3868 I.getType()); 3869 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3870 } 3871 3872 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3873 // FPToSI 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_TO_SINT, getCurSDLoc(), DestVT, N)); 3878 } 3879 3880 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3881 // UIToFP 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 SDNodeFlags Flags; 3886 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3887 Flags.setNonNeg(PNI->hasNonNeg()); 3888 3889 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags)); 3890 } 3891 3892 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3893 // SIToFP is never a no-op cast, no need to check 3894 SDValue N = getValue(I.getOperand(0)); 3895 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3896 I.getType()); 3897 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3898 } 3899 3900 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3901 // What to do depends on the size of the integer and the size of the pointer. 3902 // We can either truncate, zero extend, or no-op, accordingly. 3903 SDValue N = getValue(I.getOperand(0)); 3904 auto &TLI = DAG.getTargetLoweringInfo(); 3905 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3906 I.getType()); 3907 EVT PtrMemVT = 3908 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3909 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3910 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3911 setValue(&I, N); 3912 } 3913 3914 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3915 // What to do depends on the size of the integer and the size of the pointer. 3916 // We can either truncate, zero extend, or no-op, accordingly. 3917 SDValue N = getValue(I.getOperand(0)); 3918 auto &TLI = DAG.getTargetLoweringInfo(); 3919 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3920 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3921 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3922 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3923 setValue(&I, N); 3924 } 3925 3926 void SelectionDAGBuilder::visitBitCast(const User &I) { 3927 SDValue N = getValue(I.getOperand(0)); 3928 SDLoc dl = getCurSDLoc(); 3929 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3930 I.getType()); 3931 3932 // BitCast assures us that source and destination are the same size so this is 3933 // either a BITCAST or a no-op. 3934 if (DestVT != N.getValueType()) 3935 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3936 DestVT, N)); // convert types. 3937 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3938 // might fold any kind of constant expression to an integer constant and that 3939 // is not what we are looking for. Only recognize a bitcast of a genuine 3940 // constant integer as an opaque constant. 3941 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3942 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3943 /*isOpaque*/true)); 3944 else 3945 setValue(&I, N); // noop cast. 3946 } 3947 3948 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3949 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3950 const Value *SV = I.getOperand(0); 3951 SDValue N = getValue(SV); 3952 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3953 3954 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3955 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3956 3957 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3958 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3959 3960 setValue(&I, N); 3961 } 3962 3963 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3964 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3965 SDValue InVec = getValue(I.getOperand(0)); 3966 SDValue InVal = getValue(I.getOperand(1)); 3967 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3968 TLI.getVectorIdxTy(DAG.getDataLayout())); 3969 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3970 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3971 InVec, InVal, InIdx)); 3972 } 3973 3974 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3975 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3976 SDValue InVec = getValue(I.getOperand(0)); 3977 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3978 TLI.getVectorIdxTy(DAG.getDataLayout())); 3979 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3980 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3981 InVec, InIdx)); 3982 } 3983 3984 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3985 SDValue Src1 = getValue(I.getOperand(0)); 3986 SDValue Src2 = getValue(I.getOperand(1)); 3987 ArrayRef<int> Mask; 3988 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3989 Mask = SVI->getShuffleMask(); 3990 else 3991 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3992 SDLoc DL = getCurSDLoc(); 3993 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3994 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3995 EVT SrcVT = Src1.getValueType(); 3996 3997 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3998 VT.isScalableVector()) { 3999 // Canonical splat form of first element of first input vector. 4000 SDValue FirstElt = 4001 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 4002 DAG.getVectorIdxConstant(0, DL)); 4003 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 4004 return; 4005 } 4006 4007 // For now, we only handle splats for scalable vectors. 4008 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 4009 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 4010 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 4011 4012 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 4013 unsigned MaskNumElts = Mask.size(); 4014 4015 if (SrcNumElts == MaskNumElts) { 4016 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 4017 return; 4018 } 4019 4020 // Normalize the shuffle vector since mask and vector length don't match. 4021 if (SrcNumElts < MaskNumElts) { 4022 // Mask is longer than the source vectors. We can use concatenate vector to 4023 // make the mask and vectors lengths match. 4024 4025 if (MaskNumElts % SrcNumElts == 0) { 4026 // Mask length is a multiple of the source vector length. 4027 // Check if the shuffle is some kind of concatenation of the input 4028 // vectors. 4029 unsigned NumConcat = MaskNumElts / SrcNumElts; 4030 bool IsConcat = true; 4031 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 4032 for (unsigned i = 0; i != MaskNumElts; ++i) { 4033 int Idx = Mask[i]; 4034 if (Idx < 0) 4035 continue; 4036 // Ensure the indices in each SrcVT sized piece are sequential and that 4037 // the same source is used for the whole piece. 4038 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 4039 (ConcatSrcs[i / SrcNumElts] >= 0 && 4040 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 4041 IsConcat = false; 4042 break; 4043 } 4044 // Remember which source this index came from. 4045 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 4046 } 4047 4048 // The shuffle is concatenating multiple vectors together. Just emit 4049 // a CONCAT_VECTORS operation. 4050 if (IsConcat) { 4051 SmallVector<SDValue, 8> ConcatOps; 4052 for (auto Src : ConcatSrcs) { 4053 if (Src < 0) 4054 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 4055 else if (Src == 0) 4056 ConcatOps.push_back(Src1); 4057 else 4058 ConcatOps.push_back(Src2); 4059 } 4060 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 4061 return; 4062 } 4063 } 4064 4065 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 4066 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 4067 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 4068 PaddedMaskNumElts); 4069 4070 // Pad both vectors with undefs to make them the same length as the mask. 4071 SDValue UndefVal = DAG.getUNDEF(SrcVT); 4072 4073 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 4074 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 4075 MOps1[0] = Src1; 4076 MOps2[0] = Src2; 4077 4078 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 4079 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 4080 4081 // Readjust mask for new input vector length. 4082 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 4083 for (unsigned i = 0; i != MaskNumElts; ++i) { 4084 int Idx = Mask[i]; 4085 if (Idx >= (int)SrcNumElts) 4086 Idx -= SrcNumElts - PaddedMaskNumElts; 4087 MappedOps[i] = Idx; 4088 } 4089 4090 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 4091 4092 // If the concatenated vector was padded, extract a subvector with the 4093 // correct number of elements. 4094 if (MaskNumElts != PaddedMaskNumElts) 4095 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 4096 DAG.getVectorIdxConstant(0, DL)); 4097 4098 setValue(&I, Result); 4099 return; 4100 } 4101 4102 if (SrcNumElts > MaskNumElts) { 4103 // Analyze the access pattern of the vector to see if we can extract 4104 // two subvectors and do the shuffle. 4105 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 4106 bool CanExtract = true; 4107 for (int Idx : Mask) { 4108 unsigned Input = 0; 4109 if (Idx < 0) 4110 continue; 4111 4112 if (Idx >= (int)SrcNumElts) { 4113 Input = 1; 4114 Idx -= SrcNumElts; 4115 } 4116 4117 // If all the indices come from the same MaskNumElts sized portion of 4118 // the sources we can use extract. Also make sure the extract wouldn't 4119 // extract past the end of the source. 4120 int NewStartIdx = alignDown(Idx, MaskNumElts); 4121 if (NewStartIdx + MaskNumElts > SrcNumElts || 4122 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 4123 CanExtract = false; 4124 // Make sure we always update StartIdx as we use it to track if all 4125 // elements are undef. 4126 StartIdx[Input] = NewStartIdx; 4127 } 4128 4129 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 4130 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 4131 return; 4132 } 4133 if (CanExtract) { 4134 // Extract appropriate subvector and generate a vector shuffle 4135 for (unsigned Input = 0; Input < 2; ++Input) { 4136 SDValue &Src = Input == 0 ? Src1 : Src2; 4137 if (StartIdx[Input] < 0) 4138 Src = DAG.getUNDEF(VT); 4139 else { 4140 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 4141 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 4142 } 4143 } 4144 4145 // Calculate new mask. 4146 SmallVector<int, 8> MappedOps(Mask); 4147 for (int &Idx : MappedOps) { 4148 if (Idx >= (int)SrcNumElts) 4149 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 4150 else if (Idx >= 0) 4151 Idx -= StartIdx[0]; 4152 } 4153 4154 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 4155 return; 4156 } 4157 } 4158 4159 // We can't use either concat vectors or extract subvectors so fall back to 4160 // replacing the shuffle with extract and build vector. 4161 // to insert and build vector. 4162 EVT EltVT = VT.getVectorElementType(); 4163 SmallVector<SDValue,8> Ops; 4164 for (int Idx : Mask) { 4165 SDValue Res; 4166 4167 if (Idx < 0) { 4168 Res = DAG.getUNDEF(EltVT); 4169 } else { 4170 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 4171 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 4172 4173 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4174 DAG.getVectorIdxConstant(Idx, DL)); 4175 } 4176 4177 Ops.push_back(Res); 4178 } 4179 4180 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4181 } 4182 4183 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4184 ArrayRef<unsigned> Indices = I.getIndices(); 4185 const Value *Op0 = I.getOperand(0); 4186 const Value *Op1 = I.getOperand(1); 4187 Type *AggTy = I.getType(); 4188 Type *ValTy = Op1->getType(); 4189 bool IntoUndef = isa<UndefValue>(Op0); 4190 bool FromUndef = isa<UndefValue>(Op1); 4191 4192 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4193 4194 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4195 SmallVector<EVT, 4> AggValueVTs; 4196 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4197 SmallVector<EVT, 4> ValValueVTs; 4198 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4199 4200 unsigned NumAggValues = AggValueVTs.size(); 4201 unsigned NumValValues = ValValueVTs.size(); 4202 SmallVector<SDValue, 4> Values(NumAggValues); 4203 4204 // Ignore an insertvalue that produces an empty object 4205 if (!NumAggValues) { 4206 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4207 return; 4208 } 4209 4210 SDValue Agg = getValue(Op0); 4211 unsigned i = 0; 4212 // Copy the beginning value(s) from the original aggregate. 4213 for (; i != LinearIndex; ++i) 4214 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4215 SDValue(Agg.getNode(), Agg.getResNo() + i); 4216 // Copy values from the inserted value(s). 4217 if (NumValValues) { 4218 SDValue Val = getValue(Op1); 4219 for (; i != LinearIndex + NumValValues; ++i) 4220 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4221 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4222 } 4223 // Copy remaining value(s) from the original aggregate. 4224 for (; i != NumAggValues; ++i) 4225 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4226 SDValue(Agg.getNode(), Agg.getResNo() + i); 4227 4228 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4229 DAG.getVTList(AggValueVTs), Values)); 4230 } 4231 4232 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4233 ArrayRef<unsigned> Indices = I.getIndices(); 4234 const Value *Op0 = I.getOperand(0); 4235 Type *AggTy = Op0->getType(); 4236 Type *ValTy = I.getType(); 4237 bool OutOfUndef = isa<UndefValue>(Op0); 4238 4239 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4240 4241 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4242 SmallVector<EVT, 4> ValValueVTs; 4243 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4244 4245 unsigned NumValValues = ValValueVTs.size(); 4246 4247 // Ignore a extractvalue that produces an empty object 4248 if (!NumValValues) { 4249 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4250 return; 4251 } 4252 4253 SmallVector<SDValue, 4> Values(NumValValues); 4254 4255 SDValue Agg = getValue(Op0); 4256 // Copy out the selected value(s). 4257 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4258 Values[i - LinearIndex] = 4259 OutOfUndef ? 4260 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4261 SDValue(Agg.getNode(), Agg.getResNo() + i); 4262 4263 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4264 DAG.getVTList(ValValueVTs), Values)); 4265 } 4266 4267 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4268 Value *Op0 = I.getOperand(0); 4269 // Note that the pointer operand may be a vector of pointers. Take the scalar 4270 // element which holds a pointer. 4271 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4272 SDValue N = getValue(Op0); 4273 SDLoc dl = getCurSDLoc(); 4274 auto &TLI = DAG.getTargetLoweringInfo(); 4275 4276 // Normalize Vector GEP - all scalar operands should be converted to the 4277 // splat vector. 4278 bool IsVectorGEP = I.getType()->isVectorTy(); 4279 ElementCount VectorElementCount = 4280 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4281 : ElementCount::getFixed(0); 4282 4283 if (IsVectorGEP && !N.getValueType().isVector()) { 4284 LLVMContext &Context = *DAG.getContext(); 4285 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4286 N = DAG.getSplat(VT, dl, N); 4287 } 4288 4289 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4290 GTI != E; ++GTI) { 4291 const Value *Idx = GTI.getOperand(); 4292 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4293 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4294 if (Field) { 4295 // N = N + Offset 4296 uint64_t Offset = 4297 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4298 4299 // In an inbounds GEP with an offset that is nonnegative even when 4300 // interpreted as signed, assume there is no unsigned overflow. 4301 SDNodeFlags Flags; 4302 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 4303 Flags.setNoUnsignedWrap(true); 4304 4305 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4306 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4307 } 4308 } else { 4309 // IdxSize is the width of the arithmetic according to IR semantics. 4310 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4311 // (and fix up the result later). 4312 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4313 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4314 TypeSize ElementSize = 4315 GTI.getSequentialElementStride(DAG.getDataLayout()); 4316 // We intentionally mask away the high bits here; ElementSize may not 4317 // fit in IdxTy. 4318 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4319 bool ElementScalable = ElementSize.isScalable(); 4320 4321 // If this is a scalar constant or a splat vector of constants, 4322 // handle it quickly. 4323 const auto *C = dyn_cast<Constant>(Idx); 4324 if (C && isa<VectorType>(C->getType())) 4325 C = C->getSplatValue(); 4326 4327 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4328 if (CI && CI->isZero()) 4329 continue; 4330 if (CI && !ElementScalable) { 4331 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4332 LLVMContext &Context = *DAG.getContext(); 4333 SDValue OffsVal; 4334 if (IsVectorGEP) 4335 OffsVal = DAG.getConstant( 4336 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4337 else 4338 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4339 4340 // In an inbounds GEP with an offset that is nonnegative even when 4341 // interpreted as signed, assume there is no unsigned overflow. 4342 SDNodeFlags Flags; 4343 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4344 Flags.setNoUnsignedWrap(true); 4345 4346 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4347 4348 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4349 continue; 4350 } 4351 4352 // N = N + Idx * ElementMul; 4353 SDValue IdxN = getValue(Idx); 4354 4355 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4356 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4357 VectorElementCount); 4358 IdxN = DAG.getSplat(VT, dl, IdxN); 4359 } 4360 4361 // If the index is smaller or larger than intptr_t, truncate or extend 4362 // it. 4363 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4364 4365 if (ElementScalable) { 4366 EVT VScaleTy = N.getValueType().getScalarType(); 4367 SDValue VScale = DAG.getNode( 4368 ISD::VSCALE, dl, VScaleTy, 4369 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4370 if (IsVectorGEP) 4371 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4372 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4373 } else { 4374 // If this is a multiply by a power of two, turn it into a shl 4375 // immediately. This is a very common case. 4376 if (ElementMul != 1) { 4377 if (ElementMul.isPowerOf2()) { 4378 unsigned Amt = ElementMul.logBase2(); 4379 IdxN = DAG.getNode(ISD::SHL, dl, 4380 N.getValueType(), IdxN, 4381 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4382 } else { 4383 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4384 IdxN.getValueType()); 4385 IdxN = DAG.getNode(ISD::MUL, dl, 4386 N.getValueType(), IdxN, Scale); 4387 } 4388 } 4389 } 4390 4391 N = DAG.getNode(ISD::ADD, dl, 4392 N.getValueType(), N, IdxN); 4393 } 4394 } 4395 4396 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4397 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4398 if (IsVectorGEP) { 4399 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4400 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4401 } 4402 4403 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4404 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4405 4406 setValue(&I, N); 4407 } 4408 4409 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4410 // If this is a fixed sized alloca in the entry block of the function, 4411 // allocate it statically on the stack. 4412 if (FuncInfo.StaticAllocaMap.count(&I)) 4413 return; // getValue will auto-populate this. 4414 4415 SDLoc dl = getCurSDLoc(); 4416 Type *Ty = I.getAllocatedType(); 4417 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4418 auto &DL = DAG.getDataLayout(); 4419 TypeSize TySize = DL.getTypeAllocSize(Ty); 4420 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4421 4422 SDValue AllocSize = getValue(I.getArraySize()); 4423 4424 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4425 if (AllocSize.getValueType() != IntPtr) 4426 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4427 4428 if (TySize.isScalable()) 4429 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4430 DAG.getVScale(dl, IntPtr, 4431 APInt(IntPtr.getScalarSizeInBits(), 4432 TySize.getKnownMinValue()))); 4433 else { 4434 SDValue TySizeValue = 4435 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4436 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4437 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4438 } 4439 4440 // Handle alignment. If the requested alignment is less than or equal to 4441 // the stack alignment, ignore it. If the size is greater than or equal to 4442 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4443 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4444 if (*Alignment <= StackAlign) 4445 Alignment = std::nullopt; 4446 4447 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4448 // Round the size of the allocation up to the stack alignment size 4449 // by add SA-1 to the size. This doesn't overflow because we're computing 4450 // an address inside an alloca. 4451 SDNodeFlags Flags; 4452 Flags.setNoUnsignedWrap(true); 4453 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4454 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4455 4456 // Mask out the low bits for alignment purposes. 4457 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4458 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4459 4460 SDValue Ops[] = { 4461 getRoot(), AllocSize, 4462 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4463 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4464 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4465 setValue(&I, DSA); 4466 DAG.setRoot(DSA.getValue(1)); 4467 4468 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4469 } 4470 4471 static const MDNode *getRangeMetadata(const Instruction &I) { 4472 // If !noundef is not present, then !range violation results in a poison 4473 // value rather than immediate undefined behavior. In theory, transferring 4474 // these annotations to SDAG is fine, but in practice there are key SDAG 4475 // transforms that are known not to be poison-safe, such as folding logical 4476 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4477 // also present. 4478 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4479 return nullptr; 4480 return I.getMetadata(LLVMContext::MD_range); 4481 } 4482 4483 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4484 if (I.isAtomic()) 4485 return visitAtomicLoad(I); 4486 4487 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4488 const Value *SV = I.getOperand(0); 4489 if (TLI.supportSwiftError()) { 4490 // Swifterror values can come from either a function parameter with 4491 // swifterror attribute or an alloca with swifterror attribute. 4492 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4493 if (Arg->hasSwiftErrorAttr()) 4494 return visitLoadFromSwiftError(I); 4495 } 4496 4497 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4498 if (Alloca->isSwiftError()) 4499 return visitLoadFromSwiftError(I); 4500 } 4501 } 4502 4503 SDValue Ptr = getValue(SV); 4504 4505 Type *Ty = I.getType(); 4506 SmallVector<EVT, 4> ValueVTs, MemVTs; 4507 SmallVector<TypeSize, 4> Offsets; 4508 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4509 unsigned NumValues = ValueVTs.size(); 4510 if (NumValues == 0) 4511 return; 4512 4513 Align Alignment = I.getAlign(); 4514 AAMDNodes AAInfo = I.getAAMetadata(); 4515 const MDNode *Ranges = getRangeMetadata(I); 4516 bool isVolatile = I.isVolatile(); 4517 MachineMemOperand::Flags MMOFlags = 4518 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4519 4520 SDValue Root; 4521 bool ConstantMemory = false; 4522 if (isVolatile) 4523 // Serialize volatile loads with other side effects. 4524 Root = getRoot(); 4525 else if (NumValues > MaxParallelChains) 4526 Root = getMemoryRoot(); 4527 else if (AA && 4528 AA->pointsToConstantMemory(MemoryLocation( 4529 SV, 4530 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4531 AAInfo))) { 4532 // Do not serialize (non-volatile) loads of constant memory with anything. 4533 Root = DAG.getEntryNode(); 4534 ConstantMemory = true; 4535 MMOFlags |= MachineMemOperand::MOInvariant; 4536 } else { 4537 // Do not serialize non-volatile loads against each other. 4538 Root = DAG.getRoot(); 4539 } 4540 4541 SDLoc dl = getCurSDLoc(); 4542 4543 if (isVolatile) 4544 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4545 4546 SmallVector<SDValue, 4> Values(NumValues); 4547 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4548 4549 unsigned ChainI = 0; 4550 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4551 // Serializing loads here may result in excessive register pressure, and 4552 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4553 // could recover a bit by hoisting nodes upward in the chain by recognizing 4554 // they are side-effect free or do not alias. The optimizer should really 4555 // avoid this case by converting large object/array copies to llvm.memcpy 4556 // (MaxParallelChains should always remain as failsafe). 4557 if (ChainI == MaxParallelChains) { 4558 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4559 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4560 ArrayRef(Chains.data(), ChainI)); 4561 Root = Chain; 4562 ChainI = 0; 4563 } 4564 4565 // TODO: MachinePointerInfo only supports a fixed length offset. 4566 MachinePointerInfo PtrInfo = 4567 !Offsets[i].isScalable() || Offsets[i].isZero() 4568 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4569 : MachinePointerInfo(); 4570 4571 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4572 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4573 MMOFlags, AAInfo, Ranges); 4574 Chains[ChainI] = L.getValue(1); 4575 4576 if (MemVTs[i] != ValueVTs[i]) 4577 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4578 4579 Values[i] = L; 4580 } 4581 4582 if (!ConstantMemory) { 4583 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4584 ArrayRef(Chains.data(), ChainI)); 4585 if (isVolatile) 4586 DAG.setRoot(Chain); 4587 else 4588 PendingLoads.push_back(Chain); 4589 } 4590 4591 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4592 DAG.getVTList(ValueVTs), Values)); 4593 } 4594 4595 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4596 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4597 "call visitStoreToSwiftError when backend supports swifterror"); 4598 4599 SmallVector<EVT, 4> ValueVTs; 4600 SmallVector<uint64_t, 4> Offsets; 4601 const Value *SrcV = I.getOperand(0); 4602 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4603 SrcV->getType(), ValueVTs, &Offsets, 0); 4604 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4605 "expect a single EVT for swifterror"); 4606 4607 SDValue Src = getValue(SrcV); 4608 // Create a virtual register, then update the virtual register. 4609 Register VReg = 4610 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4611 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4612 // Chain can be getRoot or getControlRoot. 4613 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4614 SDValue(Src.getNode(), Src.getResNo())); 4615 DAG.setRoot(CopyNode); 4616 } 4617 4618 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4619 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4620 "call visitLoadFromSwiftError when backend supports swifterror"); 4621 4622 assert(!I.isVolatile() && 4623 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4624 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4625 "Support volatile, non temporal, invariant for load_from_swift_error"); 4626 4627 const Value *SV = I.getOperand(0); 4628 Type *Ty = I.getType(); 4629 assert( 4630 (!AA || 4631 !AA->pointsToConstantMemory(MemoryLocation( 4632 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4633 I.getAAMetadata()))) && 4634 "load_from_swift_error should not be constant memory"); 4635 4636 SmallVector<EVT, 4> ValueVTs; 4637 SmallVector<uint64_t, 4> Offsets; 4638 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4639 ValueVTs, &Offsets, 0); 4640 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4641 "expect a single EVT for swifterror"); 4642 4643 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4644 SDValue L = DAG.getCopyFromReg( 4645 getRoot(), getCurSDLoc(), 4646 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4647 4648 setValue(&I, L); 4649 } 4650 4651 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4652 if (I.isAtomic()) 4653 return visitAtomicStore(I); 4654 4655 const Value *SrcV = I.getOperand(0); 4656 const Value *PtrV = I.getOperand(1); 4657 4658 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4659 if (TLI.supportSwiftError()) { 4660 // Swifterror values can come from either a function parameter with 4661 // swifterror attribute or an alloca with swifterror attribute. 4662 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4663 if (Arg->hasSwiftErrorAttr()) 4664 return visitStoreToSwiftError(I); 4665 } 4666 4667 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4668 if (Alloca->isSwiftError()) 4669 return visitStoreToSwiftError(I); 4670 } 4671 } 4672 4673 SmallVector<EVT, 4> ValueVTs, MemVTs; 4674 SmallVector<TypeSize, 4> Offsets; 4675 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4676 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4677 unsigned NumValues = ValueVTs.size(); 4678 if (NumValues == 0) 4679 return; 4680 4681 // Get the lowered operands. Note that we do this after 4682 // checking if NumResults is zero, because with zero results 4683 // the operands won't have values in the map. 4684 SDValue Src = getValue(SrcV); 4685 SDValue Ptr = getValue(PtrV); 4686 4687 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4688 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4689 SDLoc dl = getCurSDLoc(); 4690 Align Alignment = I.getAlign(); 4691 AAMDNodes AAInfo = I.getAAMetadata(); 4692 4693 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4694 4695 unsigned ChainI = 0; 4696 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4697 // See visitLoad comments. 4698 if (ChainI == MaxParallelChains) { 4699 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4700 ArrayRef(Chains.data(), ChainI)); 4701 Root = Chain; 4702 ChainI = 0; 4703 } 4704 4705 // TODO: MachinePointerInfo only supports a fixed length offset. 4706 MachinePointerInfo PtrInfo = 4707 !Offsets[i].isScalable() || Offsets[i].isZero() 4708 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4709 : MachinePointerInfo(); 4710 4711 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4712 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4713 if (MemVTs[i] != ValueVTs[i]) 4714 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4715 SDValue St = 4716 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4717 Chains[ChainI] = St; 4718 } 4719 4720 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4721 ArrayRef(Chains.data(), ChainI)); 4722 setValue(&I, StoreNode); 4723 DAG.setRoot(StoreNode); 4724 } 4725 4726 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4727 bool IsCompressing) { 4728 SDLoc sdl = getCurSDLoc(); 4729 4730 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4731 Align &Alignment) { 4732 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4733 Src0 = I.getArgOperand(0); 4734 Ptr = I.getArgOperand(1); 4735 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue(); 4736 Mask = I.getArgOperand(3); 4737 }; 4738 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4739 Align &Alignment) { 4740 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4741 Src0 = I.getArgOperand(0); 4742 Ptr = I.getArgOperand(1); 4743 Mask = I.getArgOperand(2); 4744 Alignment = I.getParamAlign(1).valueOrOne(); 4745 }; 4746 4747 Value *PtrOperand, *MaskOperand, *Src0Operand; 4748 Align Alignment; 4749 if (IsCompressing) 4750 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4751 else 4752 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4753 4754 SDValue Ptr = getValue(PtrOperand); 4755 SDValue Src0 = getValue(Src0Operand); 4756 SDValue Mask = getValue(MaskOperand); 4757 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4758 4759 EVT VT = Src0.getValueType(); 4760 4761 auto MMOFlags = MachineMemOperand::MOStore; 4762 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4763 MMOFlags |= MachineMemOperand::MONonTemporal; 4764 4765 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4766 MachinePointerInfo(PtrOperand), MMOFlags, 4767 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4768 SDValue StoreNode = 4769 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4770 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4771 DAG.setRoot(StoreNode); 4772 setValue(&I, StoreNode); 4773 } 4774 4775 // Get a uniform base for the Gather/Scatter intrinsic. 4776 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4777 // We try to represent it as a base pointer + vector of indices. 4778 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4779 // The first operand of the GEP may be a single pointer or a vector of pointers 4780 // Example: 4781 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4782 // or 4783 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4784 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4785 // 4786 // When the first GEP operand is a single pointer - it is the uniform base we 4787 // are looking for. If first operand of the GEP is a splat vector - we 4788 // extract the splat value and use it as a uniform base. 4789 // In all other cases the function returns 'false'. 4790 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4791 ISD::MemIndexType &IndexType, SDValue &Scale, 4792 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4793 uint64_t ElemSize) { 4794 SelectionDAG& DAG = SDB->DAG; 4795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4796 const DataLayout &DL = DAG.getDataLayout(); 4797 4798 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4799 4800 // Handle splat constant pointer. 4801 if (auto *C = dyn_cast<Constant>(Ptr)) { 4802 C = C->getSplatValue(); 4803 if (!C) 4804 return false; 4805 4806 Base = SDB->getValue(C); 4807 4808 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4809 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4810 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4811 IndexType = ISD::SIGNED_SCALED; 4812 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4813 return true; 4814 } 4815 4816 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4817 if (!GEP || GEP->getParent() != CurBB) 4818 return false; 4819 4820 if (GEP->getNumOperands() != 2) 4821 return false; 4822 4823 const Value *BasePtr = GEP->getPointerOperand(); 4824 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4825 4826 // Make sure the base is scalar and the index is a vector. 4827 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4828 return false; 4829 4830 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4831 if (ScaleVal.isScalable()) 4832 return false; 4833 4834 // Target may not support the required addressing mode. 4835 if (ScaleVal != 1 && 4836 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4837 return false; 4838 4839 Base = SDB->getValue(BasePtr); 4840 Index = SDB->getValue(IndexVal); 4841 IndexType = ISD::SIGNED_SCALED; 4842 4843 Scale = 4844 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4845 return true; 4846 } 4847 4848 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4849 SDLoc sdl = getCurSDLoc(); 4850 4851 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4852 const Value *Ptr = I.getArgOperand(1); 4853 SDValue Src0 = getValue(I.getArgOperand(0)); 4854 SDValue Mask = getValue(I.getArgOperand(3)); 4855 EVT VT = Src0.getValueType(); 4856 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4857 ->getMaybeAlignValue() 4858 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4859 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4860 4861 SDValue Base; 4862 SDValue Index; 4863 ISD::MemIndexType IndexType; 4864 SDValue Scale; 4865 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4866 I.getParent(), VT.getScalarStoreSize()); 4867 4868 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4869 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4870 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4871 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4872 if (!UniformBase) { 4873 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4874 Index = getValue(Ptr); 4875 IndexType = ISD::SIGNED_SCALED; 4876 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4877 } 4878 4879 EVT IdxVT = Index.getValueType(); 4880 EVT EltTy = IdxVT.getVectorElementType(); 4881 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4882 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4883 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4884 } 4885 4886 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4887 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4888 Ops, MMO, IndexType, false); 4889 DAG.setRoot(Scatter); 4890 setValue(&I, Scatter); 4891 } 4892 4893 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4894 SDLoc sdl = getCurSDLoc(); 4895 4896 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4897 Align &Alignment) { 4898 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4899 Ptr = I.getArgOperand(0); 4900 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue(); 4901 Mask = I.getArgOperand(2); 4902 Src0 = I.getArgOperand(3); 4903 }; 4904 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4905 Align &Alignment) { 4906 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4907 Ptr = I.getArgOperand(0); 4908 Alignment = I.getParamAlign(0).valueOrOne(); 4909 Mask = I.getArgOperand(1); 4910 Src0 = I.getArgOperand(2); 4911 }; 4912 4913 Value *PtrOperand, *MaskOperand, *Src0Operand; 4914 Align Alignment; 4915 if (IsExpanding) 4916 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4917 else 4918 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4919 4920 SDValue Ptr = getValue(PtrOperand); 4921 SDValue Src0 = getValue(Src0Operand); 4922 SDValue Mask = getValue(MaskOperand); 4923 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4924 4925 EVT VT = Src0.getValueType(); 4926 AAMDNodes AAInfo = I.getAAMetadata(); 4927 const MDNode *Ranges = getRangeMetadata(I); 4928 4929 // Do not serialize masked loads of constant memory with anything. 4930 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4931 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4932 4933 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4934 4935 auto MMOFlags = MachineMemOperand::MOLoad; 4936 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4937 MMOFlags |= MachineMemOperand::MONonTemporal; 4938 4939 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4940 MachinePointerInfo(PtrOperand), MMOFlags, 4941 LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges); 4942 4943 SDValue Load = 4944 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4945 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4946 if (AddToChain) 4947 PendingLoads.push_back(Load.getValue(1)); 4948 setValue(&I, Load); 4949 } 4950 4951 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4952 SDLoc sdl = getCurSDLoc(); 4953 4954 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4955 const Value *Ptr = I.getArgOperand(0); 4956 SDValue Src0 = getValue(I.getArgOperand(3)); 4957 SDValue Mask = getValue(I.getArgOperand(2)); 4958 4959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4960 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4961 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4962 ->getMaybeAlignValue() 4963 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4964 4965 const MDNode *Ranges = getRangeMetadata(I); 4966 4967 SDValue Root = DAG.getRoot(); 4968 SDValue Base; 4969 SDValue Index; 4970 ISD::MemIndexType IndexType; 4971 SDValue Scale; 4972 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4973 I.getParent(), VT.getScalarStoreSize()); 4974 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4975 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4976 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4977 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(), 4978 Ranges); 4979 4980 if (!UniformBase) { 4981 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4982 Index = getValue(Ptr); 4983 IndexType = ISD::SIGNED_SCALED; 4984 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4985 } 4986 4987 EVT IdxVT = Index.getValueType(); 4988 EVT EltTy = IdxVT.getVectorElementType(); 4989 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4990 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4991 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4992 } 4993 4994 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4995 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4996 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4997 4998 PendingLoads.push_back(Gather.getValue(1)); 4999 setValue(&I, Gather); 5000 } 5001 5002 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 5003 SDLoc dl = getCurSDLoc(); 5004 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 5005 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 5006 SyncScope::ID SSID = I.getSyncScopeID(); 5007 5008 SDValue InChain = getRoot(); 5009 5010 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 5011 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 5012 5013 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5014 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5015 5016 MachineFunction &MF = DAG.getMachineFunction(); 5017 MachineMemOperand *MMO = MF.getMachineMemOperand( 5018 MachinePointerInfo(I.getPointerOperand()), Flags, 5019 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5020 AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering); 5021 5022 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 5023 dl, MemVT, VTs, InChain, 5024 getValue(I.getPointerOperand()), 5025 getValue(I.getCompareOperand()), 5026 getValue(I.getNewValOperand()), MMO); 5027 5028 SDValue OutChain = L.getValue(2); 5029 5030 setValue(&I, L); 5031 DAG.setRoot(OutChain); 5032 } 5033 5034 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 5035 SDLoc dl = getCurSDLoc(); 5036 ISD::NodeType NT; 5037 switch (I.getOperation()) { 5038 default: llvm_unreachable("Unknown atomicrmw operation"); 5039 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 5040 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 5041 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 5042 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 5043 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 5044 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 5045 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 5046 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 5047 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 5048 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 5049 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 5050 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 5051 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 5052 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 5053 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 5054 case AtomicRMWInst::UIncWrap: 5055 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 5056 break; 5057 case AtomicRMWInst::UDecWrap: 5058 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 5059 break; 5060 } 5061 AtomicOrdering Ordering = I.getOrdering(); 5062 SyncScope::ID SSID = I.getSyncScopeID(); 5063 5064 SDValue InChain = getRoot(); 5065 5066 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 5067 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5068 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5069 5070 MachineFunction &MF = DAG.getMachineFunction(); 5071 MachineMemOperand *MMO = MF.getMachineMemOperand( 5072 MachinePointerInfo(I.getPointerOperand()), Flags, 5073 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5074 AAMDNodes(), nullptr, SSID, Ordering); 5075 5076 SDValue L = 5077 DAG.getAtomic(NT, dl, MemVT, InChain, 5078 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 5079 MMO); 5080 5081 SDValue OutChain = L.getValue(1); 5082 5083 setValue(&I, L); 5084 DAG.setRoot(OutChain); 5085 } 5086 5087 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 5088 SDLoc dl = getCurSDLoc(); 5089 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5090 SDValue Ops[3]; 5091 Ops[0] = getRoot(); 5092 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 5093 TLI.getFenceOperandTy(DAG.getDataLayout())); 5094 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 5095 TLI.getFenceOperandTy(DAG.getDataLayout())); 5096 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 5097 setValue(&I, N); 5098 DAG.setRoot(N); 5099 } 5100 5101 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 5102 SDLoc dl = getCurSDLoc(); 5103 AtomicOrdering Order = I.getOrdering(); 5104 SyncScope::ID SSID = I.getSyncScopeID(); 5105 5106 SDValue InChain = getRoot(); 5107 5108 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5109 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5110 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 5111 5112 if (!TLI.supportsUnalignedAtomics() && 5113 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5114 report_fatal_error("Cannot generate unaligned atomic load"); 5115 5116 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 5117 5118 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5119 MachinePointerInfo(I.getPointerOperand()), Flags, 5120 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5121 nullptr, SSID, Order); 5122 5123 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 5124 5125 SDValue Ptr = getValue(I.getPointerOperand()); 5126 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 5127 Ptr, MMO); 5128 5129 SDValue OutChain = L.getValue(1); 5130 if (MemVT != VT) 5131 L = DAG.getPtrExtOrTrunc(L, dl, VT); 5132 5133 setValue(&I, L); 5134 DAG.setRoot(OutChain); 5135 } 5136 5137 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 5138 SDLoc dl = getCurSDLoc(); 5139 5140 AtomicOrdering Ordering = I.getOrdering(); 5141 SyncScope::ID SSID = I.getSyncScopeID(); 5142 5143 SDValue InChain = getRoot(); 5144 5145 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5146 EVT MemVT = 5147 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 5148 5149 if (!TLI.supportsUnalignedAtomics() && 5150 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5151 report_fatal_error("Cannot generate unaligned atomic store"); 5152 5153 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 5154 5155 MachineFunction &MF = DAG.getMachineFunction(); 5156 MachineMemOperand *MMO = MF.getMachineMemOperand( 5157 MachinePointerInfo(I.getPointerOperand()), Flags, 5158 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5159 nullptr, SSID, Ordering); 5160 5161 SDValue Val = getValue(I.getValueOperand()); 5162 if (Val.getValueType() != MemVT) 5163 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 5164 SDValue Ptr = getValue(I.getPointerOperand()); 5165 5166 SDValue OutChain = 5167 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 5168 5169 setValue(&I, OutChain); 5170 DAG.setRoot(OutChain); 5171 } 5172 5173 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 5174 /// node. 5175 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5176 unsigned Intrinsic) { 5177 // Ignore the callsite's attributes. A specific call site may be marked with 5178 // readnone, but the lowering code will expect the chain based on the 5179 // definition. 5180 const Function *F = I.getCalledFunction(); 5181 bool HasChain = !F->doesNotAccessMemory(); 5182 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 5183 5184 // Build the operand list. 5185 SmallVector<SDValue, 8> Ops; 5186 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5187 if (OnlyLoad) { 5188 // We don't need to serialize loads against other loads. 5189 Ops.push_back(DAG.getRoot()); 5190 } else { 5191 Ops.push_back(getRoot()); 5192 } 5193 } 5194 5195 // Info is set by getTgtMemIntrinsic 5196 TargetLowering::IntrinsicInfo Info; 5197 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5198 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5199 DAG.getMachineFunction(), 5200 Intrinsic); 5201 5202 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5203 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5204 Info.opc == ISD::INTRINSIC_W_CHAIN) 5205 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5206 TLI.getPointerTy(DAG.getDataLayout()))); 5207 5208 // Add all operands of the call to the operand list. 5209 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5210 const Value *Arg = I.getArgOperand(i); 5211 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5212 Ops.push_back(getValue(Arg)); 5213 continue; 5214 } 5215 5216 // Use TargetConstant instead of a regular constant for immarg. 5217 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5218 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5219 assert(CI->getBitWidth() <= 64 && 5220 "large intrinsic immediates not handled"); 5221 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5222 } else { 5223 Ops.push_back( 5224 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5225 } 5226 } 5227 5228 SmallVector<EVT, 4> ValueVTs; 5229 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5230 5231 if (HasChain) 5232 ValueVTs.push_back(MVT::Other); 5233 5234 SDVTList VTs = DAG.getVTList(ValueVTs); 5235 5236 // Propagate fast-math-flags from IR to node(s). 5237 SDNodeFlags Flags; 5238 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5239 Flags.copyFMF(*FPMO); 5240 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5241 5242 // Create the node. 5243 SDValue Result; 5244 5245 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) { 5246 auto *Token = Bundle->Inputs[0].get(); 5247 SDValue ConvControlToken = getValue(Token); 5248 assert(Ops.back().getValueType() != MVT::Glue && 5249 "Did not expected another glue node here."); 5250 ConvControlToken = 5251 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken); 5252 Ops.push_back(ConvControlToken); 5253 } 5254 5255 // In some cases, custom collection of operands from CallInst I may be needed. 5256 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5257 if (IsTgtIntrinsic) { 5258 // This is target intrinsic that touches memory 5259 // 5260 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5261 // didn't yield anything useful. 5262 MachinePointerInfo MPI; 5263 if (Info.ptrVal) 5264 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5265 else if (Info.fallbackAddressSpace) 5266 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5267 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5268 Info.memVT, MPI, Info.align, Info.flags, 5269 Info.size, I.getAAMetadata()); 5270 } else if (!HasChain) { 5271 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5272 } else if (!I.getType()->isVoidTy()) { 5273 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5274 } else { 5275 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5276 } 5277 5278 if (HasChain) { 5279 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5280 if (OnlyLoad) 5281 PendingLoads.push_back(Chain); 5282 else 5283 DAG.setRoot(Chain); 5284 } 5285 5286 if (!I.getType()->isVoidTy()) { 5287 if (!isa<VectorType>(I.getType())) 5288 Result = lowerRangeToAssertZExt(DAG, I, Result); 5289 5290 MaybeAlign Alignment = I.getRetAlign(); 5291 5292 // Insert `assertalign` node if there's an alignment. 5293 if (InsertAssertAlign && Alignment) { 5294 Result = 5295 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5296 } 5297 5298 setValue(&I, Result); 5299 } 5300 } 5301 5302 /// GetSignificand - Get the significand and build it into a floating-point 5303 /// number with exponent of 1: 5304 /// 5305 /// Op = (Op & 0x007fffff) | 0x3f800000; 5306 /// 5307 /// where Op is the hexadecimal representation of floating point value. 5308 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5309 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5310 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5311 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5312 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5313 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5314 } 5315 5316 /// GetExponent - Get the exponent: 5317 /// 5318 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5319 /// 5320 /// where Op is the hexadecimal representation of floating point value. 5321 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5322 const TargetLowering &TLI, const SDLoc &dl) { 5323 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5324 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5325 SDValue t1 = DAG.getNode( 5326 ISD::SRL, dl, MVT::i32, t0, 5327 DAG.getConstant(23, dl, 5328 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5329 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5330 DAG.getConstant(127, dl, MVT::i32)); 5331 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5332 } 5333 5334 /// getF32Constant - Get 32-bit floating point constant. 5335 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5336 const SDLoc &dl) { 5337 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5338 MVT::f32); 5339 } 5340 5341 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5342 SelectionDAG &DAG) { 5343 // TODO: What fast-math-flags should be set on the floating-point nodes? 5344 5345 // IntegerPartOfX = ((int32_t)(t0); 5346 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5347 5348 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5349 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5350 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5351 5352 // IntegerPartOfX <<= 23; 5353 IntegerPartOfX = 5354 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5355 DAG.getConstant(23, dl, 5356 DAG.getTargetLoweringInfo().getShiftAmountTy( 5357 MVT::i32, DAG.getDataLayout()))); 5358 5359 SDValue TwoToFractionalPartOfX; 5360 if (LimitFloatPrecision <= 6) { 5361 // For floating-point precision of 6: 5362 // 5363 // TwoToFractionalPartOfX = 5364 // 0.997535578f + 5365 // (0.735607626f + 0.252464424f * x) * x; 5366 // 5367 // error 0.0144103317, which is 6 bits 5368 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5369 getF32Constant(DAG, 0x3e814304, dl)); 5370 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5371 getF32Constant(DAG, 0x3f3c50c8, dl)); 5372 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5373 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5374 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5375 } else if (LimitFloatPrecision <= 12) { 5376 // For floating-point precision of 12: 5377 // 5378 // TwoToFractionalPartOfX = 5379 // 0.999892986f + 5380 // (0.696457318f + 5381 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5382 // 5383 // error 0.000107046256, which is 13 to 14 bits 5384 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5385 getF32Constant(DAG, 0x3da235e3, dl)); 5386 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5387 getF32Constant(DAG, 0x3e65b8f3, dl)); 5388 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5389 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5390 getF32Constant(DAG, 0x3f324b07, dl)); 5391 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5392 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5393 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5394 } else { // LimitFloatPrecision <= 18 5395 // For floating-point precision of 18: 5396 // 5397 // TwoToFractionalPartOfX = 5398 // 0.999999982f + 5399 // (0.693148872f + 5400 // (0.240227044f + 5401 // (0.554906021e-1f + 5402 // (0.961591928e-2f + 5403 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5404 // error 2.47208000*10^(-7), which is better than 18 bits 5405 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5406 getF32Constant(DAG, 0x3924b03e, dl)); 5407 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5408 getF32Constant(DAG, 0x3ab24b87, dl)); 5409 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5410 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5411 getF32Constant(DAG, 0x3c1d8c17, dl)); 5412 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5413 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5414 getF32Constant(DAG, 0x3d634a1d, dl)); 5415 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5416 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5417 getF32Constant(DAG, 0x3e75fe14, dl)); 5418 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5419 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5420 getF32Constant(DAG, 0x3f317234, dl)); 5421 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5422 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5423 getF32Constant(DAG, 0x3f800000, dl)); 5424 } 5425 5426 // Add the exponent into the result in integer domain. 5427 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5428 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5429 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5430 } 5431 5432 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5433 /// limited-precision mode. 5434 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5435 const TargetLowering &TLI, SDNodeFlags Flags) { 5436 if (Op.getValueType() == MVT::f32 && 5437 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5438 5439 // Put the exponent in the right bit position for later addition to the 5440 // final result: 5441 // 5442 // t0 = Op * log2(e) 5443 5444 // TODO: What fast-math-flags should be set here? 5445 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5446 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5447 return getLimitedPrecisionExp2(t0, dl, DAG); 5448 } 5449 5450 // No special expansion. 5451 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5452 } 5453 5454 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5455 /// limited-precision mode. 5456 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5457 const TargetLowering &TLI, SDNodeFlags Flags) { 5458 // TODO: What fast-math-flags should be set on the floating-point nodes? 5459 5460 if (Op.getValueType() == MVT::f32 && 5461 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5462 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5463 5464 // Scale the exponent by log(2). 5465 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5466 SDValue LogOfExponent = 5467 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5468 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5469 5470 // Get the significand and build it into a floating-point number with 5471 // exponent of 1. 5472 SDValue X = GetSignificand(DAG, Op1, dl); 5473 5474 SDValue LogOfMantissa; 5475 if (LimitFloatPrecision <= 6) { 5476 // For floating-point precision of 6: 5477 // 5478 // LogofMantissa = 5479 // -1.1609546f + 5480 // (1.4034025f - 0.23903021f * x) * x; 5481 // 5482 // error 0.0034276066, which is better than 8 bits 5483 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5484 getF32Constant(DAG, 0xbe74c456, dl)); 5485 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5486 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5487 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5488 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5489 getF32Constant(DAG, 0x3f949a29, dl)); 5490 } else if (LimitFloatPrecision <= 12) { 5491 // For floating-point precision of 12: 5492 // 5493 // LogOfMantissa = 5494 // -1.7417939f + 5495 // (2.8212026f + 5496 // (-1.4699568f + 5497 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5498 // 5499 // error 0.000061011436, which is 14 bits 5500 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5501 getF32Constant(DAG, 0xbd67b6d6, dl)); 5502 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5503 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5504 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5505 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5506 getF32Constant(DAG, 0x3fbc278b, dl)); 5507 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5508 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5509 getF32Constant(DAG, 0x40348e95, dl)); 5510 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5511 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5512 getF32Constant(DAG, 0x3fdef31a, dl)); 5513 } else { // LimitFloatPrecision <= 18 5514 // For floating-point precision of 18: 5515 // 5516 // LogOfMantissa = 5517 // -2.1072184f + 5518 // (4.2372794f + 5519 // (-3.7029485f + 5520 // (2.2781945f + 5521 // (-0.87823314f + 5522 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5523 // 5524 // error 0.0000023660568, which is better than 18 bits 5525 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5526 getF32Constant(DAG, 0xbc91e5ac, dl)); 5527 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5528 getF32Constant(DAG, 0x3e4350aa, dl)); 5529 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5530 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5531 getF32Constant(DAG, 0x3f60d3e3, dl)); 5532 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5533 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5534 getF32Constant(DAG, 0x4011cdf0, dl)); 5535 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5536 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5537 getF32Constant(DAG, 0x406cfd1c, dl)); 5538 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5539 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5540 getF32Constant(DAG, 0x408797cb, dl)); 5541 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5542 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5543 getF32Constant(DAG, 0x4006dcab, dl)); 5544 } 5545 5546 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5547 } 5548 5549 // No special expansion. 5550 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5551 } 5552 5553 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5554 /// limited-precision mode. 5555 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5556 const TargetLowering &TLI, SDNodeFlags Flags) { 5557 // TODO: What fast-math-flags should be set on the floating-point nodes? 5558 5559 if (Op.getValueType() == MVT::f32 && 5560 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5561 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5562 5563 // Get the exponent. 5564 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5565 5566 // Get the significand and build it into a floating-point number with 5567 // exponent of 1. 5568 SDValue X = GetSignificand(DAG, Op1, dl); 5569 5570 // Different possible minimax approximations of significand in 5571 // floating-point for various degrees of accuracy over [1,2]. 5572 SDValue Log2ofMantissa; 5573 if (LimitFloatPrecision <= 6) { 5574 // For floating-point precision of 6: 5575 // 5576 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5577 // 5578 // error 0.0049451742, which is more than 7 bits 5579 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5580 getF32Constant(DAG, 0xbeb08fe0, dl)); 5581 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5582 getF32Constant(DAG, 0x40019463, dl)); 5583 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5584 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5585 getF32Constant(DAG, 0x3fd6633d, dl)); 5586 } else if (LimitFloatPrecision <= 12) { 5587 // For floating-point precision of 12: 5588 // 5589 // Log2ofMantissa = 5590 // -2.51285454f + 5591 // (4.07009056f + 5592 // (-2.12067489f + 5593 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5594 // 5595 // error 0.0000876136000, which is better than 13 bits 5596 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5597 getF32Constant(DAG, 0xbda7262e, dl)); 5598 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5599 getF32Constant(DAG, 0x3f25280b, dl)); 5600 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5601 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5602 getF32Constant(DAG, 0x4007b923, dl)); 5603 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5604 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5605 getF32Constant(DAG, 0x40823e2f, dl)); 5606 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5607 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5608 getF32Constant(DAG, 0x4020d29c, dl)); 5609 } else { // LimitFloatPrecision <= 18 5610 // For floating-point precision of 18: 5611 // 5612 // Log2ofMantissa = 5613 // -3.0400495f + 5614 // (6.1129976f + 5615 // (-5.3420409f + 5616 // (3.2865683f + 5617 // (-1.2669343f + 5618 // (0.27515199f - 5619 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5620 // 5621 // error 0.0000018516, which is better than 18 bits 5622 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5623 getF32Constant(DAG, 0xbcd2769e, dl)); 5624 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5625 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5626 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5627 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5628 getF32Constant(DAG, 0x3fa22ae7, dl)); 5629 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5630 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5631 getF32Constant(DAG, 0x40525723, dl)); 5632 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5633 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5634 getF32Constant(DAG, 0x40aaf200, dl)); 5635 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5636 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5637 getF32Constant(DAG, 0x40c39dad, dl)); 5638 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5639 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5640 getF32Constant(DAG, 0x4042902c, dl)); 5641 } 5642 5643 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5644 } 5645 5646 // No special expansion. 5647 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5648 } 5649 5650 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5651 /// limited-precision mode. 5652 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5653 const TargetLowering &TLI, SDNodeFlags Flags) { 5654 // TODO: What fast-math-flags should be set on the floating-point nodes? 5655 5656 if (Op.getValueType() == MVT::f32 && 5657 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5658 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5659 5660 // Scale the exponent by log10(2) [0.30102999f]. 5661 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5662 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5663 getF32Constant(DAG, 0x3e9a209a, dl)); 5664 5665 // Get the significand and build it into a floating-point number with 5666 // exponent of 1. 5667 SDValue X = GetSignificand(DAG, Op1, dl); 5668 5669 SDValue Log10ofMantissa; 5670 if (LimitFloatPrecision <= 6) { 5671 // For floating-point precision of 6: 5672 // 5673 // Log10ofMantissa = 5674 // -0.50419619f + 5675 // (0.60948995f - 0.10380950f * x) * x; 5676 // 5677 // error 0.0014886165, which is 6 bits 5678 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5679 getF32Constant(DAG, 0xbdd49a13, dl)); 5680 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5681 getF32Constant(DAG, 0x3f1c0789, dl)); 5682 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5683 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5684 getF32Constant(DAG, 0x3f011300, dl)); 5685 } else if (LimitFloatPrecision <= 12) { 5686 // For floating-point precision of 12: 5687 // 5688 // Log10ofMantissa = 5689 // -0.64831180f + 5690 // (0.91751397f + 5691 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5692 // 5693 // error 0.00019228036, which is better than 12 bits 5694 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5695 getF32Constant(DAG, 0x3d431f31, dl)); 5696 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5697 getF32Constant(DAG, 0x3ea21fb2, dl)); 5698 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5699 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5700 getF32Constant(DAG, 0x3f6ae232, dl)); 5701 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5702 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5703 getF32Constant(DAG, 0x3f25f7c3, dl)); 5704 } else { // LimitFloatPrecision <= 18 5705 // For floating-point precision of 18: 5706 // 5707 // Log10ofMantissa = 5708 // -0.84299375f + 5709 // (1.5327582f + 5710 // (-1.0688956f + 5711 // (0.49102474f + 5712 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5713 // 5714 // error 0.0000037995730, which is better than 18 bits 5715 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5716 getF32Constant(DAG, 0x3c5d51ce, dl)); 5717 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5718 getF32Constant(DAG, 0x3e00685a, dl)); 5719 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5720 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5721 getF32Constant(DAG, 0x3efb6798, dl)); 5722 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5723 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5724 getF32Constant(DAG, 0x3f88d192, dl)); 5725 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5726 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5727 getF32Constant(DAG, 0x3fc4316c, dl)); 5728 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5729 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5730 getF32Constant(DAG, 0x3f57ce70, dl)); 5731 } 5732 5733 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5734 } 5735 5736 // No special expansion. 5737 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5738 } 5739 5740 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5741 /// limited-precision mode. 5742 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5743 const TargetLowering &TLI, SDNodeFlags Flags) { 5744 if (Op.getValueType() == MVT::f32 && 5745 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5746 return getLimitedPrecisionExp2(Op, dl, DAG); 5747 5748 // No special expansion. 5749 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5750 } 5751 5752 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5753 /// limited-precision mode with x == 10.0f. 5754 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5755 SelectionDAG &DAG, const TargetLowering &TLI, 5756 SDNodeFlags Flags) { 5757 bool IsExp10 = false; 5758 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5759 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5760 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5761 APFloat Ten(10.0f); 5762 IsExp10 = LHSC->isExactlyValue(Ten); 5763 } 5764 } 5765 5766 // TODO: What fast-math-flags should be set on the FMUL node? 5767 if (IsExp10) { 5768 // Put the exponent in the right bit position for later addition to the 5769 // final result: 5770 // 5771 // #define LOG2OF10 3.3219281f 5772 // t0 = Op * LOG2OF10; 5773 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5774 getF32Constant(DAG, 0x40549a78, dl)); 5775 return getLimitedPrecisionExp2(t0, dl, DAG); 5776 } 5777 5778 // No special expansion. 5779 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5780 } 5781 5782 /// ExpandPowI - Expand a llvm.powi intrinsic. 5783 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5784 SelectionDAG &DAG) { 5785 // If RHS is a constant, we can expand this out to a multiplication tree if 5786 // it's beneficial on the target, otherwise we end up lowering to a call to 5787 // __powidf2 (for example). 5788 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5789 unsigned Val = RHSC->getSExtValue(); 5790 5791 // powi(x, 0) -> 1.0 5792 if (Val == 0) 5793 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5794 5795 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5796 Val, DAG.shouldOptForSize())) { 5797 // Get the exponent as a positive value. 5798 if ((int)Val < 0) 5799 Val = -Val; 5800 // We use the simple binary decomposition method to generate the multiply 5801 // sequence. There are more optimal ways to do this (for example, 5802 // powi(x,15) generates one more multiply than it should), but this has 5803 // the benefit of being both really simple and much better than a libcall. 5804 SDValue Res; // Logically starts equal to 1.0 5805 SDValue CurSquare = LHS; 5806 // TODO: Intrinsics should have fast-math-flags that propagate to these 5807 // nodes. 5808 while (Val) { 5809 if (Val & 1) { 5810 if (Res.getNode()) 5811 Res = 5812 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5813 else 5814 Res = CurSquare; // 1.0*CurSquare. 5815 } 5816 5817 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5818 CurSquare, CurSquare); 5819 Val >>= 1; 5820 } 5821 5822 // If the original was negative, invert the result, producing 1/(x*x*x). 5823 if (RHSC->getSExtValue() < 0) 5824 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5825 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5826 return Res; 5827 } 5828 } 5829 5830 // Otherwise, expand to a libcall. 5831 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5832 } 5833 5834 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5835 SDValue LHS, SDValue RHS, SDValue Scale, 5836 SelectionDAG &DAG, const TargetLowering &TLI) { 5837 EVT VT = LHS.getValueType(); 5838 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5839 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5840 LLVMContext &Ctx = *DAG.getContext(); 5841 5842 // If the type is legal but the operation isn't, this node might survive all 5843 // the way to operation legalization. If we end up there and we do not have 5844 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5845 // node. 5846 5847 // Coax the legalizer into expanding the node during type legalization instead 5848 // by bumping the size by one bit. This will force it to Promote, enabling the 5849 // early expansion and avoiding the need to expand later. 5850 5851 // We don't have to do this if Scale is 0; that can always be expanded, unless 5852 // it's a saturating signed operation. Those can experience true integer 5853 // division overflow, a case which we must avoid. 5854 5855 // FIXME: We wouldn't have to do this (or any of the early 5856 // expansion/promotion) if it was possible to expand a libcall of an 5857 // illegal type during operation legalization. But it's not, so things 5858 // get a bit hacky. 5859 unsigned ScaleInt = Scale->getAsZExtVal(); 5860 if ((ScaleInt > 0 || (Saturating && Signed)) && 5861 (TLI.isTypeLegal(VT) || 5862 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5863 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5864 Opcode, VT, ScaleInt); 5865 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5866 EVT PromVT; 5867 if (VT.isScalarInteger()) 5868 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5869 else if (VT.isVector()) { 5870 PromVT = VT.getVectorElementType(); 5871 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5872 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5873 } else 5874 llvm_unreachable("Wrong VT for DIVFIX?"); 5875 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5876 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5877 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5878 // For saturating operations, we need to shift up the LHS to get the 5879 // proper saturation width, and then shift down again afterwards. 5880 if (Saturating) 5881 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5882 DAG.getConstant(1, DL, ShiftTy)); 5883 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5884 if (Saturating) 5885 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5886 DAG.getConstant(1, DL, ShiftTy)); 5887 return DAG.getZExtOrTrunc(Res, DL, VT); 5888 } 5889 } 5890 5891 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5892 } 5893 5894 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5895 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5896 static void 5897 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5898 const SDValue &N) { 5899 switch (N.getOpcode()) { 5900 case ISD::CopyFromReg: { 5901 SDValue Op = N.getOperand(1); 5902 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5903 Op.getValueType().getSizeInBits()); 5904 return; 5905 } 5906 case ISD::BITCAST: 5907 case ISD::AssertZext: 5908 case ISD::AssertSext: 5909 case ISD::TRUNCATE: 5910 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5911 return; 5912 case ISD::BUILD_PAIR: 5913 case ISD::BUILD_VECTOR: 5914 case ISD::CONCAT_VECTORS: 5915 for (SDValue Op : N->op_values()) 5916 getUnderlyingArgRegs(Regs, Op); 5917 return; 5918 default: 5919 return; 5920 } 5921 } 5922 5923 /// If the DbgValueInst is a dbg_value of a function argument, create the 5924 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5925 /// instruction selection, they will be inserted to the entry BB. 5926 /// We don't currently support this for variadic dbg_values, as they shouldn't 5927 /// appear for function arguments or in the prologue. 5928 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5929 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5930 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5931 const Argument *Arg = dyn_cast<Argument>(V); 5932 if (!Arg) 5933 return false; 5934 5935 MachineFunction &MF = DAG.getMachineFunction(); 5936 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5937 5938 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5939 // we've been asked to pursue. 5940 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5941 bool Indirect) { 5942 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5943 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5944 // pointing at the VReg, which will be patched up later. 5945 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5946 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5947 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5948 /* isKill */ false, /* isDead */ false, 5949 /* isUndef */ false, /* isEarlyClobber */ false, 5950 /* SubReg */ 0, /* isDebug */ true)}); 5951 5952 auto *NewDIExpr = FragExpr; 5953 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5954 // the DIExpression. 5955 if (Indirect) 5956 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5957 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5958 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5959 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5960 } else { 5961 // Create a completely standard DBG_VALUE. 5962 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5963 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5964 } 5965 }; 5966 5967 if (Kind == FuncArgumentDbgValueKind::Value) { 5968 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5969 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5970 // the entry block. 5971 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5972 if (!IsInEntryBlock) 5973 return false; 5974 5975 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5976 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5977 // variable that also is a param. 5978 // 5979 // Although, if we are at the top of the entry block already, we can still 5980 // emit using ArgDbgValue. This might catch some situations when the 5981 // dbg.value refers to an argument that isn't used in the entry block, so 5982 // any CopyToReg node would be optimized out and the only way to express 5983 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5984 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5985 // we should only emit as ArgDbgValue if the Variable is an argument to the 5986 // current function, and the dbg.value intrinsic is found in the entry 5987 // block. 5988 bool VariableIsFunctionInputArg = Variable->isParameter() && 5989 !DL->getInlinedAt(); 5990 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5991 if (!IsInPrologue && !VariableIsFunctionInputArg) 5992 return false; 5993 5994 // Here we assume that a function argument on IR level only can be used to 5995 // describe one input parameter on source level. If we for example have 5996 // source code like this 5997 // 5998 // struct A { long x, y; }; 5999 // void foo(struct A a, long b) { 6000 // ... 6001 // b = a.x; 6002 // ... 6003 // } 6004 // 6005 // and IR like this 6006 // 6007 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 6008 // entry: 6009 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 6010 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 6011 // call void @llvm.dbg.value(metadata i32 %b, "b", 6012 // ... 6013 // call void @llvm.dbg.value(metadata i32 %a1, "b" 6014 // ... 6015 // 6016 // then the last dbg.value is describing a parameter "b" using a value that 6017 // is an argument. But since we already has used %a1 to describe a parameter 6018 // we should not handle that last dbg.value here (that would result in an 6019 // incorrect hoisting of the DBG_VALUE to the function entry). 6020 // Notice that we allow one dbg.value per IR level argument, to accommodate 6021 // for the situation with fragments above. 6022 // If there is no node for the value being handled, we return true to skip 6023 // the normal generation of debug info, as it would kill existing debug 6024 // info for the parameter in case of duplicates. 6025 if (VariableIsFunctionInputArg) { 6026 unsigned ArgNo = Arg->getArgNo(); 6027 if (ArgNo >= FuncInfo.DescribedArgs.size()) 6028 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 6029 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 6030 return !NodeMap[V].getNode(); 6031 FuncInfo.DescribedArgs.set(ArgNo); 6032 } 6033 } 6034 6035 bool IsIndirect = false; 6036 std::optional<MachineOperand> Op; 6037 // Some arguments' frame index is recorded during argument lowering. 6038 int FI = FuncInfo.getArgumentFrameIndex(Arg); 6039 if (FI != std::numeric_limits<int>::max()) 6040 Op = MachineOperand::CreateFI(FI); 6041 6042 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 6043 if (!Op && N.getNode()) { 6044 getUnderlyingArgRegs(ArgRegsAndSizes, N); 6045 Register Reg; 6046 if (ArgRegsAndSizes.size() == 1) 6047 Reg = ArgRegsAndSizes.front().first; 6048 6049 if (Reg && Reg.isVirtual()) { 6050 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6051 Register PR = RegInfo.getLiveInPhysReg(Reg); 6052 if (PR) 6053 Reg = PR; 6054 } 6055 if (Reg) { 6056 Op = MachineOperand::CreateReg(Reg, false); 6057 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6058 } 6059 } 6060 6061 if (!Op && N.getNode()) { 6062 // Check if frame index is available. 6063 SDValue LCandidate = peekThroughBitcasts(N); 6064 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 6065 if (FrameIndexSDNode *FINode = 6066 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 6067 Op = MachineOperand::CreateFI(FINode->getIndex()); 6068 } 6069 6070 if (!Op) { 6071 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 6072 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 6073 SplitRegs) { 6074 unsigned Offset = 0; 6075 for (const auto &RegAndSize : SplitRegs) { 6076 // If the expression is already a fragment, the current register 6077 // offset+size might extend beyond the fragment. In this case, only 6078 // the register bits that are inside the fragment are relevant. 6079 int RegFragmentSizeInBits = RegAndSize.second; 6080 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 6081 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 6082 // The register is entirely outside the expression fragment, 6083 // so is irrelevant for debug info. 6084 if (Offset >= ExprFragmentSizeInBits) 6085 break; 6086 // The register is partially outside the expression fragment, only 6087 // the low bits within the fragment are relevant for debug info. 6088 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 6089 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 6090 } 6091 } 6092 6093 auto FragmentExpr = DIExpression::createFragmentExpression( 6094 Expr, Offset, RegFragmentSizeInBits); 6095 Offset += RegAndSize.second; 6096 // If a valid fragment expression cannot be created, the variable's 6097 // correct value cannot be determined and so it is set as Undef. 6098 if (!FragmentExpr) { 6099 SDDbgValue *SDV = DAG.getConstantDbgValue( 6100 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 6101 DAG.AddDbgValue(SDV, false); 6102 continue; 6103 } 6104 MachineInstr *NewMI = 6105 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 6106 Kind != FuncArgumentDbgValueKind::Value); 6107 FuncInfo.ArgDbgValues.push_back(NewMI); 6108 } 6109 }; 6110 6111 // Check if ValueMap has reg number. 6112 DenseMap<const Value *, Register>::const_iterator 6113 VMI = FuncInfo.ValueMap.find(V); 6114 if (VMI != FuncInfo.ValueMap.end()) { 6115 const auto &TLI = DAG.getTargetLoweringInfo(); 6116 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 6117 V->getType(), std::nullopt); 6118 if (RFV.occupiesMultipleRegs()) { 6119 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 6120 return true; 6121 } 6122 6123 Op = MachineOperand::CreateReg(VMI->second, false); 6124 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6125 } else if (ArgRegsAndSizes.size() > 1) { 6126 // This was split due to the calling convention, and no virtual register 6127 // mapping exists for the value. 6128 splitMultiRegDbgValue(ArgRegsAndSizes); 6129 return true; 6130 } 6131 } 6132 6133 if (!Op) 6134 return false; 6135 6136 assert(Variable->isValidLocationForIntrinsic(DL) && 6137 "Expected inlined-at fields to agree"); 6138 MachineInstr *NewMI = nullptr; 6139 6140 if (Op->isReg()) 6141 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 6142 else 6143 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 6144 Variable, Expr); 6145 6146 // Otherwise, use ArgDbgValues. 6147 FuncInfo.ArgDbgValues.push_back(NewMI); 6148 return true; 6149 } 6150 6151 /// Return the appropriate SDDbgValue based on N. 6152 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 6153 DILocalVariable *Variable, 6154 DIExpression *Expr, 6155 const DebugLoc &dl, 6156 unsigned DbgSDNodeOrder) { 6157 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 6158 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 6159 // stack slot locations. 6160 // 6161 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 6162 // debug values here after optimization: 6163 // 6164 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 6165 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 6166 // 6167 // Both describe the direct values of their associated variables. 6168 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 6169 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6170 } 6171 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 6172 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6173 } 6174 6175 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 6176 switch (Intrinsic) { 6177 case Intrinsic::smul_fix: 6178 return ISD::SMULFIX; 6179 case Intrinsic::umul_fix: 6180 return ISD::UMULFIX; 6181 case Intrinsic::smul_fix_sat: 6182 return ISD::SMULFIXSAT; 6183 case Intrinsic::umul_fix_sat: 6184 return ISD::UMULFIXSAT; 6185 case Intrinsic::sdiv_fix: 6186 return ISD::SDIVFIX; 6187 case Intrinsic::udiv_fix: 6188 return ISD::UDIVFIX; 6189 case Intrinsic::sdiv_fix_sat: 6190 return ISD::SDIVFIXSAT; 6191 case Intrinsic::udiv_fix_sat: 6192 return ISD::UDIVFIXSAT; 6193 default: 6194 llvm_unreachable("Unhandled fixed point intrinsic"); 6195 } 6196 } 6197 6198 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6199 const char *FunctionName) { 6200 assert(FunctionName && "FunctionName must not be nullptr"); 6201 SDValue Callee = DAG.getExternalSymbol( 6202 FunctionName, 6203 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6204 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6205 } 6206 6207 /// Given a @llvm.call.preallocated.setup, return the corresponding 6208 /// preallocated call. 6209 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6210 assert(cast<CallBase>(PreallocatedSetup) 6211 ->getCalledFunction() 6212 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6213 "expected call_preallocated_setup Value"); 6214 for (const auto *U : PreallocatedSetup->users()) { 6215 auto *UseCall = cast<CallBase>(U); 6216 const Function *Fn = UseCall->getCalledFunction(); 6217 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6218 return UseCall; 6219 } 6220 } 6221 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6222 } 6223 6224 /// If DI is a debug value with an EntryValue expression, lower it using the 6225 /// corresponding physical register of the associated Argument value 6226 /// (guaranteed to exist by the verifier). 6227 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6228 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6229 DIExpression *Expr, DebugLoc DbgLoc) { 6230 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6231 return false; 6232 6233 // These properties are guaranteed by the verifier. 6234 const Argument *Arg = cast<Argument>(Values[0]); 6235 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6236 6237 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6238 if (ArgIt == FuncInfo.ValueMap.end()) { 6239 LLVM_DEBUG( 6240 dbgs() << "Dropping dbg.value: expression is entry_value but " 6241 "couldn't find an associated register for the Argument\n"); 6242 return true; 6243 } 6244 Register ArgVReg = ArgIt->getSecond(); 6245 6246 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6247 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6248 SDDbgValue *SDV = DAG.getVRegDbgValue( 6249 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6250 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6251 return true; 6252 } 6253 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6254 "couldn't find a physical register\n"); 6255 return true; 6256 } 6257 6258 /// Lower the call to the specified intrinsic function. 6259 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I, 6260 unsigned Intrinsic) { 6261 SDLoc sdl = getCurSDLoc(); 6262 switch (Intrinsic) { 6263 case Intrinsic::experimental_convergence_anchor: 6264 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped)); 6265 break; 6266 case Intrinsic::experimental_convergence_entry: 6267 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped)); 6268 break; 6269 case Intrinsic::experimental_convergence_loop: { 6270 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl); 6271 auto *Token = Bundle->Inputs[0].get(); 6272 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped, 6273 getValue(Token))); 6274 break; 6275 } 6276 } 6277 } 6278 6279 /// Lower the call to the specified intrinsic function. 6280 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6281 unsigned Intrinsic) { 6282 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6283 SDLoc sdl = getCurSDLoc(); 6284 DebugLoc dl = getCurDebugLoc(); 6285 SDValue Res; 6286 6287 SDNodeFlags Flags; 6288 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6289 Flags.copyFMF(*FPOp); 6290 6291 switch (Intrinsic) { 6292 default: 6293 // By default, turn this into a target intrinsic node. 6294 visitTargetIntrinsic(I, Intrinsic); 6295 return; 6296 case Intrinsic::vscale: { 6297 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6298 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6299 return; 6300 } 6301 case Intrinsic::vastart: visitVAStart(I); return; 6302 case Intrinsic::vaend: visitVAEnd(I); return; 6303 case Intrinsic::vacopy: visitVACopy(I); return; 6304 case Intrinsic::returnaddress: 6305 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6306 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6307 getValue(I.getArgOperand(0)))); 6308 return; 6309 case Intrinsic::addressofreturnaddress: 6310 setValue(&I, 6311 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6312 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6313 return; 6314 case Intrinsic::sponentry: 6315 setValue(&I, 6316 DAG.getNode(ISD::SPONENTRY, sdl, 6317 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6318 return; 6319 case Intrinsic::frameaddress: 6320 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6321 TLI.getFrameIndexTy(DAG.getDataLayout()), 6322 getValue(I.getArgOperand(0)))); 6323 return; 6324 case Intrinsic::read_volatile_register: 6325 case Intrinsic::read_register: { 6326 Value *Reg = I.getArgOperand(0); 6327 SDValue Chain = getRoot(); 6328 SDValue RegName = 6329 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6330 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6331 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6332 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6333 setValue(&I, Res); 6334 DAG.setRoot(Res.getValue(1)); 6335 return; 6336 } 6337 case Intrinsic::write_register: { 6338 Value *Reg = I.getArgOperand(0); 6339 Value *RegValue = I.getArgOperand(1); 6340 SDValue Chain = getRoot(); 6341 SDValue RegName = 6342 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6343 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6344 RegName, getValue(RegValue))); 6345 return; 6346 } 6347 case Intrinsic::memcpy: { 6348 const auto &MCI = cast<MemCpyInst>(I); 6349 SDValue Op1 = getValue(I.getArgOperand(0)); 6350 SDValue Op2 = getValue(I.getArgOperand(1)); 6351 SDValue Op3 = getValue(I.getArgOperand(2)); 6352 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6353 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6354 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6355 Align Alignment = std::min(DstAlign, SrcAlign); 6356 bool isVol = MCI.isVolatile(); 6357 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6358 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6359 // node. 6360 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6361 SDValue MC = DAG.getMemcpy( 6362 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6363 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6364 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6365 updateDAGForMaybeTailCall(MC); 6366 return; 6367 } 6368 case Intrinsic::memcpy_inline: { 6369 const auto &MCI = cast<MemCpyInlineInst>(I); 6370 SDValue Dst = getValue(I.getArgOperand(0)); 6371 SDValue Src = getValue(I.getArgOperand(1)); 6372 SDValue Size = getValue(I.getArgOperand(2)); 6373 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6374 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6375 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6376 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6377 Align Alignment = std::min(DstAlign, SrcAlign); 6378 bool isVol = MCI.isVolatile(); 6379 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6380 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6381 // node. 6382 SDValue MC = DAG.getMemcpy( 6383 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6384 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6385 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6386 updateDAGForMaybeTailCall(MC); 6387 return; 6388 } 6389 case Intrinsic::memset: { 6390 const auto &MSI = cast<MemSetInst>(I); 6391 SDValue Op1 = getValue(I.getArgOperand(0)); 6392 SDValue Op2 = getValue(I.getArgOperand(1)); 6393 SDValue Op3 = getValue(I.getArgOperand(2)); 6394 // @llvm.memset defines 0 and 1 to both mean no alignment. 6395 Align Alignment = MSI.getDestAlign().valueOrOne(); 6396 bool isVol = MSI.isVolatile(); 6397 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6398 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6399 SDValue MS = DAG.getMemset( 6400 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6401 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6402 updateDAGForMaybeTailCall(MS); 6403 return; 6404 } 6405 case Intrinsic::memset_inline: { 6406 const auto &MSII = cast<MemSetInlineInst>(I); 6407 SDValue Dst = getValue(I.getArgOperand(0)); 6408 SDValue Value = getValue(I.getArgOperand(1)); 6409 SDValue Size = getValue(I.getArgOperand(2)); 6410 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6411 // @llvm.memset defines 0 and 1 to both mean no alignment. 6412 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6413 bool isVol = MSII.isVolatile(); 6414 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6415 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6416 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6417 /* AlwaysInline */ true, isTC, 6418 MachinePointerInfo(I.getArgOperand(0)), 6419 I.getAAMetadata()); 6420 updateDAGForMaybeTailCall(MC); 6421 return; 6422 } 6423 case Intrinsic::memmove: { 6424 const auto &MMI = cast<MemMoveInst>(I); 6425 SDValue Op1 = getValue(I.getArgOperand(0)); 6426 SDValue Op2 = getValue(I.getArgOperand(1)); 6427 SDValue Op3 = getValue(I.getArgOperand(2)); 6428 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6429 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6430 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6431 Align Alignment = std::min(DstAlign, SrcAlign); 6432 bool isVol = MMI.isVolatile(); 6433 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6434 // FIXME: Support passing different dest/src alignments to the memmove DAG 6435 // node. 6436 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6437 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6438 isTC, MachinePointerInfo(I.getArgOperand(0)), 6439 MachinePointerInfo(I.getArgOperand(1)), 6440 I.getAAMetadata(), AA); 6441 updateDAGForMaybeTailCall(MM); 6442 return; 6443 } 6444 case Intrinsic::memcpy_element_unordered_atomic: { 6445 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6446 SDValue Dst = getValue(MI.getRawDest()); 6447 SDValue Src = getValue(MI.getRawSource()); 6448 SDValue Length = getValue(MI.getLength()); 6449 6450 Type *LengthTy = MI.getLength()->getType(); 6451 unsigned ElemSz = MI.getElementSizeInBytes(); 6452 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6453 SDValue MC = 6454 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6455 isTC, MachinePointerInfo(MI.getRawDest()), 6456 MachinePointerInfo(MI.getRawSource())); 6457 updateDAGForMaybeTailCall(MC); 6458 return; 6459 } 6460 case Intrinsic::memmove_element_unordered_atomic: { 6461 auto &MI = cast<AtomicMemMoveInst>(I); 6462 SDValue Dst = getValue(MI.getRawDest()); 6463 SDValue Src = getValue(MI.getRawSource()); 6464 SDValue Length = getValue(MI.getLength()); 6465 6466 Type *LengthTy = MI.getLength()->getType(); 6467 unsigned ElemSz = MI.getElementSizeInBytes(); 6468 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6469 SDValue MC = 6470 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6471 isTC, MachinePointerInfo(MI.getRawDest()), 6472 MachinePointerInfo(MI.getRawSource())); 6473 updateDAGForMaybeTailCall(MC); 6474 return; 6475 } 6476 case Intrinsic::memset_element_unordered_atomic: { 6477 auto &MI = cast<AtomicMemSetInst>(I); 6478 SDValue Dst = getValue(MI.getRawDest()); 6479 SDValue Val = getValue(MI.getValue()); 6480 SDValue Length = getValue(MI.getLength()); 6481 6482 Type *LengthTy = MI.getLength()->getType(); 6483 unsigned ElemSz = MI.getElementSizeInBytes(); 6484 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6485 SDValue MC = 6486 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6487 isTC, MachinePointerInfo(MI.getRawDest())); 6488 updateDAGForMaybeTailCall(MC); 6489 return; 6490 } 6491 case Intrinsic::call_preallocated_setup: { 6492 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6493 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6494 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6495 getRoot(), SrcValue); 6496 setValue(&I, Res); 6497 DAG.setRoot(Res); 6498 return; 6499 } 6500 case Intrinsic::call_preallocated_arg: { 6501 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6502 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6503 SDValue Ops[3]; 6504 Ops[0] = getRoot(); 6505 Ops[1] = SrcValue; 6506 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6507 MVT::i32); // arg index 6508 SDValue Res = DAG.getNode( 6509 ISD::PREALLOCATED_ARG, sdl, 6510 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6511 setValue(&I, Res); 6512 DAG.setRoot(Res.getValue(1)); 6513 return; 6514 } 6515 case Intrinsic::dbg_declare: { 6516 const auto &DI = cast<DbgDeclareInst>(I); 6517 // Debug intrinsics are handled separately in assignment tracking mode. 6518 // Some intrinsics are handled right after Argument lowering. 6519 if (AssignmentTrackingEnabled || 6520 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6521 return; 6522 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6523 DILocalVariable *Variable = DI.getVariable(); 6524 DIExpression *Expression = DI.getExpression(); 6525 dropDanglingDebugInfo(Variable, Expression); 6526 // Assume dbg.declare can not currently use DIArgList, i.e. 6527 // it is non-variadic. 6528 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6529 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6530 DI.getDebugLoc()); 6531 return; 6532 } 6533 case Intrinsic::dbg_label: { 6534 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6535 DILabel *Label = DI.getLabel(); 6536 assert(Label && "Missing label"); 6537 6538 SDDbgLabel *SDV; 6539 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6540 DAG.AddDbgLabel(SDV); 6541 return; 6542 } 6543 case Intrinsic::dbg_assign: { 6544 // Debug intrinsics are handled seperately in assignment tracking mode. 6545 if (AssignmentTrackingEnabled) 6546 return; 6547 // If assignment tracking hasn't been enabled then fall through and treat 6548 // the dbg.assign as a dbg.value. 6549 [[fallthrough]]; 6550 } 6551 case Intrinsic::dbg_value: { 6552 // Debug intrinsics are handled seperately in assignment tracking mode. 6553 if (AssignmentTrackingEnabled) 6554 return; 6555 const DbgValueInst &DI = cast<DbgValueInst>(I); 6556 assert(DI.getVariable() && "Missing variable"); 6557 6558 DILocalVariable *Variable = DI.getVariable(); 6559 DIExpression *Expression = DI.getExpression(); 6560 dropDanglingDebugInfo(Variable, Expression); 6561 6562 if (DI.isKillLocation()) { 6563 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6564 return; 6565 } 6566 6567 SmallVector<Value *, 4> Values(DI.getValues()); 6568 if (Values.empty()) 6569 return; 6570 6571 bool IsVariadic = DI.hasArgList(); 6572 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6573 SDNodeOrder, IsVariadic)) 6574 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6575 DI.getDebugLoc(), SDNodeOrder); 6576 return; 6577 } 6578 6579 case Intrinsic::eh_typeid_for: { 6580 // Find the type id for the given typeinfo. 6581 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6582 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6583 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6584 setValue(&I, Res); 6585 return; 6586 } 6587 6588 case Intrinsic::eh_return_i32: 6589 case Intrinsic::eh_return_i64: 6590 DAG.getMachineFunction().setCallsEHReturn(true); 6591 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6592 MVT::Other, 6593 getControlRoot(), 6594 getValue(I.getArgOperand(0)), 6595 getValue(I.getArgOperand(1)))); 6596 return; 6597 case Intrinsic::eh_unwind_init: 6598 DAG.getMachineFunction().setCallsUnwindInit(true); 6599 return; 6600 case Intrinsic::eh_dwarf_cfa: 6601 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6602 TLI.getPointerTy(DAG.getDataLayout()), 6603 getValue(I.getArgOperand(0)))); 6604 return; 6605 case Intrinsic::eh_sjlj_callsite: { 6606 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6607 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6608 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6609 6610 MMI.setCurrentCallSite(CI->getZExtValue()); 6611 return; 6612 } 6613 case Intrinsic::eh_sjlj_functioncontext: { 6614 // Get and store the index of the function context. 6615 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6616 AllocaInst *FnCtx = 6617 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6618 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6619 MFI.setFunctionContextIndex(FI); 6620 return; 6621 } 6622 case Intrinsic::eh_sjlj_setjmp: { 6623 SDValue Ops[2]; 6624 Ops[0] = getRoot(); 6625 Ops[1] = getValue(I.getArgOperand(0)); 6626 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6627 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6628 setValue(&I, Op.getValue(0)); 6629 DAG.setRoot(Op.getValue(1)); 6630 return; 6631 } 6632 case Intrinsic::eh_sjlj_longjmp: 6633 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6634 getRoot(), getValue(I.getArgOperand(0)))); 6635 return; 6636 case Intrinsic::eh_sjlj_setup_dispatch: 6637 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6638 getRoot())); 6639 return; 6640 case Intrinsic::masked_gather: 6641 visitMaskedGather(I); 6642 return; 6643 case Intrinsic::masked_load: 6644 visitMaskedLoad(I); 6645 return; 6646 case Intrinsic::masked_scatter: 6647 visitMaskedScatter(I); 6648 return; 6649 case Intrinsic::masked_store: 6650 visitMaskedStore(I); 6651 return; 6652 case Intrinsic::masked_expandload: 6653 visitMaskedLoad(I, true /* IsExpanding */); 6654 return; 6655 case Intrinsic::masked_compressstore: 6656 visitMaskedStore(I, true /* IsCompressing */); 6657 return; 6658 case Intrinsic::powi: 6659 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6660 getValue(I.getArgOperand(1)), DAG)); 6661 return; 6662 case Intrinsic::log: 6663 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6664 return; 6665 case Intrinsic::log2: 6666 setValue(&I, 6667 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6668 return; 6669 case Intrinsic::log10: 6670 setValue(&I, 6671 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6672 return; 6673 case Intrinsic::exp: 6674 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6675 return; 6676 case Intrinsic::exp2: 6677 setValue(&I, 6678 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6679 return; 6680 case Intrinsic::pow: 6681 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6682 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6683 return; 6684 case Intrinsic::sqrt: 6685 case Intrinsic::fabs: 6686 case Intrinsic::sin: 6687 case Intrinsic::cos: 6688 case Intrinsic::exp10: 6689 case Intrinsic::floor: 6690 case Intrinsic::ceil: 6691 case Intrinsic::trunc: 6692 case Intrinsic::rint: 6693 case Intrinsic::nearbyint: 6694 case Intrinsic::round: 6695 case Intrinsic::roundeven: 6696 case Intrinsic::canonicalize: { 6697 unsigned Opcode; 6698 switch (Intrinsic) { 6699 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6700 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6701 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6702 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6703 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6704 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6705 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6706 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6707 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6708 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6709 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6710 case Intrinsic::round: Opcode = ISD::FROUND; break; 6711 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6712 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6713 } 6714 6715 setValue(&I, DAG.getNode(Opcode, sdl, 6716 getValue(I.getArgOperand(0)).getValueType(), 6717 getValue(I.getArgOperand(0)), Flags)); 6718 return; 6719 } 6720 case Intrinsic::lround: 6721 case Intrinsic::llround: 6722 case Intrinsic::lrint: 6723 case Intrinsic::llrint: { 6724 unsigned Opcode; 6725 switch (Intrinsic) { 6726 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6727 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6728 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6729 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6730 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6731 } 6732 6733 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6734 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6735 getValue(I.getArgOperand(0)))); 6736 return; 6737 } 6738 case Intrinsic::minnum: 6739 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6740 getValue(I.getArgOperand(0)).getValueType(), 6741 getValue(I.getArgOperand(0)), 6742 getValue(I.getArgOperand(1)), Flags)); 6743 return; 6744 case Intrinsic::maxnum: 6745 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6746 getValue(I.getArgOperand(0)).getValueType(), 6747 getValue(I.getArgOperand(0)), 6748 getValue(I.getArgOperand(1)), Flags)); 6749 return; 6750 case Intrinsic::minimum: 6751 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6752 getValue(I.getArgOperand(0)).getValueType(), 6753 getValue(I.getArgOperand(0)), 6754 getValue(I.getArgOperand(1)), Flags)); 6755 return; 6756 case Intrinsic::maximum: 6757 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6758 getValue(I.getArgOperand(0)).getValueType(), 6759 getValue(I.getArgOperand(0)), 6760 getValue(I.getArgOperand(1)), Flags)); 6761 return; 6762 case Intrinsic::copysign: 6763 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6764 getValue(I.getArgOperand(0)).getValueType(), 6765 getValue(I.getArgOperand(0)), 6766 getValue(I.getArgOperand(1)), Flags)); 6767 return; 6768 case Intrinsic::ldexp: 6769 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6770 getValue(I.getArgOperand(0)).getValueType(), 6771 getValue(I.getArgOperand(0)), 6772 getValue(I.getArgOperand(1)), Flags)); 6773 return; 6774 case Intrinsic::frexp: { 6775 SmallVector<EVT, 2> ValueVTs; 6776 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6777 SDVTList VTs = DAG.getVTList(ValueVTs); 6778 setValue(&I, 6779 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6780 return; 6781 } 6782 case Intrinsic::arithmetic_fence: { 6783 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6784 getValue(I.getArgOperand(0)).getValueType(), 6785 getValue(I.getArgOperand(0)), Flags)); 6786 return; 6787 } 6788 case Intrinsic::fma: 6789 setValue(&I, DAG.getNode( 6790 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6791 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6792 getValue(I.getArgOperand(2)), Flags)); 6793 return; 6794 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6795 case Intrinsic::INTRINSIC: 6796 #include "llvm/IR/ConstrainedOps.def" 6797 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6798 return; 6799 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6800 #include "llvm/IR/VPIntrinsics.def" 6801 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6802 return; 6803 case Intrinsic::fptrunc_round: { 6804 // Get the last argument, the metadata and convert it to an integer in the 6805 // call 6806 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6807 std::optional<RoundingMode> RoundMode = 6808 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6809 6810 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6811 6812 // Propagate fast-math-flags from IR to node(s). 6813 SDNodeFlags Flags; 6814 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6815 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6816 6817 SDValue Result; 6818 Result = DAG.getNode( 6819 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6820 DAG.getTargetConstant((int)*RoundMode, sdl, 6821 TLI.getPointerTy(DAG.getDataLayout()))); 6822 setValue(&I, Result); 6823 6824 return; 6825 } 6826 case Intrinsic::fmuladd: { 6827 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6828 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6829 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6830 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6831 getValue(I.getArgOperand(0)).getValueType(), 6832 getValue(I.getArgOperand(0)), 6833 getValue(I.getArgOperand(1)), 6834 getValue(I.getArgOperand(2)), Flags)); 6835 } else { 6836 // TODO: Intrinsic calls should have fast-math-flags. 6837 SDValue Mul = DAG.getNode( 6838 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6839 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6840 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6841 getValue(I.getArgOperand(0)).getValueType(), 6842 Mul, getValue(I.getArgOperand(2)), Flags); 6843 setValue(&I, Add); 6844 } 6845 return; 6846 } 6847 case Intrinsic::convert_to_fp16: 6848 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6849 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6850 getValue(I.getArgOperand(0)), 6851 DAG.getTargetConstant(0, sdl, 6852 MVT::i32)))); 6853 return; 6854 case Intrinsic::convert_from_fp16: 6855 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6856 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6857 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6858 getValue(I.getArgOperand(0))))); 6859 return; 6860 case Intrinsic::fptosi_sat: { 6861 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6862 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6863 getValue(I.getArgOperand(0)), 6864 DAG.getValueType(VT.getScalarType()))); 6865 return; 6866 } 6867 case Intrinsic::fptoui_sat: { 6868 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6869 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6870 getValue(I.getArgOperand(0)), 6871 DAG.getValueType(VT.getScalarType()))); 6872 return; 6873 } 6874 case Intrinsic::set_rounding: 6875 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6876 {getRoot(), getValue(I.getArgOperand(0))}); 6877 setValue(&I, Res); 6878 DAG.setRoot(Res.getValue(0)); 6879 return; 6880 case Intrinsic::is_fpclass: { 6881 const DataLayout DLayout = DAG.getDataLayout(); 6882 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6883 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6884 FPClassTest Test = static_cast<FPClassTest>( 6885 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6886 MachineFunction &MF = DAG.getMachineFunction(); 6887 const Function &F = MF.getFunction(); 6888 SDValue Op = getValue(I.getArgOperand(0)); 6889 SDNodeFlags Flags; 6890 Flags.setNoFPExcept( 6891 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6892 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6893 // expansion can use illegal types. Making expansion early allows 6894 // legalizing these types prior to selection. 6895 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6896 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6897 setValue(&I, Result); 6898 return; 6899 } 6900 6901 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6902 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6903 setValue(&I, V); 6904 return; 6905 } 6906 case Intrinsic::get_fpenv: { 6907 const DataLayout DLayout = DAG.getDataLayout(); 6908 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6909 Align TempAlign = DAG.getEVTAlign(EnvVT); 6910 SDValue Chain = getRoot(); 6911 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6912 // and temporary storage in stack. 6913 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6914 Res = DAG.getNode( 6915 ISD::GET_FPENV, sdl, 6916 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6917 MVT::Other), 6918 Chain); 6919 } else { 6920 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6921 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6922 auto MPI = 6923 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6924 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6925 MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(), 6926 TempAlign); 6927 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6928 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6929 } 6930 setValue(&I, Res); 6931 DAG.setRoot(Res.getValue(1)); 6932 return; 6933 } 6934 case Intrinsic::set_fpenv: { 6935 const DataLayout DLayout = DAG.getDataLayout(); 6936 SDValue Env = getValue(I.getArgOperand(0)); 6937 EVT EnvVT = Env.getValueType(); 6938 Align TempAlign = DAG.getEVTAlign(EnvVT); 6939 SDValue Chain = getRoot(); 6940 // If SET_FPENV is custom or legal, use it. Otherwise use loading 6941 // environment from memory. 6942 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6943 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 6944 } else { 6945 // Allocate space in stack, copy environment bits into it and use this 6946 // memory in SET_FPENV_MEM. 6947 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6948 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6949 auto MPI = 6950 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6951 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 6952 MachineMemOperand::MOStore); 6953 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6954 MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(), 6955 TempAlign); 6956 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6957 } 6958 DAG.setRoot(Chain); 6959 return; 6960 } 6961 case Intrinsic::reset_fpenv: 6962 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 6963 return; 6964 case Intrinsic::get_fpmode: 6965 Res = DAG.getNode( 6966 ISD::GET_FPMODE, sdl, 6967 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6968 MVT::Other), 6969 DAG.getRoot()); 6970 setValue(&I, Res); 6971 DAG.setRoot(Res.getValue(1)); 6972 return; 6973 case Intrinsic::set_fpmode: 6974 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 6975 getValue(I.getArgOperand(0))); 6976 DAG.setRoot(Res); 6977 return; 6978 case Intrinsic::reset_fpmode: { 6979 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 6980 DAG.setRoot(Res); 6981 return; 6982 } 6983 case Intrinsic::pcmarker: { 6984 SDValue Tmp = getValue(I.getArgOperand(0)); 6985 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6986 return; 6987 } 6988 case Intrinsic::readcyclecounter: { 6989 SDValue Op = getRoot(); 6990 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6991 DAG.getVTList(MVT::i64, MVT::Other), Op); 6992 setValue(&I, Res); 6993 DAG.setRoot(Res.getValue(1)); 6994 return; 6995 } 6996 case Intrinsic::readsteadycounter: { 6997 SDValue Op = getRoot(); 6998 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 6999 DAG.getVTList(MVT::i64, MVT::Other), Op); 7000 setValue(&I, Res); 7001 DAG.setRoot(Res.getValue(1)); 7002 return; 7003 } 7004 case Intrinsic::bitreverse: 7005 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 7006 getValue(I.getArgOperand(0)).getValueType(), 7007 getValue(I.getArgOperand(0)))); 7008 return; 7009 case Intrinsic::bswap: 7010 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 7011 getValue(I.getArgOperand(0)).getValueType(), 7012 getValue(I.getArgOperand(0)))); 7013 return; 7014 case Intrinsic::cttz: { 7015 SDValue Arg = getValue(I.getArgOperand(0)); 7016 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7017 EVT Ty = Arg.getValueType(); 7018 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 7019 sdl, Ty, Arg)); 7020 return; 7021 } 7022 case Intrinsic::ctlz: { 7023 SDValue Arg = getValue(I.getArgOperand(0)); 7024 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7025 EVT Ty = Arg.getValueType(); 7026 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 7027 sdl, Ty, Arg)); 7028 return; 7029 } 7030 case Intrinsic::ctpop: { 7031 SDValue Arg = getValue(I.getArgOperand(0)); 7032 EVT Ty = Arg.getValueType(); 7033 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 7034 return; 7035 } 7036 case Intrinsic::fshl: 7037 case Intrinsic::fshr: { 7038 bool IsFSHL = Intrinsic == Intrinsic::fshl; 7039 SDValue X = getValue(I.getArgOperand(0)); 7040 SDValue Y = getValue(I.getArgOperand(1)); 7041 SDValue Z = getValue(I.getArgOperand(2)); 7042 EVT VT = X.getValueType(); 7043 7044 if (X == Y) { 7045 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 7046 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 7047 } else { 7048 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 7049 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 7050 } 7051 return; 7052 } 7053 case Intrinsic::sadd_sat: { 7054 SDValue Op1 = getValue(I.getArgOperand(0)); 7055 SDValue Op2 = getValue(I.getArgOperand(1)); 7056 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7057 return; 7058 } 7059 case Intrinsic::uadd_sat: { 7060 SDValue Op1 = getValue(I.getArgOperand(0)); 7061 SDValue Op2 = getValue(I.getArgOperand(1)); 7062 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7063 return; 7064 } 7065 case Intrinsic::ssub_sat: { 7066 SDValue Op1 = getValue(I.getArgOperand(0)); 7067 SDValue Op2 = getValue(I.getArgOperand(1)); 7068 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7069 return; 7070 } 7071 case Intrinsic::usub_sat: { 7072 SDValue Op1 = getValue(I.getArgOperand(0)); 7073 SDValue Op2 = getValue(I.getArgOperand(1)); 7074 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7075 return; 7076 } 7077 case Intrinsic::sshl_sat: { 7078 SDValue Op1 = getValue(I.getArgOperand(0)); 7079 SDValue Op2 = getValue(I.getArgOperand(1)); 7080 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7081 return; 7082 } 7083 case Intrinsic::ushl_sat: { 7084 SDValue Op1 = getValue(I.getArgOperand(0)); 7085 SDValue Op2 = getValue(I.getArgOperand(1)); 7086 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7087 return; 7088 } 7089 case Intrinsic::smul_fix: 7090 case Intrinsic::umul_fix: 7091 case Intrinsic::smul_fix_sat: 7092 case Intrinsic::umul_fix_sat: { 7093 SDValue Op1 = getValue(I.getArgOperand(0)); 7094 SDValue Op2 = getValue(I.getArgOperand(1)); 7095 SDValue Op3 = getValue(I.getArgOperand(2)); 7096 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7097 Op1.getValueType(), Op1, Op2, Op3)); 7098 return; 7099 } 7100 case Intrinsic::sdiv_fix: 7101 case Intrinsic::udiv_fix: 7102 case Intrinsic::sdiv_fix_sat: 7103 case Intrinsic::udiv_fix_sat: { 7104 SDValue Op1 = getValue(I.getArgOperand(0)); 7105 SDValue Op2 = getValue(I.getArgOperand(1)); 7106 SDValue Op3 = getValue(I.getArgOperand(2)); 7107 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7108 Op1, Op2, Op3, DAG, TLI)); 7109 return; 7110 } 7111 case Intrinsic::smax: { 7112 SDValue Op1 = getValue(I.getArgOperand(0)); 7113 SDValue Op2 = getValue(I.getArgOperand(1)); 7114 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 7115 return; 7116 } 7117 case Intrinsic::smin: { 7118 SDValue Op1 = getValue(I.getArgOperand(0)); 7119 SDValue Op2 = getValue(I.getArgOperand(1)); 7120 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 7121 return; 7122 } 7123 case Intrinsic::umax: { 7124 SDValue Op1 = getValue(I.getArgOperand(0)); 7125 SDValue Op2 = getValue(I.getArgOperand(1)); 7126 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 7127 return; 7128 } 7129 case Intrinsic::umin: { 7130 SDValue Op1 = getValue(I.getArgOperand(0)); 7131 SDValue Op2 = getValue(I.getArgOperand(1)); 7132 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 7133 return; 7134 } 7135 case Intrinsic::abs: { 7136 // TODO: Preserve "int min is poison" arg in SDAG? 7137 SDValue Op1 = getValue(I.getArgOperand(0)); 7138 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 7139 return; 7140 } 7141 case Intrinsic::stacksave: { 7142 SDValue Op = getRoot(); 7143 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7144 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 7145 setValue(&I, Res); 7146 DAG.setRoot(Res.getValue(1)); 7147 return; 7148 } 7149 case Intrinsic::stackrestore: 7150 Res = getValue(I.getArgOperand(0)); 7151 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 7152 return; 7153 case Intrinsic::get_dynamic_area_offset: { 7154 SDValue Op = getRoot(); 7155 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7156 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7157 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 7158 // target. 7159 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 7160 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 7161 " intrinsic!"); 7162 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 7163 Op); 7164 DAG.setRoot(Op); 7165 setValue(&I, Res); 7166 return; 7167 } 7168 case Intrinsic::stackguard: { 7169 MachineFunction &MF = DAG.getMachineFunction(); 7170 const Module &M = *MF.getFunction().getParent(); 7171 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7172 SDValue Chain = getRoot(); 7173 if (TLI.useLoadStackGuardNode()) { 7174 Res = getLoadStackGuard(DAG, sdl, Chain); 7175 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 7176 } else { 7177 const Value *Global = TLI.getSDagStackGuard(M); 7178 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7179 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7180 MachinePointerInfo(Global, 0), Align, 7181 MachineMemOperand::MOVolatile); 7182 } 7183 if (TLI.useStackGuardXorFP()) 7184 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7185 DAG.setRoot(Chain); 7186 setValue(&I, Res); 7187 return; 7188 } 7189 case Intrinsic::stackprotector: { 7190 // Emit code into the DAG to store the stack guard onto the stack. 7191 MachineFunction &MF = DAG.getMachineFunction(); 7192 MachineFrameInfo &MFI = MF.getFrameInfo(); 7193 SDValue Src, Chain = getRoot(); 7194 7195 if (TLI.useLoadStackGuardNode()) 7196 Src = getLoadStackGuard(DAG, sdl, Chain); 7197 else 7198 Src = getValue(I.getArgOperand(0)); // The guard's value. 7199 7200 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7201 7202 int FI = FuncInfo.StaticAllocaMap[Slot]; 7203 MFI.setStackProtectorIndex(FI); 7204 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7205 7206 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7207 7208 // Store the stack protector onto the stack. 7209 Res = DAG.getStore( 7210 Chain, sdl, Src, FIN, 7211 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7212 MaybeAlign(), MachineMemOperand::MOVolatile); 7213 setValue(&I, Res); 7214 DAG.setRoot(Res); 7215 return; 7216 } 7217 case Intrinsic::objectsize: 7218 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7219 7220 case Intrinsic::is_constant: 7221 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7222 7223 case Intrinsic::annotation: 7224 case Intrinsic::ptr_annotation: 7225 case Intrinsic::launder_invariant_group: 7226 case Intrinsic::strip_invariant_group: 7227 // Drop the intrinsic, but forward the value 7228 setValue(&I, getValue(I.getOperand(0))); 7229 return; 7230 7231 case Intrinsic::assume: 7232 case Intrinsic::experimental_noalias_scope_decl: 7233 case Intrinsic::var_annotation: 7234 case Intrinsic::sideeffect: 7235 // Discard annotate attributes, noalias scope declarations, assumptions, and 7236 // artificial side-effects. 7237 return; 7238 7239 case Intrinsic::codeview_annotation: { 7240 // Emit a label associated with this metadata. 7241 MachineFunction &MF = DAG.getMachineFunction(); 7242 MCSymbol *Label = 7243 MF.getMMI().getContext().createTempSymbol("annotation", true); 7244 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7245 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7246 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7247 DAG.setRoot(Res); 7248 return; 7249 } 7250 7251 case Intrinsic::init_trampoline: { 7252 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7253 7254 SDValue Ops[6]; 7255 Ops[0] = getRoot(); 7256 Ops[1] = getValue(I.getArgOperand(0)); 7257 Ops[2] = getValue(I.getArgOperand(1)); 7258 Ops[3] = getValue(I.getArgOperand(2)); 7259 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7260 Ops[5] = DAG.getSrcValue(F); 7261 7262 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7263 7264 DAG.setRoot(Res); 7265 return; 7266 } 7267 case Intrinsic::adjust_trampoline: 7268 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7269 TLI.getPointerTy(DAG.getDataLayout()), 7270 getValue(I.getArgOperand(0)))); 7271 return; 7272 case Intrinsic::gcroot: { 7273 assert(DAG.getMachineFunction().getFunction().hasGC() && 7274 "only valid in functions with gc specified, enforced by Verifier"); 7275 assert(GFI && "implied by previous"); 7276 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7277 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7278 7279 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7280 GFI->addStackRoot(FI->getIndex(), TypeMap); 7281 return; 7282 } 7283 case Intrinsic::gcread: 7284 case Intrinsic::gcwrite: 7285 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7286 case Intrinsic::get_rounding: 7287 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7288 setValue(&I, Res); 7289 DAG.setRoot(Res.getValue(1)); 7290 return; 7291 7292 case Intrinsic::expect: 7293 // Just replace __builtin_expect(exp, c) with EXP. 7294 setValue(&I, getValue(I.getArgOperand(0))); 7295 return; 7296 7297 case Intrinsic::ubsantrap: 7298 case Intrinsic::debugtrap: 7299 case Intrinsic::trap: { 7300 StringRef TrapFuncName = 7301 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7302 if (TrapFuncName.empty()) { 7303 switch (Intrinsic) { 7304 case Intrinsic::trap: 7305 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7306 break; 7307 case Intrinsic::debugtrap: 7308 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7309 break; 7310 case Intrinsic::ubsantrap: 7311 DAG.setRoot(DAG.getNode( 7312 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7313 DAG.getTargetConstant( 7314 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7315 MVT::i32))); 7316 break; 7317 default: llvm_unreachable("unknown trap intrinsic"); 7318 } 7319 return; 7320 } 7321 TargetLowering::ArgListTy Args; 7322 if (Intrinsic == Intrinsic::ubsantrap) { 7323 Args.push_back(TargetLoweringBase::ArgListEntry()); 7324 Args[0].Val = I.getArgOperand(0); 7325 Args[0].Node = getValue(Args[0].Val); 7326 Args[0].Ty = Args[0].Val->getType(); 7327 } 7328 7329 TargetLowering::CallLoweringInfo CLI(DAG); 7330 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7331 CallingConv::C, I.getType(), 7332 DAG.getExternalSymbol(TrapFuncName.data(), 7333 TLI.getPointerTy(DAG.getDataLayout())), 7334 std::move(Args)); 7335 7336 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7337 DAG.setRoot(Result.second); 7338 return; 7339 } 7340 7341 case Intrinsic::allow_runtime_check: 7342 case Intrinsic::allow_ubsan_check: 7343 setValue(&I, getValue(ConstantInt::getTrue(I.getType()))); 7344 return; 7345 7346 case Intrinsic::uadd_with_overflow: 7347 case Intrinsic::sadd_with_overflow: 7348 case Intrinsic::usub_with_overflow: 7349 case Intrinsic::ssub_with_overflow: 7350 case Intrinsic::umul_with_overflow: 7351 case Intrinsic::smul_with_overflow: { 7352 ISD::NodeType Op; 7353 switch (Intrinsic) { 7354 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7355 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7356 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7357 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7358 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7359 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7360 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7361 } 7362 SDValue Op1 = getValue(I.getArgOperand(0)); 7363 SDValue Op2 = getValue(I.getArgOperand(1)); 7364 7365 EVT ResultVT = Op1.getValueType(); 7366 EVT OverflowVT = MVT::i1; 7367 if (ResultVT.isVector()) 7368 OverflowVT = EVT::getVectorVT( 7369 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7370 7371 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7372 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7373 return; 7374 } 7375 case Intrinsic::prefetch: { 7376 SDValue Ops[5]; 7377 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7378 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7379 Ops[0] = DAG.getRoot(); 7380 Ops[1] = getValue(I.getArgOperand(0)); 7381 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7382 MVT::i32); 7383 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7384 MVT::i32); 7385 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7386 MVT::i32); 7387 SDValue Result = DAG.getMemIntrinsicNode( 7388 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7389 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7390 /* align */ std::nullopt, Flags); 7391 7392 // Chain the prefetch in parallel with any pending loads, to stay out of 7393 // the way of later optimizations. 7394 PendingLoads.push_back(Result); 7395 Result = getRoot(); 7396 DAG.setRoot(Result); 7397 return; 7398 } 7399 case Intrinsic::lifetime_start: 7400 case Intrinsic::lifetime_end: { 7401 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7402 // Stack coloring is not enabled in O0, discard region information. 7403 if (TM.getOptLevel() == CodeGenOptLevel::None) 7404 return; 7405 7406 const int64_t ObjectSize = 7407 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7408 Value *const ObjectPtr = I.getArgOperand(1); 7409 SmallVector<const Value *, 4> Allocas; 7410 getUnderlyingObjects(ObjectPtr, Allocas); 7411 7412 for (const Value *Alloca : Allocas) { 7413 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7414 7415 // Could not find an Alloca. 7416 if (!LifetimeObject) 7417 continue; 7418 7419 // First check that the Alloca is static, otherwise it won't have a 7420 // valid frame index. 7421 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7422 if (SI == FuncInfo.StaticAllocaMap.end()) 7423 return; 7424 7425 const int FrameIndex = SI->second; 7426 int64_t Offset; 7427 if (GetPointerBaseWithConstantOffset( 7428 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7429 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7430 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7431 Offset); 7432 DAG.setRoot(Res); 7433 } 7434 return; 7435 } 7436 case Intrinsic::pseudoprobe: { 7437 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7438 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7439 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7440 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7441 DAG.setRoot(Res); 7442 return; 7443 } 7444 case Intrinsic::invariant_start: 7445 // Discard region information. 7446 setValue(&I, 7447 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7448 return; 7449 case Intrinsic::invariant_end: 7450 // Discard region information. 7451 return; 7452 case Intrinsic::clear_cache: 7453 /// FunctionName may be null. 7454 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7455 lowerCallToExternalSymbol(I, FunctionName); 7456 return; 7457 case Intrinsic::donothing: 7458 case Intrinsic::seh_try_begin: 7459 case Intrinsic::seh_scope_begin: 7460 case Intrinsic::seh_try_end: 7461 case Intrinsic::seh_scope_end: 7462 // ignore 7463 return; 7464 case Intrinsic::experimental_stackmap: 7465 visitStackmap(I); 7466 return; 7467 case Intrinsic::experimental_patchpoint_void: 7468 case Intrinsic::experimental_patchpoint: 7469 visitPatchpoint(I); 7470 return; 7471 case Intrinsic::experimental_gc_statepoint: 7472 LowerStatepoint(cast<GCStatepointInst>(I)); 7473 return; 7474 case Intrinsic::experimental_gc_result: 7475 visitGCResult(cast<GCResultInst>(I)); 7476 return; 7477 case Intrinsic::experimental_gc_relocate: 7478 visitGCRelocate(cast<GCRelocateInst>(I)); 7479 return; 7480 case Intrinsic::instrprof_cover: 7481 llvm_unreachable("instrprof failed to lower a cover"); 7482 case Intrinsic::instrprof_increment: 7483 llvm_unreachable("instrprof failed to lower an increment"); 7484 case Intrinsic::instrprof_timestamp: 7485 llvm_unreachable("instrprof failed to lower a timestamp"); 7486 case Intrinsic::instrprof_value_profile: 7487 llvm_unreachable("instrprof failed to lower a value profiling call"); 7488 case Intrinsic::instrprof_mcdc_parameters: 7489 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7490 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7491 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7492 case Intrinsic::instrprof_mcdc_condbitmap_update: 7493 llvm_unreachable("instrprof failed to lower an mcdc condbitmap update"); 7494 case Intrinsic::localescape: { 7495 MachineFunction &MF = DAG.getMachineFunction(); 7496 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7497 7498 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7499 // is the same on all targets. 7500 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7501 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7502 if (isa<ConstantPointerNull>(Arg)) 7503 continue; // Skip null pointers. They represent a hole in index space. 7504 AllocaInst *Slot = cast<AllocaInst>(Arg); 7505 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7506 "can only escape static allocas"); 7507 int FI = FuncInfo.StaticAllocaMap[Slot]; 7508 MCSymbol *FrameAllocSym = 7509 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7510 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7511 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7512 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7513 .addSym(FrameAllocSym) 7514 .addFrameIndex(FI); 7515 } 7516 7517 return; 7518 } 7519 7520 case Intrinsic::localrecover: { 7521 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7522 MachineFunction &MF = DAG.getMachineFunction(); 7523 7524 // Get the symbol that defines the frame offset. 7525 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7526 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7527 unsigned IdxVal = 7528 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7529 MCSymbol *FrameAllocSym = 7530 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7531 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7532 7533 Value *FP = I.getArgOperand(1); 7534 SDValue FPVal = getValue(FP); 7535 EVT PtrVT = FPVal.getValueType(); 7536 7537 // Create a MCSymbol for the label to avoid any target lowering 7538 // that would make this PC relative. 7539 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7540 SDValue OffsetVal = 7541 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7542 7543 // Add the offset to the FP. 7544 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7545 setValue(&I, Add); 7546 7547 return; 7548 } 7549 7550 case Intrinsic::eh_exceptionpointer: 7551 case Intrinsic::eh_exceptioncode: { 7552 // Get the exception pointer vreg, copy from it, and resize it to fit. 7553 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7554 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7555 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7556 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7557 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7558 if (Intrinsic == Intrinsic::eh_exceptioncode) 7559 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7560 setValue(&I, N); 7561 return; 7562 } 7563 case Intrinsic::xray_customevent: { 7564 // Here we want to make sure that the intrinsic behaves as if it has a 7565 // specific calling convention. 7566 const auto &Triple = DAG.getTarget().getTargetTriple(); 7567 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7568 return; 7569 7570 SmallVector<SDValue, 8> Ops; 7571 7572 // We want to say that we always want the arguments in registers. 7573 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7574 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7575 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7576 SDValue Chain = getRoot(); 7577 Ops.push_back(LogEntryVal); 7578 Ops.push_back(StrSizeVal); 7579 Ops.push_back(Chain); 7580 7581 // We need to enforce the calling convention for the callsite, so that 7582 // argument ordering is enforced correctly, and that register allocation can 7583 // see that some registers may be assumed clobbered and have to preserve 7584 // them across calls to the intrinsic. 7585 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7586 sdl, NodeTys, Ops); 7587 SDValue patchableNode = SDValue(MN, 0); 7588 DAG.setRoot(patchableNode); 7589 setValue(&I, patchableNode); 7590 return; 7591 } 7592 case Intrinsic::xray_typedevent: { 7593 // Here we want to make sure that the intrinsic behaves as if it has a 7594 // specific calling convention. 7595 const auto &Triple = DAG.getTarget().getTargetTriple(); 7596 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7597 return; 7598 7599 SmallVector<SDValue, 8> Ops; 7600 7601 // We want to say that we always want the arguments in registers. 7602 // It's unclear to me how manipulating the selection DAG here forces callers 7603 // to provide arguments in registers instead of on the stack. 7604 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7605 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7606 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7607 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7608 SDValue Chain = getRoot(); 7609 Ops.push_back(LogTypeId); 7610 Ops.push_back(LogEntryVal); 7611 Ops.push_back(StrSizeVal); 7612 Ops.push_back(Chain); 7613 7614 // We need to enforce the calling convention for the callsite, so that 7615 // argument ordering is enforced correctly, and that register allocation can 7616 // see that some registers may be assumed clobbered and have to preserve 7617 // them across calls to the intrinsic. 7618 MachineSDNode *MN = DAG.getMachineNode( 7619 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7620 SDValue patchableNode = SDValue(MN, 0); 7621 DAG.setRoot(patchableNode); 7622 setValue(&I, patchableNode); 7623 return; 7624 } 7625 case Intrinsic::experimental_deoptimize: 7626 LowerDeoptimizeCall(&I); 7627 return; 7628 case Intrinsic::experimental_stepvector: 7629 visitStepVector(I); 7630 return; 7631 case Intrinsic::vector_reduce_fadd: 7632 case Intrinsic::vector_reduce_fmul: 7633 case Intrinsic::vector_reduce_add: 7634 case Intrinsic::vector_reduce_mul: 7635 case Intrinsic::vector_reduce_and: 7636 case Intrinsic::vector_reduce_or: 7637 case Intrinsic::vector_reduce_xor: 7638 case Intrinsic::vector_reduce_smax: 7639 case Intrinsic::vector_reduce_smin: 7640 case Intrinsic::vector_reduce_umax: 7641 case Intrinsic::vector_reduce_umin: 7642 case Intrinsic::vector_reduce_fmax: 7643 case Intrinsic::vector_reduce_fmin: 7644 case Intrinsic::vector_reduce_fmaximum: 7645 case Intrinsic::vector_reduce_fminimum: 7646 visitVectorReduce(I, Intrinsic); 7647 return; 7648 7649 case Intrinsic::icall_branch_funnel: { 7650 SmallVector<SDValue, 16> Ops; 7651 Ops.push_back(getValue(I.getArgOperand(0))); 7652 7653 int64_t Offset; 7654 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7655 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7656 if (!Base) 7657 report_fatal_error( 7658 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7659 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7660 7661 struct BranchFunnelTarget { 7662 int64_t Offset; 7663 SDValue Target; 7664 }; 7665 SmallVector<BranchFunnelTarget, 8> Targets; 7666 7667 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7668 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7669 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7670 if (ElemBase != Base) 7671 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7672 "to the same GlobalValue"); 7673 7674 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7675 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7676 if (!GA) 7677 report_fatal_error( 7678 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7679 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7680 GA->getGlobal(), sdl, Val.getValueType(), 7681 GA->getOffset())}); 7682 } 7683 llvm::sort(Targets, 7684 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7685 return T1.Offset < T2.Offset; 7686 }); 7687 7688 for (auto &T : Targets) { 7689 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7690 Ops.push_back(T.Target); 7691 } 7692 7693 Ops.push_back(DAG.getRoot()); // Chain 7694 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7695 MVT::Other, Ops), 7696 0); 7697 DAG.setRoot(N); 7698 setValue(&I, N); 7699 HasTailCall = true; 7700 return; 7701 } 7702 7703 case Intrinsic::wasm_landingpad_index: 7704 // Information this intrinsic contained has been transferred to 7705 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7706 // delete it now. 7707 return; 7708 7709 case Intrinsic::aarch64_settag: 7710 case Intrinsic::aarch64_settag_zero: { 7711 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7712 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7713 SDValue Val = TSI.EmitTargetCodeForSetTag( 7714 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7715 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7716 ZeroMemory); 7717 DAG.setRoot(Val); 7718 setValue(&I, Val); 7719 return; 7720 } 7721 case Intrinsic::amdgcn_cs_chain: { 7722 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7723 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7724 "Non-zero flags not supported yet"); 7725 7726 // At this point we don't care if it's amdgpu_cs_chain or 7727 // amdgpu_cs_chain_preserve. 7728 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7729 7730 Type *RetTy = I.getType(); 7731 assert(RetTy->isVoidTy() && "Should not return"); 7732 7733 SDValue Callee = getValue(I.getOperand(0)); 7734 7735 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7736 // We'll also tack the value of the EXEC mask at the end. 7737 TargetLowering::ArgListTy Args; 7738 Args.reserve(3); 7739 7740 for (unsigned Idx : {2, 3, 1}) { 7741 TargetLowering::ArgListEntry Arg; 7742 Arg.Node = getValue(I.getOperand(Idx)); 7743 Arg.Ty = I.getOperand(Idx)->getType(); 7744 Arg.setAttributes(&I, Idx); 7745 Args.push_back(Arg); 7746 } 7747 7748 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7749 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7750 Args[2].IsInReg = true; // EXEC should be inreg 7751 7752 TargetLowering::CallLoweringInfo CLI(DAG); 7753 CLI.setDebugLoc(getCurSDLoc()) 7754 .setChain(getRoot()) 7755 .setCallee(CC, RetTy, Callee, std::move(Args)) 7756 .setNoReturn(true) 7757 .setTailCall(true) 7758 .setConvergent(I.isConvergent()); 7759 CLI.CB = &I; 7760 std::pair<SDValue, SDValue> Result = 7761 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7762 (void)Result; 7763 assert(!Result.first.getNode() && !Result.second.getNode() && 7764 "Should've lowered as tail call"); 7765 7766 HasTailCall = true; 7767 return; 7768 } 7769 case Intrinsic::ptrmask: { 7770 SDValue Ptr = getValue(I.getOperand(0)); 7771 SDValue Mask = getValue(I.getOperand(1)); 7772 7773 EVT PtrVT = Ptr.getValueType(); 7774 assert(PtrVT == Mask.getValueType() && 7775 "Pointers with different index type are not supported by SDAG"); 7776 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7777 return; 7778 } 7779 case Intrinsic::threadlocal_address: { 7780 setValue(&I, getValue(I.getOperand(0))); 7781 return; 7782 } 7783 case Intrinsic::get_active_lane_mask: { 7784 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7785 SDValue Index = getValue(I.getOperand(0)); 7786 EVT ElementVT = Index.getValueType(); 7787 7788 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7789 visitTargetIntrinsic(I, Intrinsic); 7790 return; 7791 } 7792 7793 SDValue TripCount = getValue(I.getOperand(1)); 7794 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7795 CCVT.getVectorElementCount()); 7796 7797 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7798 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7799 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7800 SDValue VectorInduction = DAG.getNode( 7801 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7802 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7803 VectorTripCount, ISD::CondCode::SETULT); 7804 setValue(&I, SetCC); 7805 return; 7806 } 7807 case Intrinsic::experimental_get_vector_length: { 7808 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7809 "Expected positive VF"); 7810 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7811 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7812 7813 SDValue Count = getValue(I.getOperand(0)); 7814 EVT CountVT = Count.getValueType(); 7815 7816 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7817 visitTargetIntrinsic(I, Intrinsic); 7818 return; 7819 } 7820 7821 // Expand to a umin between the trip count and the maximum elements the type 7822 // can hold. 7823 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7824 7825 // Extend the trip count to at least the result VT. 7826 if (CountVT.bitsLT(VT)) { 7827 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7828 CountVT = VT; 7829 } 7830 7831 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7832 ElementCount::get(VF, IsScalable)); 7833 7834 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7835 // Clip to the result type if needed. 7836 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7837 7838 setValue(&I, Trunc); 7839 return; 7840 } 7841 case Intrinsic::experimental_cttz_elts: { 7842 auto DL = getCurSDLoc(); 7843 SDValue Op = getValue(I.getOperand(0)); 7844 EVT OpVT = Op.getValueType(); 7845 7846 if (!TLI.shouldExpandCttzElements(OpVT)) { 7847 visitTargetIntrinsic(I, Intrinsic); 7848 return; 7849 } 7850 7851 if (OpVT.getScalarType() != MVT::i1) { 7852 // Compare the input vector elements to zero & use to count trailing zeros 7853 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 7854 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 7855 OpVT.getVectorElementCount()); 7856 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 7857 } 7858 7859 // Find the smallest "sensible" element type to use for the expansion. 7860 ConstantRange CR( 7861 APInt(64, OpVT.getVectorElementCount().getKnownMinValue())); 7862 if (OpVT.isScalableVT()) 7863 CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64)); 7864 7865 // If the zero-is-poison flag is set, we can assume the upper limit 7866 // of the result is VF-1. 7867 if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero()) 7868 CR = CR.subtract(APInt(64, 1)); 7869 7870 unsigned EltWidth = I.getType()->getScalarSizeInBits(); 7871 EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits()); 7872 EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8); 7873 7874 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 7875 7876 // Create the new vector type & get the vector length 7877 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 7878 OpVT.getVectorElementCount()); 7879 7880 SDValue VL = 7881 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 7882 7883 SDValue StepVec = DAG.getStepVector(DL, NewVT); 7884 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 7885 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 7886 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 7887 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 7888 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 7889 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 7890 7891 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7892 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 7893 7894 setValue(&I, Ret); 7895 return; 7896 } 7897 case Intrinsic::vector_insert: { 7898 SDValue Vec = getValue(I.getOperand(0)); 7899 SDValue SubVec = getValue(I.getOperand(1)); 7900 SDValue Index = getValue(I.getOperand(2)); 7901 7902 // The intrinsic's index type is i64, but the SDNode requires an index type 7903 // suitable for the target. Convert the index as required. 7904 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7905 if (Index.getValueType() != VectorIdxTy) 7906 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7907 7908 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7909 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7910 Index)); 7911 return; 7912 } 7913 case Intrinsic::vector_extract: { 7914 SDValue Vec = getValue(I.getOperand(0)); 7915 SDValue Index = getValue(I.getOperand(1)); 7916 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7917 7918 // The intrinsic's index type is i64, but the SDNode requires an index type 7919 // suitable for the target. Convert the index as required. 7920 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7921 if (Index.getValueType() != VectorIdxTy) 7922 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7923 7924 setValue(&I, 7925 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7926 return; 7927 } 7928 case Intrinsic::experimental_vector_reverse: 7929 visitVectorReverse(I); 7930 return; 7931 case Intrinsic::experimental_vector_splice: 7932 visitVectorSplice(I); 7933 return; 7934 case Intrinsic::callbr_landingpad: 7935 visitCallBrLandingPad(I); 7936 return; 7937 case Intrinsic::experimental_vector_interleave2: 7938 visitVectorInterleave(I); 7939 return; 7940 case Intrinsic::experimental_vector_deinterleave2: 7941 visitVectorDeinterleave(I); 7942 return; 7943 case Intrinsic::experimental_convergence_anchor: 7944 case Intrinsic::experimental_convergence_entry: 7945 case Intrinsic::experimental_convergence_loop: 7946 visitConvergenceControl(I, Intrinsic); 7947 } 7948 } 7949 7950 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7951 const ConstrainedFPIntrinsic &FPI) { 7952 SDLoc sdl = getCurSDLoc(); 7953 7954 // We do not need to serialize constrained FP intrinsics against 7955 // each other or against (nonvolatile) loads, so they can be 7956 // chained like loads. 7957 SDValue Chain = DAG.getRoot(); 7958 SmallVector<SDValue, 4> Opers; 7959 Opers.push_back(Chain); 7960 if (FPI.isUnaryOp()) { 7961 Opers.push_back(getValue(FPI.getArgOperand(0))); 7962 } else if (FPI.isTernaryOp()) { 7963 Opers.push_back(getValue(FPI.getArgOperand(0))); 7964 Opers.push_back(getValue(FPI.getArgOperand(1))); 7965 Opers.push_back(getValue(FPI.getArgOperand(2))); 7966 } else { 7967 Opers.push_back(getValue(FPI.getArgOperand(0))); 7968 Opers.push_back(getValue(FPI.getArgOperand(1))); 7969 } 7970 7971 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7972 assert(Result.getNode()->getNumValues() == 2); 7973 7974 // Push node to the appropriate list so that future instructions can be 7975 // chained up correctly. 7976 SDValue OutChain = Result.getValue(1); 7977 switch (EB) { 7978 case fp::ExceptionBehavior::ebIgnore: 7979 // The only reason why ebIgnore nodes still need to be chained is that 7980 // they might depend on the current rounding mode, and therefore must 7981 // not be moved across instruction that may change that mode. 7982 [[fallthrough]]; 7983 case fp::ExceptionBehavior::ebMayTrap: 7984 // These must not be moved across calls or instructions that may change 7985 // floating-point exception masks. 7986 PendingConstrainedFP.push_back(OutChain); 7987 break; 7988 case fp::ExceptionBehavior::ebStrict: 7989 // These must not be moved across calls or instructions that may change 7990 // floating-point exception masks or read floating-point exception flags. 7991 // In addition, they cannot be optimized out even if unused. 7992 PendingConstrainedFPStrict.push_back(OutChain); 7993 break; 7994 } 7995 }; 7996 7997 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7998 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7999 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 8000 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 8001 8002 SDNodeFlags Flags; 8003 if (EB == fp::ExceptionBehavior::ebIgnore) 8004 Flags.setNoFPExcept(true); 8005 8006 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 8007 Flags.copyFMF(*FPOp); 8008 8009 unsigned Opcode; 8010 switch (FPI.getIntrinsicID()) { 8011 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8012 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8013 case Intrinsic::INTRINSIC: \ 8014 Opcode = ISD::STRICT_##DAGN; \ 8015 break; 8016 #include "llvm/IR/ConstrainedOps.def" 8017 case Intrinsic::experimental_constrained_fmuladd: { 8018 Opcode = ISD::STRICT_FMA; 8019 // Break fmuladd into fmul and fadd. 8020 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 8021 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 8022 Opers.pop_back(); 8023 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 8024 pushOutChain(Mul, EB); 8025 Opcode = ISD::STRICT_FADD; 8026 Opers.clear(); 8027 Opers.push_back(Mul.getValue(1)); 8028 Opers.push_back(Mul.getValue(0)); 8029 Opers.push_back(getValue(FPI.getArgOperand(2))); 8030 } 8031 break; 8032 } 8033 } 8034 8035 // A few strict DAG nodes carry additional operands that are not 8036 // set up by the default code above. 8037 switch (Opcode) { 8038 default: break; 8039 case ISD::STRICT_FP_ROUND: 8040 Opers.push_back( 8041 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 8042 break; 8043 case ISD::STRICT_FSETCC: 8044 case ISD::STRICT_FSETCCS: { 8045 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 8046 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 8047 if (TM.Options.NoNaNsFPMath) 8048 Condition = getFCmpCodeWithoutNaN(Condition); 8049 Opers.push_back(DAG.getCondCode(Condition)); 8050 break; 8051 } 8052 } 8053 8054 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 8055 pushOutChain(Result, EB); 8056 8057 SDValue FPResult = Result.getValue(0); 8058 setValue(&FPI, FPResult); 8059 } 8060 8061 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 8062 std::optional<unsigned> ResOPC; 8063 switch (VPIntrin.getIntrinsicID()) { 8064 case Intrinsic::vp_ctlz: { 8065 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8066 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 8067 break; 8068 } 8069 case Intrinsic::vp_cttz: { 8070 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8071 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 8072 break; 8073 } 8074 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 8075 case Intrinsic::VPID: \ 8076 ResOPC = ISD::VPSD; \ 8077 break; 8078 #include "llvm/IR/VPIntrinsics.def" 8079 } 8080 8081 if (!ResOPC) 8082 llvm_unreachable( 8083 "Inconsistency: no SDNode available for this VPIntrinsic!"); 8084 8085 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 8086 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 8087 if (VPIntrin.getFastMathFlags().allowReassoc()) 8088 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 8089 : ISD::VP_REDUCE_FMUL; 8090 } 8091 8092 return *ResOPC; 8093 } 8094 8095 void SelectionDAGBuilder::visitVPLoad( 8096 const VPIntrinsic &VPIntrin, EVT VT, 8097 const SmallVectorImpl<SDValue> &OpValues) { 8098 SDLoc DL = getCurSDLoc(); 8099 Value *PtrOperand = VPIntrin.getArgOperand(0); 8100 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8101 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8102 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8103 SDValue LD; 8104 // Do not serialize variable-length loads of constant memory with 8105 // anything. 8106 if (!Alignment) 8107 Alignment = DAG.getEVTAlign(VT); 8108 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8109 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8110 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8111 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8112 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8113 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8114 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 8115 MMO, false /*IsExpanding */); 8116 if (AddToChain) 8117 PendingLoads.push_back(LD.getValue(1)); 8118 setValue(&VPIntrin, LD); 8119 } 8120 8121 void SelectionDAGBuilder::visitVPGather( 8122 const VPIntrinsic &VPIntrin, EVT VT, 8123 const SmallVectorImpl<SDValue> &OpValues) { 8124 SDLoc DL = getCurSDLoc(); 8125 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8126 Value *PtrOperand = VPIntrin.getArgOperand(0); 8127 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8128 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8129 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8130 SDValue LD; 8131 if (!Alignment) 8132 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8133 unsigned AS = 8134 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8135 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8136 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8137 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8138 SDValue Base, Index, Scale; 8139 ISD::MemIndexType IndexType; 8140 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8141 this, VPIntrin.getParent(), 8142 VT.getScalarStoreSize()); 8143 if (!UniformBase) { 8144 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8145 Index = getValue(PtrOperand); 8146 IndexType = ISD::SIGNED_SCALED; 8147 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8148 } 8149 EVT IdxVT = Index.getValueType(); 8150 EVT EltTy = IdxVT.getVectorElementType(); 8151 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8152 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8153 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8154 } 8155 LD = DAG.getGatherVP( 8156 DAG.getVTList(VT, MVT::Other), VT, DL, 8157 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 8158 IndexType); 8159 PendingLoads.push_back(LD.getValue(1)); 8160 setValue(&VPIntrin, LD); 8161 } 8162 8163 void SelectionDAGBuilder::visitVPStore( 8164 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8165 SDLoc DL = getCurSDLoc(); 8166 Value *PtrOperand = VPIntrin.getArgOperand(1); 8167 EVT VT = OpValues[0].getValueType(); 8168 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8169 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8170 SDValue ST; 8171 if (!Alignment) 8172 Alignment = DAG.getEVTAlign(VT); 8173 SDValue Ptr = OpValues[1]; 8174 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 8175 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8176 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8177 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8178 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 8179 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 8180 /* IsTruncating */ false, /*IsCompressing*/ false); 8181 DAG.setRoot(ST); 8182 setValue(&VPIntrin, ST); 8183 } 8184 8185 void SelectionDAGBuilder::visitVPScatter( 8186 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8187 SDLoc DL = getCurSDLoc(); 8188 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8189 Value *PtrOperand = VPIntrin.getArgOperand(1); 8190 EVT VT = OpValues[0].getValueType(); 8191 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8192 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8193 SDValue ST; 8194 if (!Alignment) 8195 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8196 unsigned AS = 8197 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8198 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8199 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8200 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8201 SDValue Base, Index, Scale; 8202 ISD::MemIndexType IndexType; 8203 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8204 this, VPIntrin.getParent(), 8205 VT.getScalarStoreSize()); 8206 if (!UniformBase) { 8207 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8208 Index = getValue(PtrOperand); 8209 IndexType = ISD::SIGNED_SCALED; 8210 Scale = 8211 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8212 } 8213 EVT IdxVT = Index.getValueType(); 8214 EVT EltTy = IdxVT.getVectorElementType(); 8215 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8216 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8217 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8218 } 8219 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8220 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8221 OpValues[2], OpValues[3]}, 8222 MMO, IndexType); 8223 DAG.setRoot(ST); 8224 setValue(&VPIntrin, ST); 8225 } 8226 8227 void SelectionDAGBuilder::visitVPStridedLoad( 8228 const VPIntrinsic &VPIntrin, EVT VT, 8229 const SmallVectorImpl<SDValue> &OpValues) { 8230 SDLoc DL = getCurSDLoc(); 8231 Value *PtrOperand = VPIntrin.getArgOperand(0); 8232 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8233 if (!Alignment) 8234 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8235 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8236 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8237 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8238 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8239 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8240 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8241 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8242 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8243 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8244 8245 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8246 OpValues[2], OpValues[3], MMO, 8247 false /*IsExpanding*/); 8248 8249 if (AddToChain) 8250 PendingLoads.push_back(LD.getValue(1)); 8251 setValue(&VPIntrin, LD); 8252 } 8253 8254 void SelectionDAGBuilder::visitVPStridedStore( 8255 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8256 SDLoc DL = getCurSDLoc(); 8257 Value *PtrOperand = VPIntrin.getArgOperand(1); 8258 EVT VT = OpValues[0].getValueType(); 8259 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8260 if (!Alignment) 8261 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8262 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8263 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8264 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8265 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8266 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8267 8268 SDValue ST = DAG.getStridedStoreVP( 8269 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8270 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8271 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8272 /*IsCompressing*/ false); 8273 8274 DAG.setRoot(ST); 8275 setValue(&VPIntrin, ST); 8276 } 8277 8278 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8279 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8280 SDLoc DL = getCurSDLoc(); 8281 8282 ISD::CondCode Condition; 8283 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8284 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8285 if (IsFP) { 8286 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8287 // flags, but calls that don't return floating-point types can't be 8288 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8289 Condition = getFCmpCondCode(CondCode); 8290 if (TM.Options.NoNaNsFPMath) 8291 Condition = getFCmpCodeWithoutNaN(Condition); 8292 } else { 8293 Condition = getICmpCondCode(CondCode); 8294 } 8295 8296 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8297 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8298 // #2 is the condition code 8299 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8300 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8301 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8302 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8303 "Unexpected target EVL type"); 8304 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8305 8306 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8307 VPIntrin.getType()); 8308 setValue(&VPIntrin, 8309 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8310 } 8311 8312 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8313 const VPIntrinsic &VPIntrin) { 8314 SDLoc DL = getCurSDLoc(); 8315 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8316 8317 auto IID = VPIntrin.getIntrinsicID(); 8318 8319 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8320 return visitVPCmp(*CmpI); 8321 8322 SmallVector<EVT, 4> ValueVTs; 8323 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8324 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8325 SDVTList VTs = DAG.getVTList(ValueVTs); 8326 8327 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8328 8329 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8330 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8331 "Unexpected target EVL type"); 8332 8333 // Request operands. 8334 SmallVector<SDValue, 7> OpValues; 8335 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8336 auto Op = getValue(VPIntrin.getArgOperand(I)); 8337 if (I == EVLParamPos) 8338 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8339 OpValues.push_back(Op); 8340 } 8341 8342 switch (Opcode) { 8343 default: { 8344 SDNodeFlags SDFlags; 8345 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8346 SDFlags.copyFMF(*FPMO); 8347 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8348 setValue(&VPIntrin, Result); 8349 break; 8350 } 8351 case ISD::VP_LOAD: 8352 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8353 break; 8354 case ISD::VP_GATHER: 8355 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8356 break; 8357 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8358 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8359 break; 8360 case ISD::VP_STORE: 8361 visitVPStore(VPIntrin, OpValues); 8362 break; 8363 case ISD::VP_SCATTER: 8364 visitVPScatter(VPIntrin, OpValues); 8365 break; 8366 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8367 visitVPStridedStore(VPIntrin, OpValues); 8368 break; 8369 case ISD::VP_FMULADD: { 8370 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8371 SDNodeFlags SDFlags; 8372 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8373 SDFlags.copyFMF(*FPMO); 8374 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8375 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8376 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8377 } else { 8378 SDValue Mul = DAG.getNode( 8379 ISD::VP_FMUL, DL, VTs, 8380 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8381 SDValue Add = 8382 DAG.getNode(ISD::VP_FADD, DL, VTs, 8383 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8384 setValue(&VPIntrin, Add); 8385 } 8386 break; 8387 } 8388 case ISD::VP_IS_FPCLASS: { 8389 const DataLayout DLayout = DAG.getDataLayout(); 8390 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8391 auto Constant = OpValues[1]->getAsZExtVal(); 8392 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8393 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8394 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8395 setValue(&VPIntrin, V); 8396 return; 8397 } 8398 case ISD::VP_INTTOPTR: { 8399 SDValue N = OpValues[0]; 8400 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8401 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8402 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8403 OpValues[2]); 8404 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8405 OpValues[2]); 8406 setValue(&VPIntrin, N); 8407 break; 8408 } 8409 case ISD::VP_PTRTOINT: { 8410 SDValue N = OpValues[0]; 8411 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8412 VPIntrin.getType()); 8413 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8414 VPIntrin.getOperand(0)->getType()); 8415 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8416 OpValues[2]); 8417 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8418 OpValues[2]); 8419 setValue(&VPIntrin, N); 8420 break; 8421 } 8422 case ISD::VP_ABS: 8423 case ISD::VP_CTLZ: 8424 case ISD::VP_CTLZ_ZERO_UNDEF: 8425 case ISD::VP_CTTZ: 8426 case ISD::VP_CTTZ_ZERO_UNDEF: { 8427 SDValue Result = 8428 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8429 setValue(&VPIntrin, Result); 8430 break; 8431 } 8432 } 8433 } 8434 8435 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8436 const BasicBlock *EHPadBB, 8437 MCSymbol *&BeginLabel) { 8438 MachineFunction &MF = DAG.getMachineFunction(); 8439 MachineModuleInfo &MMI = MF.getMMI(); 8440 8441 // Insert a label before the invoke call to mark the try range. This can be 8442 // used to detect deletion of the invoke via the MachineModuleInfo. 8443 BeginLabel = MMI.getContext().createTempSymbol(); 8444 8445 // For SjLj, keep track of which landing pads go with which invokes 8446 // so as to maintain the ordering of pads in the LSDA. 8447 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 8448 if (CallSiteIndex) { 8449 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8450 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 8451 8452 // Now that the call site is handled, stop tracking it. 8453 MMI.setCurrentCallSite(0); 8454 } 8455 8456 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8457 } 8458 8459 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8460 const BasicBlock *EHPadBB, 8461 MCSymbol *BeginLabel) { 8462 assert(BeginLabel && "BeginLabel should've been set"); 8463 8464 MachineFunction &MF = DAG.getMachineFunction(); 8465 MachineModuleInfo &MMI = MF.getMMI(); 8466 8467 // Insert a label at the end of the invoke call to mark the try range. This 8468 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8469 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8470 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8471 8472 // Inform MachineModuleInfo of range. 8473 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8474 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8475 // actually use outlined funclets and their LSDA info style. 8476 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8477 assert(II && "II should've been set"); 8478 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8479 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8480 } else if (!isScopedEHPersonality(Pers)) { 8481 assert(EHPadBB); 8482 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8483 } 8484 8485 return Chain; 8486 } 8487 8488 std::pair<SDValue, SDValue> 8489 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8490 const BasicBlock *EHPadBB) { 8491 MCSymbol *BeginLabel = nullptr; 8492 8493 if (EHPadBB) { 8494 // Both PendingLoads and PendingExports must be flushed here; 8495 // this call might not return. 8496 (void)getRoot(); 8497 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8498 CLI.setChain(getRoot()); 8499 } 8500 8501 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8502 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8503 8504 assert((CLI.IsTailCall || Result.second.getNode()) && 8505 "Non-null chain expected with non-tail call!"); 8506 assert((Result.second.getNode() || !Result.first.getNode()) && 8507 "Null value expected with tail call!"); 8508 8509 if (!Result.second.getNode()) { 8510 // As a special case, a null chain means that a tail call has been emitted 8511 // and the DAG root is already updated. 8512 HasTailCall = true; 8513 8514 // Since there's no actual continuation from this block, nothing can be 8515 // relying on us setting vregs for them. 8516 PendingExports.clear(); 8517 } else { 8518 DAG.setRoot(Result.second); 8519 } 8520 8521 if (EHPadBB) { 8522 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8523 BeginLabel)); 8524 } 8525 8526 return Result; 8527 } 8528 8529 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8530 bool isTailCall, 8531 bool isMustTailCall, 8532 const BasicBlock *EHPadBB) { 8533 auto &DL = DAG.getDataLayout(); 8534 FunctionType *FTy = CB.getFunctionType(); 8535 Type *RetTy = CB.getType(); 8536 8537 TargetLowering::ArgListTy Args; 8538 Args.reserve(CB.arg_size()); 8539 8540 const Value *SwiftErrorVal = nullptr; 8541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8542 8543 if (isTailCall) { 8544 // Avoid emitting tail calls in functions with the disable-tail-calls 8545 // attribute. 8546 auto *Caller = CB.getParent()->getParent(); 8547 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8548 "true" && !isMustTailCall) 8549 isTailCall = false; 8550 8551 // We can't tail call inside a function with a swifterror argument. Lowering 8552 // does not support this yet. It would have to move into the swifterror 8553 // register before the call. 8554 if (TLI.supportSwiftError() && 8555 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8556 isTailCall = false; 8557 } 8558 8559 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8560 TargetLowering::ArgListEntry Entry; 8561 const Value *V = *I; 8562 8563 // Skip empty types 8564 if (V->getType()->isEmptyTy()) 8565 continue; 8566 8567 SDValue ArgNode = getValue(V); 8568 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8569 8570 Entry.setAttributes(&CB, I - CB.arg_begin()); 8571 8572 // Use swifterror virtual register as input to the call. 8573 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8574 SwiftErrorVal = V; 8575 // We find the virtual register for the actual swifterror argument. 8576 // Instead of using the Value, we use the virtual register instead. 8577 Entry.Node = 8578 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8579 EVT(TLI.getPointerTy(DL))); 8580 } 8581 8582 Args.push_back(Entry); 8583 8584 // If we have an explicit sret argument that is an Instruction, (i.e., it 8585 // might point to function-local memory), we can't meaningfully tail-call. 8586 if (Entry.IsSRet && isa<Instruction>(V)) 8587 isTailCall = false; 8588 } 8589 8590 // If call site has a cfguardtarget operand bundle, create and add an 8591 // additional ArgListEntry. 8592 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8593 TargetLowering::ArgListEntry Entry; 8594 Value *V = Bundle->Inputs[0]; 8595 SDValue ArgNode = getValue(V); 8596 Entry.Node = ArgNode; 8597 Entry.Ty = V->getType(); 8598 Entry.IsCFGuardTarget = true; 8599 Args.push_back(Entry); 8600 } 8601 8602 // Check if target-independent constraints permit a tail call here. 8603 // Target-dependent constraints are checked within TLI->LowerCallTo. 8604 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8605 isTailCall = false; 8606 8607 // Disable tail calls if there is an swifterror argument. Targets have not 8608 // been updated to support tail calls. 8609 if (TLI.supportSwiftError() && SwiftErrorVal) 8610 isTailCall = false; 8611 8612 ConstantInt *CFIType = nullptr; 8613 if (CB.isIndirectCall()) { 8614 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8615 if (!TLI.supportKCFIBundles()) 8616 report_fatal_error( 8617 "Target doesn't support calls with kcfi operand bundles."); 8618 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8619 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8620 } 8621 } 8622 8623 SDValue ConvControlToken; 8624 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) { 8625 auto *Token = Bundle->Inputs[0].get(); 8626 ConvControlToken = getValue(Token); 8627 } 8628 8629 TargetLowering::CallLoweringInfo CLI(DAG); 8630 CLI.setDebugLoc(getCurSDLoc()) 8631 .setChain(getRoot()) 8632 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8633 .setTailCall(isTailCall) 8634 .setConvergent(CB.isConvergent()) 8635 .setIsPreallocated( 8636 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8637 .setCFIType(CFIType) 8638 .setConvergenceControlToken(ConvControlToken); 8639 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8640 8641 if (Result.first.getNode()) { 8642 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8643 setValue(&CB, Result.first); 8644 } 8645 8646 // The last element of CLI.InVals has the SDValue for swifterror return. 8647 // Here we copy it to a virtual register and update SwiftErrorMap for 8648 // book-keeping. 8649 if (SwiftErrorVal && TLI.supportSwiftError()) { 8650 // Get the last element of InVals. 8651 SDValue Src = CLI.InVals.back(); 8652 Register VReg = 8653 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8654 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8655 DAG.setRoot(CopyNode); 8656 } 8657 } 8658 8659 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8660 SelectionDAGBuilder &Builder) { 8661 // Check to see if this load can be trivially constant folded, e.g. if the 8662 // input is from a string literal. 8663 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8664 // Cast pointer to the type we really want to load. 8665 Type *LoadTy = 8666 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8667 if (LoadVT.isVector()) 8668 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8669 8670 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8671 PointerType::getUnqual(LoadTy)); 8672 8673 if (const Constant *LoadCst = 8674 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8675 LoadTy, Builder.DAG.getDataLayout())) 8676 return Builder.getValue(LoadCst); 8677 } 8678 8679 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8680 // still constant memory, the input chain can be the entry node. 8681 SDValue Root; 8682 bool ConstantMemory = false; 8683 8684 // Do not serialize (non-volatile) loads of constant memory with anything. 8685 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8686 Root = Builder.DAG.getEntryNode(); 8687 ConstantMemory = true; 8688 } else { 8689 // Do not serialize non-volatile loads against each other. 8690 Root = Builder.DAG.getRoot(); 8691 } 8692 8693 SDValue Ptr = Builder.getValue(PtrVal); 8694 SDValue LoadVal = 8695 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8696 MachinePointerInfo(PtrVal), Align(1)); 8697 8698 if (!ConstantMemory) 8699 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8700 return LoadVal; 8701 } 8702 8703 /// Record the value for an instruction that produces an integer result, 8704 /// converting the type where necessary. 8705 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8706 SDValue Value, 8707 bool IsSigned) { 8708 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8709 I.getType(), true); 8710 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8711 setValue(&I, Value); 8712 } 8713 8714 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8715 /// true and lower it. Otherwise return false, and it will be lowered like a 8716 /// normal call. 8717 /// The caller already checked that \p I calls the appropriate LibFunc with a 8718 /// correct prototype. 8719 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8720 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8721 const Value *Size = I.getArgOperand(2); 8722 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8723 if (CSize && CSize->getZExtValue() == 0) { 8724 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8725 I.getType(), true); 8726 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8727 return true; 8728 } 8729 8730 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8731 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8732 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8733 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8734 if (Res.first.getNode()) { 8735 processIntegerCallValue(I, Res.first, true); 8736 PendingLoads.push_back(Res.second); 8737 return true; 8738 } 8739 8740 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8741 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8742 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8743 return false; 8744 8745 // If the target has a fast compare for the given size, it will return a 8746 // preferred load type for that size. Require that the load VT is legal and 8747 // that the target supports unaligned loads of that type. Otherwise, return 8748 // INVALID. 8749 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8750 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8751 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8752 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8753 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8754 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8755 // TODO: Check alignment of src and dest ptrs. 8756 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8757 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8758 if (!TLI.isTypeLegal(LVT) || 8759 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8760 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8761 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8762 } 8763 8764 return LVT; 8765 }; 8766 8767 // This turns into unaligned loads. We only do this if the target natively 8768 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8769 // we'll only produce a small number of byte loads. 8770 MVT LoadVT; 8771 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8772 switch (NumBitsToCompare) { 8773 default: 8774 return false; 8775 case 16: 8776 LoadVT = MVT::i16; 8777 break; 8778 case 32: 8779 LoadVT = MVT::i32; 8780 break; 8781 case 64: 8782 case 128: 8783 case 256: 8784 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8785 break; 8786 } 8787 8788 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8789 return false; 8790 8791 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8792 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8793 8794 // Bitcast to a wide integer type if the loads are vectors. 8795 if (LoadVT.isVector()) { 8796 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8797 LoadL = DAG.getBitcast(CmpVT, LoadL); 8798 LoadR = DAG.getBitcast(CmpVT, LoadR); 8799 } 8800 8801 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8802 processIntegerCallValue(I, Cmp, false); 8803 return true; 8804 } 8805 8806 /// See if we can lower a memchr call into an optimized form. If so, return 8807 /// true and lower it. Otherwise return false, and it will be lowered like a 8808 /// normal call. 8809 /// The caller already checked that \p I calls the appropriate LibFunc with a 8810 /// correct prototype. 8811 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8812 const Value *Src = I.getArgOperand(0); 8813 const Value *Char = I.getArgOperand(1); 8814 const Value *Length = I.getArgOperand(2); 8815 8816 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8817 std::pair<SDValue, SDValue> Res = 8818 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8819 getValue(Src), getValue(Char), getValue(Length), 8820 MachinePointerInfo(Src)); 8821 if (Res.first.getNode()) { 8822 setValue(&I, Res.first); 8823 PendingLoads.push_back(Res.second); 8824 return true; 8825 } 8826 8827 return false; 8828 } 8829 8830 /// See if we can lower a mempcpy call into an optimized form. If so, return 8831 /// true and lower it. Otherwise return false, and it will be lowered like a 8832 /// normal call. 8833 /// The caller already checked that \p I calls the appropriate LibFunc with a 8834 /// correct prototype. 8835 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8836 SDValue Dst = getValue(I.getArgOperand(0)); 8837 SDValue Src = getValue(I.getArgOperand(1)); 8838 SDValue Size = getValue(I.getArgOperand(2)); 8839 8840 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8841 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8842 // DAG::getMemcpy needs Alignment to be defined. 8843 Align Alignment = std::min(DstAlign, SrcAlign); 8844 8845 SDLoc sdl = getCurSDLoc(); 8846 8847 // In the mempcpy context we need to pass in a false value for isTailCall 8848 // because the return pointer needs to be adjusted by the size of 8849 // the copied memory. 8850 SDValue Root = getMemoryRoot(); 8851 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8852 /*isTailCall=*/false, 8853 MachinePointerInfo(I.getArgOperand(0)), 8854 MachinePointerInfo(I.getArgOperand(1)), 8855 I.getAAMetadata()); 8856 assert(MC.getNode() != nullptr && 8857 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8858 DAG.setRoot(MC); 8859 8860 // Check if Size needs to be truncated or extended. 8861 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8862 8863 // Adjust return pointer to point just past the last dst byte. 8864 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8865 Dst, Size); 8866 setValue(&I, DstPlusSize); 8867 return true; 8868 } 8869 8870 /// See if we can lower a strcpy call into an optimized form. If so, return 8871 /// true and lower it, otherwise return false and it will be lowered like a 8872 /// normal call. 8873 /// The caller already checked that \p I calls the appropriate LibFunc with a 8874 /// correct prototype. 8875 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8876 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8877 8878 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8879 std::pair<SDValue, SDValue> Res = 8880 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8881 getValue(Arg0), getValue(Arg1), 8882 MachinePointerInfo(Arg0), 8883 MachinePointerInfo(Arg1), isStpcpy); 8884 if (Res.first.getNode()) { 8885 setValue(&I, Res.first); 8886 DAG.setRoot(Res.second); 8887 return true; 8888 } 8889 8890 return false; 8891 } 8892 8893 /// See if we can lower a strcmp call into an optimized form. If so, return 8894 /// true and lower it, otherwise return false and it will be lowered like a 8895 /// normal call. 8896 /// The caller already checked that \p I calls the appropriate LibFunc with a 8897 /// correct prototype. 8898 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8899 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8900 8901 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8902 std::pair<SDValue, SDValue> Res = 8903 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8904 getValue(Arg0), getValue(Arg1), 8905 MachinePointerInfo(Arg0), 8906 MachinePointerInfo(Arg1)); 8907 if (Res.first.getNode()) { 8908 processIntegerCallValue(I, Res.first, true); 8909 PendingLoads.push_back(Res.second); 8910 return true; 8911 } 8912 8913 return false; 8914 } 8915 8916 /// See if we can lower a strlen call into an optimized form. If so, return 8917 /// true and lower it, otherwise return false and it will be lowered like a 8918 /// normal call. 8919 /// The caller already checked that \p I calls the appropriate LibFunc with a 8920 /// correct prototype. 8921 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8922 const Value *Arg0 = I.getArgOperand(0); 8923 8924 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8925 std::pair<SDValue, SDValue> Res = 8926 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8927 getValue(Arg0), MachinePointerInfo(Arg0)); 8928 if (Res.first.getNode()) { 8929 processIntegerCallValue(I, Res.first, false); 8930 PendingLoads.push_back(Res.second); 8931 return true; 8932 } 8933 8934 return false; 8935 } 8936 8937 /// See if we can lower a strnlen call into an optimized form. If so, return 8938 /// true and lower it, otherwise return false and it will be lowered like a 8939 /// normal call. 8940 /// The caller already checked that \p I calls the appropriate LibFunc with a 8941 /// correct prototype. 8942 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8943 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8944 8945 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8946 std::pair<SDValue, SDValue> Res = 8947 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8948 getValue(Arg0), getValue(Arg1), 8949 MachinePointerInfo(Arg0)); 8950 if (Res.first.getNode()) { 8951 processIntegerCallValue(I, Res.first, false); 8952 PendingLoads.push_back(Res.second); 8953 return true; 8954 } 8955 8956 return false; 8957 } 8958 8959 /// See if we can lower a unary floating-point operation into an SDNode with 8960 /// the specified Opcode. If so, return true and lower it, otherwise return 8961 /// false and it will be lowered like a normal call. 8962 /// The caller already checked that \p I calls the appropriate LibFunc with a 8963 /// correct prototype. 8964 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8965 unsigned Opcode) { 8966 // We already checked this call's prototype; verify it doesn't modify errno. 8967 if (!I.onlyReadsMemory()) 8968 return false; 8969 8970 SDNodeFlags Flags; 8971 Flags.copyFMF(cast<FPMathOperator>(I)); 8972 8973 SDValue Tmp = getValue(I.getArgOperand(0)); 8974 setValue(&I, 8975 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8976 return true; 8977 } 8978 8979 /// See if we can lower a binary floating-point operation into an SDNode with 8980 /// the specified Opcode. If so, return true and lower it. Otherwise return 8981 /// false, and it will be lowered like a normal call. 8982 /// The caller already checked that \p I calls the appropriate LibFunc with a 8983 /// correct prototype. 8984 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8985 unsigned Opcode) { 8986 // We already checked this call's prototype; verify it doesn't modify errno. 8987 if (!I.onlyReadsMemory()) 8988 return false; 8989 8990 SDNodeFlags Flags; 8991 Flags.copyFMF(cast<FPMathOperator>(I)); 8992 8993 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8994 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8995 EVT VT = Tmp0.getValueType(); 8996 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8997 return true; 8998 } 8999 9000 void SelectionDAGBuilder::visitCall(const CallInst &I) { 9001 // Handle inline assembly differently. 9002 if (I.isInlineAsm()) { 9003 visitInlineAsm(I); 9004 return; 9005 } 9006 9007 diagnoseDontCall(I); 9008 9009 if (Function *F = I.getCalledFunction()) { 9010 if (F->isDeclaration()) { 9011 // Is this an LLVM intrinsic or a target-specific intrinsic? 9012 unsigned IID = F->getIntrinsicID(); 9013 if (!IID) 9014 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 9015 IID = II->getIntrinsicID(F); 9016 9017 if (IID) { 9018 visitIntrinsicCall(I, IID); 9019 return; 9020 } 9021 } 9022 9023 // Check for well-known libc/libm calls. If the function is internal, it 9024 // can't be a library call. Don't do the check if marked as nobuiltin for 9025 // some reason or the call site requires strict floating point semantics. 9026 LibFunc Func; 9027 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 9028 F->hasName() && LibInfo->getLibFunc(*F, Func) && 9029 LibInfo->hasOptimizedCodeGen(Func)) { 9030 switch (Func) { 9031 default: break; 9032 case LibFunc_bcmp: 9033 if (visitMemCmpBCmpCall(I)) 9034 return; 9035 break; 9036 case LibFunc_copysign: 9037 case LibFunc_copysignf: 9038 case LibFunc_copysignl: 9039 // We already checked this call's prototype; verify it doesn't modify 9040 // errno. 9041 if (I.onlyReadsMemory()) { 9042 SDValue LHS = getValue(I.getArgOperand(0)); 9043 SDValue RHS = getValue(I.getArgOperand(1)); 9044 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 9045 LHS.getValueType(), LHS, RHS)); 9046 return; 9047 } 9048 break; 9049 case LibFunc_fabs: 9050 case LibFunc_fabsf: 9051 case LibFunc_fabsl: 9052 if (visitUnaryFloatCall(I, ISD::FABS)) 9053 return; 9054 break; 9055 case LibFunc_fmin: 9056 case LibFunc_fminf: 9057 case LibFunc_fminl: 9058 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 9059 return; 9060 break; 9061 case LibFunc_fmax: 9062 case LibFunc_fmaxf: 9063 case LibFunc_fmaxl: 9064 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 9065 return; 9066 break; 9067 case LibFunc_sin: 9068 case LibFunc_sinf: 9069 case LibFunc_sinl: 9070 if (visitUnaryFloatCall(I, ISD::FSIN)) 9071 return; 9072 break; 9073 case LibFunc_cos: 9074 case LibFunc_cosf: 9075 case LibFunc_cosl: 9076 if (visitUnaryFloatCall(I, ISD::FCOS)) 9077 return; 9078 break; 9079 case LibFunc_sqrt: 9080 case LibFunc_sqrtf: 9081 case LibFunc_sqrtl: 9082 case LibFunc_sqrt_finite: 9083 case LibFunc_sqrtf_finite: 9084 case LibFunc_sqrtl_finite: 9085 if (visitUnaryFloatCall(I, ISD::FSQRT)) 9086 return; 9087 break; 9088 case LibFunc_floor: 9089 case LibFunc_floorf: 9090 case LibFunc_floorl: 9091 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 9092 return; 9093 break; 9094 case LibFunc_nearbyint: 9095 case LibFunc_nearbyintf: 9096 case LibFunc_nearbyintl: 9097 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 9098 return; 9099 break; 9100 case LibFunc_ceil: 9101 case LibFunc_ceilf: 9102 case LibFunc_ceill: 9103 if (visitUnaryFloatCall(I, ISD::FCEIL)) 9104 return; 9105 break; 9106 case LibFunc_rint: 9107 case LibFunc_rintf: 9108 case LibFunc_rintl: 9109 if (visitUnaryFloatCall(I, ISD::FRINT)) 9110 return; 9111 break; 9112 case LibFunc_round: 9113 case LibFunc_roundf: 9114 case LibFunc_roundl: 9115 if (visitUnaryFloatCall(I, ISD::FROUND)) 9116 return; 9117 break; 9118 case LibFunc_trunc: 9119 case LibFunc_truncf: 9120 case LibFunc_truncl: 9121 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 9122 return; 9123 break; 9124 case LibFunc_log2: 9125 case LibFunc_log2f: 9126 case LibFunc_log2l: 9127 if (visitUnaryFloatCall(I, ISD::FLOG2)) 9128 return; 9129 break; 9130 case LibFunc_exp2: 9131 case LibFunc_exp2f: 9132 case LibFunc_exp2l: 9133 if (visitUnaryFloatCall(I, ISD::FEXP2)) 9134 return; 9135 break; 9136 case LibFunc_exp10: 9137 case LibFunc_exp10f: 9138 case LibFunc_exp10l: 9139 if (visitUnaryFloatCall(I, ISD::FEXP10)) 9140 return; 9141 break; 9142 case LibFunc_ldexp: 9143 case LibFunc_ldexpf: 9144 case LibFunc_ldexpl: 9145 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 9146 return; 9147 break; 9148 case LibFunc_memcmp: 9149 if (visitMemCmpBCmpCall(I)) 9150 return; 9151 break; 9152 case LibFunc_mempcpy: 9153 if (visitMemPCpyCall(I)) 9154 return; 9155 break; 9156 case LibFunc_memchr: 9157 if (visitMemChrCall(I)) 9158 return; 9159 break; 9160 case LibFunc_strcpy: 9161 if (visitStrCpyCall(I, false)) 9162 return; 9163 break; 9164 case LibFunc_stpcpy: 9165 if (visitStrCpyCall(I, true)) 9166 return; 9167 break; 9168 case LibFunc_strcmp: 9169 if (visitStrCmpCall(I)) 9170 return; 9171 break; 9172 case LibFunc_strlen: 9173 if (visitStrLenCall(I)) 9174 return; 9175 break; 9176 case LibFunc_strnlen: 9177 if (visitStrNLenCall(I)) 9178 return; 9179 break; 9180 } 9181 } 9182 } 9183 9184 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9185 // have to do anything here to lower funclet bundles. 9186 // CFGuardTarget bundles are lowered in LowerCallTo. 9187 assert(!I.hasOperandBundlesOtherThan( 9188 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9189 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9190 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi, 9191 LLVMContext::OB_convergencectrl}) && 9192 "Cannot lower calls with arbitrary operand bundles!"); 9193 9194 SDValue Callee = getValue(I.getCalledOperand()); 9195 9196 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 9197 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9198 else 9199 // Check if we can potentially perform a tail call. More detailed checking 9200 // is be done within LowerCallTo, after more information about the call is 9201 // known. 9202 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9203 } 9204 9205 namespace { 9206 9207 /// AsmOperandInfo - This contains information for each constraint that we are 9208 /// lowering. 9209 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9210 public: 9211 /// CallOperand - If this is the result output operand or a clobber 9212 /// this is null, otherwise it is the incoming operand to the CallInst. 9213 /// This gets modified as the asm is processed. 9214 SDValue CallOperand; 9215 9216 /// AssignedRegs - If this is a register or register class operand, this 9217 /// contains the set of register corresponding to the operand. 9218 RegsForValue AssignedRegs; 9219 9220 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9221 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9222 } 9223 9224 /// Whether or not this operand accesses memory 9225 bool hasMemory(const TargetLowering &TLI) const { 9226 // Indirect operand accesses access memory. 9227 if (isIndirect) 9228 return true; 9229 9230 for (const auto &Code : Codes) 9231 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9232 return true; 9233 9234 return false; 9235 } 9236 }; 9237 9238 9239 } // end anonymous namespace 9240 9241 /// Make sure that the output operand \p OpInfo and its corresponding input 9242 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9243 /// out). 9244 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9245 SDISelAsmOperandInfo &MatchingOpInfo, 9246 SelectionDAG &DAG) { 9247 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9248 return; 9249 9250 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9251 const auto &TLI = DAG.getTargetLoweringInfo(); 9252 9253 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9254 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9255 OpInfo.ConstraintVT); 9256 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9257 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9258 MatchingOpInfo.ConstraintVT); 9259 if ((OpInfo.ConstraintVT.isInteger() != 9260 MatchingOpInfo.ConstraintVT.isInteger()) || 9261 (MatchRC.second != InputRC.second)) { 9262 // FIXME: error out in a more elegant fashion 9263 report_fatal_error("Unsupported asm: input constraint" 9264 " with a matching output constraint of" 9265 " incompatible type!"); 9266 } 9267 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9268 } 9269 9270 /// Get a direct memory input to behave well as an indirect operand. 9271 /// This may introduce stores, hence the need for a \p Chain. 9272 /// \return The (possibly updated) chain. 9273 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9274 SDISelAsmOperandInfo &OpInfo, 9275 SelectionDAG &DAG) { 9276 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9277 9278 // If we don't have an indirect input, put it in the constpool if we can, 9279 // otherwise spill it to a stack slot. 9280 // TODO: This isn't quite right. We need to handle these according to 9281 // the addressing mode that the constraint wants. Also, this may take 9282 // an additional register for the computation and we don't want that 9283 // either. 9284 9285 // If the operand is a float, integer, or vector constant, spill to a 9286 // constant pool entry to get its address. 9287 const Value *OpVal = OpInfo.CallOperandVal; 9288 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9289 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9290 OpInfo.CallOperand = DAG.getConstantPool( 9291 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9292 return Chain; 9293 } 9294 9295 // Otherwise, create a stack slot and emit a store to it before the asm. 9296 Type *Ty = OpVal->getType(); 9297 auto &DL = DAG.getDataLayout(); 9298 uint64_t TySize = DL.getTypeAllocSize(Ty); 9299 MachineFunction &MF = DAG.getMachineFunction(); 9300 int SSFI = MF.getFrameInfo().CreateStackObject( 9301 TySize, DL.getPrefTypeAlign(Ty), false); 9302 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9303 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9304 MachinePointerInfo::getFixedStack(MF, SSFI), 9305 TLI.getMemValueType(DL, Ty)); 9306 OpInfo.CallOperand = StackSlot; 9307 9308 return Chain; 9309 } 9310 9311 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9312 /// specified operand. We prefer to assign virtual registers, to allow the 9313 /// register allocator to handle the assignment process. However, if the asm 9314 /// uses features that we can't model on machineinstrs, we have SDISel do the 9315 /// allocation. This produces generally horrible, but correct, code. 9316 /// 9317 /// OpInfo describes the operand 9318 /// RefOpInfo describes the matching operand if any, the operand otherwise 9319 static std::optional<unsigned> 9320 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9321 SDISelAsmOperandInfo &OpInfo, 9322 SDISelAsmOperandInfo &RefOpInfo) { 9323 LLVMContext &Context = *DAG.getContext(); 9324 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9325 9326 MachineFunction &MF = DAG.getMachineFunction(); 9327 SmallVector<unsigned, 4> Regs; 9328 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9329 9330 // No work to do for memory/address operands. 9331 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9332 OpInfo.ConstraintType == TargetLowering::C_Address) 9333 return std::nullopt; 9334 9335 // If this is a constraint for a single physreg, or a constraint for a 9336 // register class, find it. 9337 unsigned AssignedReg; 9338 const TargetRegisterClass *RC; 9339 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9340 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9341 // RC is unset only on failure. Return immediately. 9342 if (!RC) 9343 return std::nullopt; 9344 9345 // Get the actual register value type. This is important, because the user 9346 // may have asked for (e.g.) the AX register in i32 type. We need to 9347 // remember that AX is actually i16 to get the right extension. 9348 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9349 9350 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9351 // If this is an FP operand in an integer register (or visa versa), or more 9352 // generally if the operand value disagrees with the register class we plan 9353 // to stick it in, fix the operand type. 9354 // 9355 // If this is an input value, the bitcast to the new type is done now. 9356 // Bitcast for output value is done at the end of visitInlineAsm(). 9357 if ((OpInfo.Type == InlineAsm::isOutput || 9358 OpInfo.Type == InlineAsm::isInput) && 9359 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9360 // Try to convert to the first EVT that the reg class contains. If the 9361 // types are identical size, use a bitcast to convert (e.g. two differing 9362 // vector types). Note: output bitcast is done at the end of 9363 // visitInlineAsm(). 9364 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9365 // Exclude indirect inputs while they are unsupported because the code 9366 // to perform the load is missing and thus OpInfo.CallOperand still 9367 // refers to the input address rather than the pointed-to value. 9368 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9369 OpInfo.CallOperand = 9370 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9371 OpInfo.ConstraintVT = RegVT; 9372 // If the operand is an FP value and we want it in integer registers, 9373 // use the corresponding integer type. This turns an f64 value into 9374 // i64, which can be passed with two i32 values on a 32-bit machine. 9375 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9376 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9377 if (OpInfo.Type == InlineAsm::isInput) 9378 OpInfo.CallOperand = 9379 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9380 OpInfo.ConstraintVT = VT; 9381 } 9382 } 9383 } 9384 9385 // No need to allocate a matching input constraint since the constraint it's 9386 // matching to has already been allocated. 9387 if (OpInfo.isMatchingInputConstraint()) 9388 return std::nullopt; 9389 9390 EVT ValueVT = OpInfo.ConstraintVT; 9391 if (OpInfo.ConstraintVT == MVT::Other) 9392 ValueVT = RegVT; 9393 9394 // Initialize NumRegs. 9395 unsigned NumRegs = 1; 9396 if (OpInfo.ConstraintVT != MVT::Other) 9397 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9398 9399 // If this is a constraint for a specific physical register, like {r17}, 9400 // assign it now. 9401 9402 // If this associated to a specific register, initialize iterator to correct 9403 // place. If virtual, make sure we have enough registers 9404 9405 // Initialize iterator if necessary 9406 TargetRegisterClass::iterator I = RC->begin(); 9407 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9408 9409 // Do not check for single registers. 9410 if (AssignedReg) { 9411 I = std::find(I, RC->end(), AssignedReg); 9412 if (I == RC->end()) { 9413 // RC does not contain the selected register, which indicates a 9414 // mismatch between the register and the required type/bitwidth. 9415 return {AssignedReg}; 9416 } 9417 } 9418 9419 for (; NumRegs; --NumRegs, ++I) { 9420 assert(I != RC->end() && "Ran out of registers to allocate!"); 9421 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9422 Regs.push_back(R); 9423 } 9424 9425 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9426 return std::nullopt; 9427 } 9428 9429 static unsigned 9430 findMatchingInlineAsmOperand(unsigned OperandNo, 9431 const std::vector<SDValue> &AsmNodeOperands) { 9432 // Scan until we find the definition we already emitted of this operand. 9433 unsigned CurOp = InlineAsm::Op_FirstOperand; 9434 for (; OperandNo; --OperandNo) { 9435 // Advance to the next operand. 9436 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9437 const InlineAsm::Flag F(OpFlag); 9438 assert( 9439 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9440 "Skipped past definitions?"); 9441 CurOp += F.getNumOperandRegisters() + 1; 9442 } 9443 return CurOp; 9444 } 9445 9446 namespace { 9447 9448 class ExtraFlags { 9449 unsigned Flags = 0; 9450 9451 public: 9452 explicit ExtraFlags(const CallBase &Call) { 9453 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9454 if (IA->hasSideEffects()) 9455 Flags |= InlineAsm::Extra_HasSideEffects; 9456 if (IA->isAlignStack()) 9457 Flags |= InlineAsm::Extra_IsAlignStack; 9458 if (Call.isConvergent()) 9459 Flags |= InlineAsm::Extra_IsConvergent; 9460 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9461 } 9462 9463 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9464 // Ideally, we would only check against memory constraints. However, the 9465 // meaning of an Other constraint can be target-specific and we can't easily 9466 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9467 // for Other constraints as well. 9468 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9469 OpInfo.ConstraintType == TargetLowering::C_Other) { 9470 if (OpInfo.Type == InlineAsm::isInput) 9471 Flags |= InlineAsm::Extra_MayLoad; 9472 else if (OpInfo.Type == InlineAsm::isOutput) 9473 Flags |= InlineAsm::Extra_MayStore; 9474 else if (OpInfo.Type == InlineAsm::isClobber) 9475 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9476 } 9477 } 9478 9479 unsigned get() const { return Flags; } 9480 }; 9481 9482 } // end anonymous namespace 9483 9484 static bool isFunction(SDValue Op) { 9485 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9486 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9487 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9488 9489 // In normal "call dllimport func" instruction (non-inlineasm) it force 9490 // indirect access by specifing call opcode. And usually specially print 9491 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9492 // not do in this way now. (In fact, this is similar with "Data Access" 9493 // action). So here we ignore dllimport function. 9494 if (Fn && !Fn->hasDLLImportStorageClass()) 9495 return true; 9496 } 9497 } 9498 return false; 9499 } 9500 9501 /// visitInlineAsm - Handle a call to an InlineAsm object. 9502 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9503 const BasicBlock *EHPadBB) { 9504 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9505 9506 /// ConstraintOperands - Information about all of the constraints. 9507 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9508 9509 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9510 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9511 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9512 9513 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9514 // AsmDialect, MayLoad, MayStore). 9515 bool HasSideEffect = IA->hasSideEffects(); 9516 ExtraFlags ExtraInfo(Call); 9517 9518 for (auto &T : TargetConstraints) { 9519 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9520 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9521 9522 if (OpInfo.CallOperandVal) 9523 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9524 9525 if (!HasSideEffect) 9526 HasSideEffect = OpInfo.hasMemory(TLI); 9527 9528 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9529 // FIXME: Could we compute this on OpInfo rather than T? 9530 9531 // Compute the constraint code and ConstraintType to use. 9532 TLI.ComputeConstraintToUse(T, SDValue()); 9533 9534 if (T.ConstraintType == TargetLowering::C_Immediate && 9535 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9536 // We've delayed emitting a diagnostic like the "n" constraint because 9537 // inlining could cause an integer showing up. 9538 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9539 "' expects an integer constant " 9540 "expression"); 9541 9542 ExtraInfo.update(T); 9543 } 9544 9545 // We won't need to flush pending loads if this asm doesn't touch 9546 // memory and is nonvolatile. 9547 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9548 9549 bool EmitEHLabels = isa<InvokeInst>(Call); 9550 if (EmitEHLabels) { 9551 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9552 } 9553 bool IsCallBr = isa<CallBrInst>(Call); 9554 9555 if (IsCallBr || EmitEHLabels) { 9556 // If this is a callbr or invoke we need to flush pending exports since 9557 // inlineasm_br and invoke are terminators. 9558 // We need to do this before nodes are glued to the inlineasm_br node. 9559 Chain = getControlRoot(); 9560 } 9561 9562 MCSymbol *BeginLabel = nullptr; 9563 if (EmitEHLabels) { 9564 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9565 } 9566 9567 int OpNo = -1; 9568 SmallVector<StringRef> AsmStrs; 9569 IA->collectAsmStrs(AsmStrs); 9570 9571 // Second pass over the constraints: compute which constraint option to use. 9572 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9573 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9574 OpNo++; 9575 9576 // If this is an output operand with a matching input operand, look up the 9577 // matching input. If their types mismatch, e.g. one is an integer, the 9578 // other is floating point, or their sizes are different, flag it as an 9579 // error. 9580 if (OpInfo.hasMatchingInput()) { 9581 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9582 patchMatchingInput(OpInfo, Input, DAG); 9583 } 9584 9585 // Compute the constraint code and ConstraintType to use. 9586 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9587 9588 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9589 OpInfo.Type == InlineAsm::isClobber) || 9590 OpInfo.ConstraintType == TargetLowering::C_Address) 9591 continue; 9592 9593 // In Linux PIC model, there are 4 cases about value/label addressing: 9594 // 9595 // 1: Function call or Label jmp inside the module. 9596 // 2: Data access (such as global variable, static variable) inside module. 9597 // 3: Function call or Label jmp outside the module. 9598 // 4: Data access (such as global variable) outside the module. 9599 // 9600 // Due to current llvm inline asm architecture designed to not "recognize" 9601 // the asm code, there are quite troubles for us to treat mem addressing 9602 // differently for same value/adress used in different instuctions. 9603 // For example, in pic model, call a func may in plt way or direclty 9604 // pc-related, but lea/mov a function adress may use got. 9605 // 9606 // Here we try to "recognize" function call for the case 1 and case 3 in 9607 // inline asm. And try to adjust the constraint for them. 9608 // 9609 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9610 // label, so here we don't handle jmp function label now, but we need to 9611 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9612 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9613 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9614 TM.getCodeModel() != CodeModel::Large) { 9615 OpInfo.isIndirect = false; 9616 OpInfo.ConstraintType = TargetLowering::C_Address; 9617 } 9618 9619 // If this is a memory input, and if the operand is not indirect, do what we 9620 // need to provide an address for the memory input. 9621 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9622 !OpInfo.isIndirect) { 9623 assert((OpInfo.isMultipleAlternative || 9624 (OpInfo.Type == InlineAsm::isInput)) && 9625 "Can only indirectify direct input operands!"); 9626 9627 // Memory operands really want the address of the value. 9628 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9629 9630 // There is no longer a Value* corresponding to this operand. 9631 OpInfo.CallOperandVal = nullptr; 9632 9633 // It is now an indirect operand. 9634 OpInfo.isIndirect = true; 9635 } 9636 9637 } 9638 9639 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9640 std::vector<SDValue> AsmNodeOperands; 9641 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9642 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9643 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9644 9645 // If we have a !srcloc metadata node associated with it, we want to attach 9646 // this to the ultimately generated inline asm machineinstr. To do this, we 9647 // pass in the third operand as this (potentially null) inline asm MDNode. 9648 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9649 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9650 9651 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9652 // bits as operand 3. 9653 AsmNodeOperands.push_back(DAG.getTargetConstant( 9654 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9655 9656 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9657 // this, assign virtual and physical registers for inputs and otput. 9658 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9659 // Assign Registers. 9660 SDISelAsmOperandInfo &RefOpInfo = 9661 OpInfo.isMatchingInputConstraint() 9662 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9663 : OpInfo; 9664 const auto RegError = 9665 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9666 if (RegError) { 9667 const MachineFunction &MF = DAG.getMachineFunction(); 9668 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9669 const char *RegName = TRI.getName(*RegError); 9670 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9671 "' allocated for constraint '" + 9672 Twine(OpInfo.ConstraintCode) + 9673 "' does not match required type"); 9674 return; 9675 } 9676 9677 auto DetectWriteToReservedRegister = [&]() { 9678 const MachineFunction &MF = DAG.getMachineFunction(); 9679 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9680 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9681 if (Register::isPhysicalRegister(Reg) && 9682 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9683 const char *RegName = TRI.getName(Reg); 9684 emitInlineAsmError(Call, "write to reserved register '" + 9685 Twine(RegName) + "'"); 9686 return true; 9687 } 9688 } 9689 return false; 9690 }; 9691 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9692 (OpInfo.Type == InlineAsm::isInput && 9693 !OpInfo.isMatchingInputConstraint())) && 9694 "Only address as input operand is allowed."); 9695 9696 switch (OpInfo.Type) { 9697 case InlineAsm::isOutput: 9698 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9699 const InlineAsm::ConstraintCode ConstraintID = 9700 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9701 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9702 "Failed to convert memory constraint code to constraint id."); 9703 9704 // Add information to the INLINEASM node to know about this output. 9705 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 9706 OpFlags.setMemConstraint(ConstraintID); 9707 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9708 MVT::i32)); 9709 AsmNodeOperands.push_back(OpInfo.CallOperand); 9710 } else { 9711 // Otherwise, this outputs to a register (directly for C_Register / 9712 // C_RegisterClass, and a target-defined fashion for 9713 // C_Immediate/C_Other). Find a register that we can use. 9714 if (OpInfo.AssignedRegs.Regs.empty()) { 9715 emitInlineAsmError( 9716 Call, "couldn't allocate output register for constraint '" + 9717 Twine(OpInfo.ConstraintCode) + "'"); 9718 return; 9719 } 9720 9721 if (DetectWriteToReservedRegister()) 9722 return; 9723 9724 // Add information to the INLINEASM node to know that this register is 9725 // set. 9726 OpInfo.AssignedRegs.AddInlineAsmOperands( 9727 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 9728 : InlineAsm::Kind::RegDef, 9729 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9730 } 9731 break; 9732 9733 case InlineAsm::isInput: 9734 case InlineAsm::isLabel: { 9735 SDValue InOperandVal = OpInfo.CallOperand; 9736 9737 if (OpInfo.isMatchingInputConstraint()) { 9738 // If this is required to match an output register we have already set, 9739 // just use its register. 9740 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9741 AsmNodeOperands); 9742 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 9743 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 9744 if (OpInfo.isIndirect) { 9745 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9746 emitInlineAsmError(Call, "inline asm not supported yet: " 9747 "don't know how to handle tied " 9748 "indirect register inputs"); 9749 return; 9750 } 9751 9752 SmallVector<unsigned, 4> Regs; 9753 MachineFunction &MF = DAG.getMachineFunction(); 9754 MachineRegisterInfo &MRI = MF.getRegInfo(); 9755 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9756 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9757 Register TiedReg = R->getReg(); 9758 MVT RegVT = R->getSimpleValueType(0); 9759 const TargetRegisterClass *RC = 9760 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9761 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9762 : TRI.getMinimalPhysRegClass(TiedReg); 9763 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 9764 Regs.push_back(MRI.createVirtualRegister(RC)); 9765 9766 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9767 9768 SDLoc dl = getCurSDLoc(); 9769 // Use the produced MatchedRegs object to 9770 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9771 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 9772 OpInfo.getMatchedOperand(), dl, DAG, 9773 AsmNodeOperands); 9774 break; 9775 } 9776 9777 assert(Flag.isMemKind() && "Unknown matching constraint!"); 9778 assert(Flag.getNumOperandRegisters() == 1 && 9779 "Unexpected number of operands"); 9780 // Add information to the INLINEASM node to know about this input. 9781 // See InlineAsm.h isUseOperandTiedToDef. 9782 Flag.clearMemConstraint(); 9783 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 9784 AsmNodeOperands.push_back(DAG.getTargetConstant( 9785 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9786 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9787 break; 9788 } 9789 9790 // Treat indirect 'X' constraint as memory. 9791 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9792 OpInfo.isIndirect) 9793 OpInfo.ConstraintType = TargetLowering::C_Memory; 9794 9795 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9796 OpInfo.ConstraintType == TargetLowering::C_Other) { 9797 std::vector<SDValue> Ops; 9798 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9799 Ops, DAG); 9800 if (Ops.empty()) { 9801 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9802 if (isa<ConstantSDNode>(InOperandVal)) { 9803 emitInlineAsmError(Call, "value out of range for constraint '" + 9804 Twine(OpInfo.ConstraintCode) + "'"); 9805 return; 9806 } 9807 9808 emitInlineAsmError(Call, 9809 "invalid operand for inline asm constraint '" + 9810 Twine(OpInfo.ConstraintCode) + "'"); 9811 return; 9812 } 9813 9814 // Add information to the INLINEASM node to know about this input. 9815 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 9816 AsmNodeOperands.push_back(DAG.getTargetConstant( 9817 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9818 llvm::append_range(AsmNodeOperands, Ops); 9819 break; 9820 } 9821 9822 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9823 assert((OpInfo.isIndirect || 9824 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9825 "Operand must be indirect to be a mem!"); 9826 assert(InOperandVal.getValueType() == 9827 TLI.getPointerTy(DAG.getDataLayout()) && 9828 "Memory operands expect pointer values"); 9829 9830 const InlineAsm::ConstraintCode ConstraintID = 9831 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9832 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9833 "Failed to convert memory constraint code to constraint id."); 9834 9835 // Add information to the INLINEASM node to know about this input. 9836 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9837 ResOpType.setMemConstraint(ConstraintID); 9838 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9839 getCurSDLoc(), 9840 MVT::i32)); 9841 AsmNodeOperands.push_back(InOperandVal); 9842 break; 9843 } 9844 9845 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9846 const InlineAsm::ConstraintCode ConstraintID = 9847 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9848 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9849 "Failed to convert memory constraint code to constraint id."); 9850 9851 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9852 9853 SDValue AsmOp = InOperandVal; 9854 if (isFunction(InOperandVal)) { 9855 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9856 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 9857 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9858 InOperandVal.getValueType(), 9859 GA->getOffset()); 9860 } 9861 9862 // Add information to the INLINEASM node to know about this input. 9863 ResOpType.setMemConstraint(ConstraintID); 9864 9865 AsmNodeOperands.push_back( 9866 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9867 9868 AsmNodeOperands.push_back(AsmOp); 9869 break; 9870 } 9871 9872 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9873 OpInfo.ConstraintType == TargetLowering::C_Register) && 9874 "Unknown constraint type!"); 9875 9876 // TODO: Support this. 9877 if (OpInfo.isIndirect) { 9878 emitInlineAsmError( 9879 Call, "Don't know how to handle indirect register inputs yet " 9880 "for constraint '" + 9881 Twine(OpInfo.ConstraintCode) + "'"); 9882 return; 9883 } 9884 9885 // Copy the input into the appropriate registers. 9886 if (OpInfo.AssignedRegs.Regs.empty()) { 9887 emitInlineAsmError(Call, 9888 "couldn't allocate input reg for constraint '" + 9889 Twine(OpInfo.ConstraintCode) + "'"); 9890 return; 9891 } 9892 9893 if (DetectWriteToReservedRegister()) 9894 return; 9895 9896 SDLoc dl = getCurSDLoc(); 9897 9898 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9899 &Call); 9900 9901 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 9902 0, dl, DAG, AsmNodeOperands); 9903 break; 9904 } 9905 case InlineAsm::isClobber: 9906 // Add the clobbered value to the operand list, so that the register 9907 // allocator is aware that the physreg got clobbered. 9908 if (!OpInfo.AssignedRegs.Regs.empty()) 9909 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 9910 false, 0, getCurSDLoc(), DAG, 9911 AsmNodeOperands); 9912 break; 9913 } 9914 } 9915 9916 // Finish up input operands. Set the input chain and add the flag last. 9917 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9918 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9919 9920 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9921 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9922 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9923 Glue = Chain.getValue(1); 9924 9925 // Do additional work to generate outputs. 9926 9927 SmallVector<EVT, 1> ResultVTs; 9928 SmallVector<SDValue, 1> ResultValues; 9929 SmallVector<SDValue, 8> OutChains; 9930 9931 llvm::Type *CallResultType = Call.getType(); 9932 ArrayRef<Type *> ResultTypes; 9933 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9934 ResultTypes = StructResult->elements(); 9935 else if (!CallResultType->isVoidTy()) 9936 ResultTypes = ArrayRef(CallResultType); 9937 9938 auto CurResultType = ResultTypes.begin(); 9939 auto handleRegAssign = [&](SDValue V) { 9940 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9941 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9942 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9943 ++CurResultType; 9944 // If the type of the inline asm call site return value is different but has 9945 // same size as the type of the asm output bitcast it. One example of this 9946 // is for vectors with different width / number of elements. This can 9947 // happen for register classes that can contain multiple different value 9948 // types. The preg or vreg allocated may not have the same VT as was 9949 // expected. 9950 // 9951 // This can also happen for a return value that disagrees with the register 9952 // class it is put in, eg. a double in a general-purpose register on a 9953 // 32-bit machine. 9954 if (ResultVT != V.getValueType() && 9955 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9956 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9957 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9958 V.getValueType().isInteger()) { 9959 // If a result value was tied to an input value, the computed result 9960 // may have a wider width than the expected result. Extract the 9961 // relevant portion. 9962 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9963 } 9964 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9965 ResultVTs.push_back(ResultVT); 9966 ResultValues.push_back(V); 9967 }; 9968 9969 // Deal with output operands. 9970 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9971 if (OpInfo.Type == InlineAsm::isOutput) { 9972 SDValue Val; 9973 // Skip trivial output operands. 9974 if (OpInfo.AssignedRegs.Regs.empty()) 9975 continue; 9976 9977 switch (OpInfo.ConstraintType) { 9978 case TargetLowering::C_Register: 9979 case TargetLowering::C_RegisterClass: 9980 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9981 Chain, &Glue, &Call); 9982 break; 9983 case TargetLowering::C_Immediate: 9984 case TargetLowering::C_Other: 9985 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9986 OpInfo, DAG); 9987 break; 9988 case TargetLowering::C_Memory: 9989 break; // Already handled. 9990 case TargetLowering::C_Address: 9991 break; // Silence warning. 9992 case TargetLowering::C_Unknown: 9993 assert(false && "Unexpected unknown constraint"); 9994 } 9995 9996 // Indirect output manifest as stores. Record output chains. 9997 if (OpInfo.isIndirect) { 9998 const Value *Ptr = OpInfo.CallOperandVal; 9999 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 10000 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 10001 MachinePointerInfo(Ptr)); 10002 OutChains.push_back(Store); 10003 } else { 10004 // generate CopyFromRegs to associated registers. 10005 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 10006 if (Val.getOpcode() == ISD::MERGE_VALUES) { 10007 for (const SDValue &V : Val->op_values()) 10008 handleRegAssign(V); 10009 } else 10010 handleRegAssign(Val); 10011 } 10012 } 10013 } 10014 10015 // Set results. 10016 if (!ResultValues.empty()) { 10017 assert(CurResultType == ResultTypes.end() && 10018 "Mismatch in number of ResultTypes"); 10019 assert(ResultValues.size() == ResultTypes.size() && 10020 "Mismatch in number of output operands in asm result"); 10021 10022 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10023 DAG.getVTList(ResultVTs), ResultValues); 10024 setValue(&Call, V); 10025 } 10026 10027 // Collect store chains. 10028 if (!OutChains.empty()) 10029 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 10030 10031 if (EmitEHLabels) { 10032 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 10033 } 10034 10035 // Only Update Root if inline assembly has a memory effect. 10036 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 10037 EmitEHLabels) 10038 DAG.setRoot(Chain); 10039 } 10040 10041 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 10042 const Twine &Message) { 10043 LLVMContext &Ctx = *DAG.getContext(); 10044 Ctx.emitError(&Call, Message); 10045 10046 // Make sure we leave the DAG in a valid state 10047 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10048 SmallVector<EVT, 1> ValueVTs; 10049 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 10050 10051 if (ValueVTs.empty()) 10052 return; 10053 10054 SmallVector<SDValue, 1> Ops; 10055 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 10056 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 10057 10058 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 10059 } 10060 10061 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 10062 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 10063 MVT::Other, getRoot(), 10064 getValue(I.getArgOperand(0)), 10065 DAG.getSrcValue(I.getArgOperand(0)))); 10066 } 10067 10068 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 10069 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10070 const DataLayout &DL = DAG.getDataLayout(); 10071 SDValue V = DAG.getVAArg( 10072 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 10073 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 10074 DL.getABITypeAlign(I.getType()).value()); 10075 DAG.setRoot(V.getValue(1)); 10076 10077 if (I.getType()->isPointerTy()) 10078 V = DAG.getPtrExtOrTrunc( 10079 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 10080 setValue(&I, V); 10081 } 10082 10083 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 10084 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 10085 MVT::Other, getRoot(), 10086 getValue(I.getArgOperand(0)), 10087 DAG.getSrcValue(I.getArgOperand(0)))); 10088 } 10089 10090 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 10091 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 10092 MVT::Other, getRoot(), 10093 getValue(I.getArgOperand(0)), 10094 getValue(I.getArgOperand(1)), 10095 DAG.getSrcValue(I.getArgOperand(0)), 10096 DAG.getSrcValue(I.getArgOperand(1)))); 10097 } 10098 10099 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 10100 const Instruction &I, 10101 SDValue Op) { 10102 const MDNode *Range = getRangeMetadata(I); 10103 if (!Range) 10104 return Op; 10105 10106 ConstantRange CR = getConstantRangeFromMetadata(*Range); 10107 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 10108 return Op; 10109 10110 APInt Lo = CR.getUnsignedMin(); 10111 if (!Lo.isMinValue()) 10112 return Op; 10113 10114 APInt Hi = CR.getUnsignedMax(); 10115 unsigned Bits = std::max(Hi.getActiveBits(), 10116 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 10117 10118 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 10119 10120 SDLoc SL = getCurSDLoc(); 10121 10122 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 10123 DAG.getValueType(SmallVT)); 10124 unsigned NumVals = Op.getNode()->getNumValues(); 10125 if (NumVals == 1) 10126 return ZExt; 10127 10128 SmallVector<SDValue, 4> Ops; 10129 10130 Ops.push_back(ZExt); 10131 for (unsigned I = 1; I != NumVals; ++I) 10132 Ops.push_back(Op.getValue(I)); 10133 10134 return DAG.getMergeValues(Ops, SL); 10135 } 10136 10137 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 10138 /// the call being lowered. 10139 /// 10140 /// This is a helper for lowering intrinsics that follow a target calling 10141 /// convention or require stack pointer adjustment. Only a subset of the 10142 /// intrinsic's operands need to participate in the calling convention. 10143 void SelectionDAGBuilder::populateCallLoweringInfo( 10144 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 10145 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 10146 AttributeSet RetAttrs, bool IsPatchPoint) { 10147 TargetLowering::ArgListTy Args; 10148 Args.reserve(NumArgs); 10149 10150 // Populate the argument list. 10151 // Attributes for args start at offset 1, after the return attribute. 10152 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 10153 ArgI != ArgE; ++ArgI) { 10154 const Value *V = Call->getOperand(ArgI); 10155 10156 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 10157 10158 TargetLowering::ArgListEntry Entry; 10159 Entry.Node = getValue(V); 10160 Entry.Ty = V->getType(); 10161 Entry.setAttributes(Call, ArgI); 10162 Args.push_back(Entry); 10163 } 10164 10165 CLI.setDebugLoc(getCurSDLoc()) 10166 .setChain(getRoot()) 10167 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 10168 RetAttrs) 10169 .setDiscardResult(Call->use_empty()) 10170 .setIsPatchPoint(IsPatchPoint) 10171 .setIsPreallocated( 10172 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 10173 } 10174 10175 /// Add a stack map intrinsic call's live variable operands to a stackmap 10176 /// or patchpoint target node's operand list. 10177 /// 10178 /// Constants are converted to TargetConstants purely as an optimization to 10179 /// avoid constant materialization and register allocation. 10180 /// 10181 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 10182 /// generate addess computation nodes, and so FinalizeISel can convert the 10183 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10184 /// address materialization and register allocation, but may also be required 10185 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10186 /// alloca in the entry block, then the runtime may assume that the alloca's 10187 /// StackMap location can be read immediately after compilation and that the 10188 /// location is valid at any point during execution (this is similar to the 10189 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10190 /// only available in a register, then the runtime would need to trap when 10191 /// execution reaches the StackMap in order to read the alloca's location. 10192 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10193 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10194 SelectionDAGBuilder &Builder) { 10195 SelectionDAG &DAG = Builder.DAG; 10196 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10197 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10198 10199 // Things on the stack are pointer-typed, meaning that they are already 10200 // legal and can be emitted directly to target nodes. 10201 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10202 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10203 } else { 10204 // Otherwise emit a target independent node to be legalised. 10205 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10206 } 10207 } 10208 } 10209 10210 /// Lower llvm.experimental.stackmap. 10211 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10212 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10213 // [live variables...]) 10214 10215 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10216 10217 SDValue Chain, InGlue, Callee; 10218 SmallVector<SDValue, 32> Ops; 10219 10220 SDLoc DL = getCurSDLoc(); 10221 Callee = getValue(CI.getCalledOperand()); 10222 10223 // The stackmap intrinsic only records the live variables (the arguments 10224 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10225 // intrinsic, this won't be lowered to a function call. This means we don't 10226 // have to worry about calling conventions and target specific lowering code. 10227 // Instead we perform the call lowering right here. 10228 // 10229 // chain, flag = CALLSEQ_START(chain, 0, 0) 10230 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10231 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10232 // 10233 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10234 InGlue = Chain.getValue(1); 10235 10236 // Add the STACKMAP operands, starting with DAG house-keeping. 10237 Ops.push_back(Chain); 10238 Ops.push_back(InGlue); 10239 10240 // Add the <id>, <numShadowBytes> operands. 10241 // 10242 // These do not require legalisation, and can be emitted directly to target 10243 // constant nodes. 10244 SDValue ID = getValue(CI.getArgOperand(0)); 10245 assert(ID.getValueType() == MVT::i64); 10246 SDValue IDConst = 10247 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10248 Ops.push_back(IDConst); 10249 10250 SDValue Shad = getValue(CI.getArgOperand(1)); 10251 assert(Shad.getValueType() == MVT::i32); 10252 SDValue ShadConst = 10253 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10254 Ops.push_back(ShadConst); 10255 10256 // Add the live variables. 10257 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10258 10259 // Create the STACKMAP node. 10260 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10261 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10262 InGlue = Chain.getValue(1); 10263 10264 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10265 10266 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10267 10268 // Set the root to the target-lowered call chain. 10269 DAG.setRoot(Chain); 10270 10271 // Inform the Frame Information that we have a stackmap in this function. 10272 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10273 } 10274 10275 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10276 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10277 const BasicBlock *EHPadBB) { 10278 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>, 10279 // i32 <numBytes>, 10280 // i8* <target>, 10281 // i32 <numArgs>, 10282 // [Args...], 10283 // [live variables...]) 10284 10285 CallingConv::ID CC = CB.getCallingConv(); 10286 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10287 bool HasDef = !CB.getType()->isVoidTy(); 10288 SDLoc dl = getCurSDLoc(); 10289 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10290 10291 // Handle immediate and symbolic callees. 10292 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10293 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10294 /*isTarget=*/true); 10295 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10296 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10297 SDLoc(SymbolicCallee), 10298 SymbolicCallee->getValueType(0)); 10299 10300 // Get the real number of arguments participating in the call <numArgs> 10301 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10302 unsigned NumArgs = NArgVal->getAsZExtVal(); 10303 10304 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10305 // Intrinsics include all meta-operands up to but not including CC. 10306 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10307 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10308 "Not enough arguments provided to the patchpoint intrinsic"); 10309 10310 // For AnyRegCC the arguments are lowered later on manually. 10311 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10312 Type *ReturnTy = 10313 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10314 10315 TargetLowering::CallLoweringInfo CLI(DAG); 10316 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10317 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10318 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10319 10320 SDNode *CallEnd = Result.second.getNode(); 10321 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10322 CallEnd = CallEnd->getOperand(0).getNode(); 10323 10324 /// Get a call instruction from the call sequence chain. 10325 /// Tail calls are not allowed. 10326 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10327 "Expected a callseq node."); 10328 SDNode *Call = CallEnd->getOperand(0).getNode(); 10329 bool HasGlue = Call->getGluedNode(); 10330 10331 // Replace the target specific call node with the patchable intrinsic. 10332 SmallVector<SDValue, 8> Ops; 10333 10334 // Push the chain. 10335 Ops.push_back(*(Call->op_begin())); 10336 10337 // Optionally, push the glue (if any). 10338 if (HasGlue) 10339 Ops.push_back(*(Call->op_end() - 1)); 10340 10341 // Push the register mask info. 10342 if (HasGlue) 10343 Ops.push_back(*(Call->op_end() - 2)); 10344 else 10345 Ops.push_back(*(Call->op_end() - 1)); 10346 10347 // Add the <id> and <numBytes> constants. 10348 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10349 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10350 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10351 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10352 10353 // Add the callee. 10354 Ops.push_back(Callee); 10355 10356 // Adjust <numArgs> to account for any arguments that have been passed on the 10357 // stack instead. 10358 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10359 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10360 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10361 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10362 10363 // Add the calling convention 10364 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10365 10366 // Add the arguments we omitted previously. The register allocator should 10367 // place these in any free register. 10368 if (IsAnyRegCC) 10369 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10370 Ops.push_back(getValue(CB.getArgOperand(i))); 10371 10372 // Push the arguments from the call instruction. 10373 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10374 Ops.append(Call->op_begin() + 2, e); 10375 10376 // Push live variables for the stack map. 10377 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10378 10379 SDVTList NodeTys; 10380 if (IsAnyRegCC && HasDef) { 10381 // Create the return types based on the intrinsic definition 10382 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10383 SmallVector<EVT, 3> ValueVTs; 10384 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10385 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10386 10387 // There is always a chain and a glue type at the end 10388 ValueVTs.push_back(MVT::Other); 10389 ValueVTs.push_back(MVT::Glue); 10390 NodeTys = DAG.getVTList(ValueVTs); 10391 } else 10392 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10393 10394 // Replace the target specific call node with a PATCHPOINT node. 10395 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10396 10397 // Update the NodeMap. 10398 if (HasDef) { 10399 if (IsAnyRegCC) 10400 setValue(&CB, SDValue(PPV.getNode(), 0)); 10401 else 10402 setValue(&CB, Result.first); 10403 } 10404 10405 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10406 // call sequence. Furthermore the location of the chain and glue can change 10407 // when the AnyReg calling convention is used and the intrinsic returns a 10408 // value. 10409 if (IsAnyRegCC && HasDef) { 10410 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10411 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10412 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10413 } else 10414 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10415 DAG.DeleteNode(Call); 10416 10417 // Inform the Frame Information that we have a patchpoint in this function. 10418 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10419 } 10420 10421 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10422 unsigned Intrinsic) { 10423 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10424 SDValue Op1 = getValue(I.getArgOperand(0)); 10425 SDValue Op2; 10426 if (I.arg_size() > 1) 10427 Op2 = getValue(I.getArgOperand(1)); 10428 SDLoc dl = getCurSDLoc(); 10429 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10430 SDValue Res; 10431 SDNodeFlags SDFlags; 10432 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10433 SDFlags.copyFMF(*FPMO); 10434 10435 switch (Intrinsic) { 10436 case Intrinsic::vector_reduce_fadd: 10437 if (SDFlags.hasAllowReassociation()) 10438 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10439 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10440 SDFlags); 10441 else 10442 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10443 break; 10444 case Intrinsic::vector_reduce_fmul: 10445 if (SDFlags.hasAllowReassociation()) 10446 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10447 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10448 SDFlags); 10449 else 10450 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10451 break; 10452 case Intrinsic::vector_reduce_add: 10453 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10454 break; 10455 case Intrinsic::vector_reduce_mul: 10456 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10457 break; 10458 case Intrinsic::vector_reduce_and: 10459 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10460 break; 10461 case Intrinsic::vector_reduce_or: 10462 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10463 break; 10464 case Intrinsic::vector_reduce_xor: 10465 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10466 break; 10467 case Intrinsic::vector_reduce_smax: 10468 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10469 break; 10470 case Intrinsic::vector_reduce_smin: 10471 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10472 break; 10473 case Intrinsic::vector_reduce_umax: 10474 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10475 break; 10476 case Intrinsic::vector_reduce_umin: 10477 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10478 break; 10479 case Intrinsic::vector_reduce_fmax: 10480 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10481 break; 10482 case Intrinsic::vector_reduce_fmin: 10483 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10484 break; 10485 case Intrinsic::vector_reduce_fmaximum: 10486 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10487 break; 10488 case Intrinsic::vector_reduce_fminimum: 10489 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10490 break; 10491 default: 10492 llvm_unreachable("Unhandled vector reduce intrinsic"); 10493 } 10494 setValue(&I, Res); 10495 } 10496 10497 /// Returns an AttributeList representing the attributes applied to the return 10498 /// value of the given call. 10499 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10500 SmallVector<Attribute::AttrKind, 2> Attrs; 10501 if (CLI.RetSExt) 10502 Attrs.push_back(Attribute::SExt); 10503 if (CLI.RetZExt) 10504 Attrs.push_back(Attribute::ZExt); 10505 if (CLI.IsInReg) 10506 Attrs.push_back(Attribute::InReg); 10507 10508 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10509 Attrs); 10510 } 10511 10512 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10513 /// implementation, which just calls LowerCall. 10514 /// FIXME: When all targets are 10515 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10516 std::pair<SDValue, SDValue> 10517 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10518 // Handle the incoming return values from the call. 10519 CLI.Ins.clear(); 10520 Type *OrigRetTy = CLI.RetTy; 10521 SmallVector<EVT, 4> RetTys; 10522 SmallVector<TypeSize, 4> Offsets; 10523 auto &DL = CLI.DAG.getDataLayout(); 10524 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 10525 10526 if (CLI.IsPostTypeLegalization) { 10527 // If we are lowering a libcall after legalization, split the return type. 10528 SmallVector<EVT, 4> OldRetTys; 10529 SmallVector<TypeSize, 4> OldOffsets; 10530 RetTys.swap(OldRetTys); 10531 Offsets.swap(OldOffsets); 10532 10533 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10534 EVT RetVT = OldRetTys[i]; 10535 uint64_t Offset = OldOffsets[i]; 10536 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10537 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10538 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10539 RetTys.append(NumRegs, RegisterVT); 10540 for (unsigned j = 0; j != NumRegs; ++j) 10541 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ)); 10542 } 10543 } 10544 10545 SmallVector<ISD::OutputArg, 4> Outs; 10546 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10547 10548 bool CanLowerReturn = 10549 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10550 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10551 10552 SDValue DemoteStackSlot; 10553 int DemoteStackIdx = -100; 10554 if (!CanLowerReturn) { 10555 // FIXME: equivalent assert? 10556 // assert(!CS.hasInAllocaArgument() && 10557 // "sret demotion is incompatible with inalloca"); 10558 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10559 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10560 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10561 DemoteStackIdx = 10562 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10563 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10564 DL.getAllocaAddrSpace()); 10565 10566 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10567 ArgListEntry Entry; 10568 Entry.Node = DemoteStackSlot; 10569 Entry.Ty = StackSlotPtrType; 10570 Entry.IsSExt = false; 10571 Entry.IsZExt = false; 10572 Entry.IsInReg = false; 10573 Entry.IsSRet = true; 10574 Entry.IsNest = false; 10575 Entry.IsByVal = false; 10576 Entry.IsByRef = false; 10577 Entry.IsReturned = false; 10578 Entry.IsSwiftSelf = false; 10579 Entry.IsSwiftAsync = false; 10580 Entry.IsSwiftError = false; 10581 Entry.IsCFGuardTarget = false; 10582 Entry.Alignment = Alignment; 10583 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10584 CLI.NumFixedArgs += 1; 10585 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10586 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10587 10588 // sret demotion isn't compatible with tail-calls, since the sret argument 10589 // points into the callers stack frame. 10590 CLI.IsTailCall = false; 10591 } else { 10592 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10593 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10594 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10595 ISD::ArgFlagsTy Flags; 10596 if (NeedsRegBlock) { 10597 Flags.setInConsecutiveRegs(); 10598 if (I == RetTys.size() - 1) 10599 Flags.setInConsecutiveRegsLast(); 10600 } 10601 EVT VT = RetTys[I]; 10602 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10603 CLI.CallConv, VT); 10604 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10605 CLI.CallConv, VT); 10606 for (unsigned i = 0; i != NumRegs; ++i) { 10607 ISD::InputArg MyFlags; 10608 MyFlags.Flags = Flags; 10609 MyFlags.VT = RegisterVT; 10610 MyFlags.ArgVT = VT; 10611 MyFlags.Used = CLI.IsReturnValueUsed; 10612 if (CLI.RetTy->isPointerTy()) { 10613 MyFlags.Flags.setPointer(); 10614 MyFlags.Flags.setPointerAddrSpace( 10615 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10616 } 10617 if (CLI.RetSExt) 10618 MyFlags.Flags.setSExt(); 10619 if (CLI.RetZExt) 10620 MyFlags.Flags.setZExt(); 10621 if (CLI.IsInReg) 10622 MyFlags.Flags.setInReg(); 10623 CLI.Ins.push_back(MyFlags); 10624 } 10625 } 10626 } 10627 10628 // We push in swifterror return as the last element of CLI.Ins. 10629 ArgListTy &Args = CLI.getArgs(); 10630 if (supportSwiftError()) { 10631 for (const ArgListEntry &Arg : Args) { 10632 if (Arg.IsSwiftError) { 10633 ISD::InputArg MyFlags; 10634 MyFlags.VT = getPointerTy(DL); 10635 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10636 MyFlags.Flags.setSwiftError(); 10637 CLI.Ins.push_back(MyFlags); 10638 } 10639 } 10640 } 10641 10642 // Handle all of the outgoing arguments. 10643 CLI.Outs.clear(); 10644 CLI.OutVals.clear(); 10645 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10646 SmallVector<EVT, 4> ValueVTs; 10647 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10648 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10649 Type *FinalType = Args[i].Ty; 10650 if (Args[i].IsByVal) 10651 FinalType = Args[i].IndirectType; 10652 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10653 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10654 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10655 ++Value) { 10656 EVT VT = ValueVTs[Value]; 10657 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10658 SDValue Op = SDValue(Args[i].Node.getNode(), 10659 Args[i].Node.getResNo() + Value); 10660 ISD::ArgFlagsTy Flags; 10661 10662 // Certain targets (such as MIPS), may have a different ABI alignment 10663 // for a type depending on the context. Give the target a chance to 10664 // specify the alignment it wants. 10665 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10666 Flags.setOrigAlign(OriginalAlignment); 10667 10668 if (Args[i].Ty->isPointerTy()) { 10669 Flags.setPointer(); 10670 Flags.setPointerAddrSpace( 10671 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10672 } 10673 if (Args[i].IsZExt) 10674 Flags.setZExt(); 10675 if (Args[i].IsSExt) 10676 Flags.setSExt(); 10677 if (Args[i].IsInReg) { 10678 // If we are using vectorcall calling convention, a structure that is 10679 // passed InReg - is surely an HVA 10680 if (CLI.CallConv == CallingConv::X86_VectorCall && 10681 isa<StructType>(FinalType)) { 10682 // The first value of a structure is marked 10683 if (0 == Value) 10684 Flags.setHvaStart(); 10685 Flags.setHva(); 10686 } 10687 // Set InReg Flag 10688 Flags.setInReg(); 10689 } 10690 if (Args[i].IsSRet) 10691 Flags.setSRet(); 10692 if (Args[i].IsSwiftSelf) 10693 Flags.setSwiftSelf(); 10694 if (Args[i].IsSwiftAsync) 10695 Flags.setSwiftAsync(); 10696 if (Args[i].IsSwiftError) 10697 Flags.setSwiftError(); 10698 if (Args[i].IsCFGuardTarget) 10699 Flags.setCFGuardTarget(); 10700 if (Args[i].IsByVal) 10701 Flags.setByVal(); 10702 if (Args[i].IsByRef) 10703 Flags.setByRef(); 10704 if (Args[i].IsPreallocated) { 10705 Flags.setPreallocated(); 10706 // Set the byval flag for CCAssignFn callbacks that don't know about 10707 // preallocated. This way we can know how many bytes we should've 10708 // allocated and how many bytes a callee cleanup function will pop. If 10709 // we port preallocated to more targets, we'll have to add custom 10710 // preallocated handling in the various CC lowering callbacks. 10711 Flags.setByVal(); 10712 } 10713 if (Args[i].IsInAlloca) { 10714 Flags.setInAlloca(); 10715 // Set the byval flag for CCAssignFn callbacks that don't know about 10716 // inalloca. This way we can know how many bytes we should've allocated 10717 // and how many bytes a callee cleanup function will pop. If we port 10718 // inalloca to more targets, we'll have to add custom inalloca handling 10719 // in the various CC lowering callbacks. 10720 Flags.setByVal(); 10721 } 10722 Align MemAlign; 10723 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10724 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10725 Flags.setByValSize(FrameSize); 10726 10727 // info is not there but there are cases it cannot get right. 10728 if (auto MA = Args[i].Alignment) 10729 MemAlign = *MA; 10730 else 10731 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10732 } else if (auto MA = Args[i].Alignment) { 10733 MemAlign = *MA; 10734 } else { 10735 MemAlign = OriginalAlignment; 10736 } 10737 Flags.setMemAlign(MemAlign); 10738 if (Args[i].IsNest) 10739 Flags.setNest(); 10740 if (NeedsRegBlock) 10741 Flags.setInConsecutiveRegs(); 10742 10743 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10744 CLI.CallConv, VT); 10745 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10746 CLI.CallConv, VT); 10747 SmallVector<SDValue, 4> Parts(NumParts); 10748 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10749 10750 if (Args[i].IsSExt) 10751 ExtendKind = ISD::SIGN_EXTEND; 10752 else if (Args[i].IsZExt) 10753 ExtendKind = ISD::ZERO_EXTEND; 10754 10755 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10756 // for now. 10757 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10758 CanLowerReturn) { 10759 assert((CLI.RetTy == Args[i].Ty || 10760 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10761 CLI.RetTy->getPointerAddressSpace() == 10762 Args[i].Ty->getPointerAddressSpace())) && 10763 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10764 // Before passing 'returned' to the target lowering code, ensure that 10765 // either the register MVT and the actual EVT are the same size or that 10766 // the return value and argument are extended in the same way; in these 10767 // cases it's safe to pass the argument register value unchanged as the 10768 // return register value (although it's at the target's option whether 10769 // to do so) 10770 // TODO: allow code generation to take advantage of partially preserved 10771 // registers rather than clobbering the entire register when the 10772 // parameter extension method is not compatible with the return 10773 // extension method 10774 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10775 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10776 CLI.RetZExt == Args[i].IsZExt)) 10777 Flags.setReturned(); 10778 } 10779 10780 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10781 CLI.CallConv, ExtendKind); 10782 10783 for (unsigned j = 0; j != NumParts; ++j) { 10784 // if it isn't first piece, alignment must be 1 10785 // For scalable vectors the scalable part is currently handled 10786 // by individual targets, so we just use the known minimum size here. 10787 ISD::OutputArg MyFlags( 10788 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10789 i < CLI.NumFixedArgs, i, 10790 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10791 if (NumParts > 1 && j == 0) 10792 MyFlags.Flags.setSplit(); 10793 else if (j != 0) { 10794 MyFlags.Flags.setOrigAlign(Align(1)); 10795 if (j == NumParts - 1) 10796 MyFlags.Flags.setSplitEnd(); 10797 } 10798 10799 CLI.Outs.push_back(MyFlags); 10800 CLI.OutVals.push_back(Parts[j]); 10801 } 10802 10803 if (NeedsRegBlock && Value == NumValues - 1) 10804 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10805 } 10806 } 10807 10808 SmallVector<SDValue, 4> InVals; 10809 CLI.Chain = LowerCall(CLI, InVals); 10810 10811 // Update CLI.InVals to use outside of this function. 10812 CLI.InVals = InVals; 10813 10814 // Verify that the target's LowerCall behaved as expected. 10815 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10816 "LowerCall didn't return a valid chain!"); 10817 assert((!CLI.IsTailCall || InVals.empty()) && 10818 "LowerCall emitted a return value for a tail call!"); 10819 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10820 "LowerCall didn't emit the correct number of values!"); 10821 10822 // For a tail call, the return value is merely live-out and there aren't 10823 // any nodes in the DAG representing it. Return a special value to 10824 // indicate that a tail call has been emitted and no more Instructions 10825 // should be processed in the current block. 10826 if (CLI.IsTailCall) { 10827 CLI.DAG.setRoot(CLI.Chain); 10828 return std::make_pair(SDValue(), SDValue()); 10829 } 10830 10831 #ifndef NDEBUG 10832 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10833 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10834 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10835 "LowerCall emitted a value with the wrong type!"); 10836 } 10837 #endif 10838 10839 SmallVector<SDValue, 4> ReturnValues; 10840 if (!CanLowerReturn) { 10841 // The instruction result is the result of loading from the 10842 // hidden sret parameter. 10843 SmallVector<EVT, 1> PVTs; 10844 Type *PtrRetTy = 10845 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10846 10847 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10848 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10849 EVT PtrVT = PVTs[0]; 10850 10851 unsigned NumValues = RetTys.size(); 10852 ReturnValues.resize(NumValues); 10853 SmallVector<SDValue, 4> Chains(NumValues); 10854 10855 // An aggregate return value cannot wrap around the address space, so 10856 // offsets to its parts don't wrap either. 10857 SDNodeFlags Flags; 10858 Flags.setNoUnsignedWrap(true); 10859 10860 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10861 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10862 for (unsigned i = 0; i < NumValues; ++i) { 10863 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10864 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10865 PtrVT), Flags); 10866 SDValue L = CLI.DAG.getLoad( 10867 RetTys[i], CLI.DL, CLI.Chain, Add, 10868 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10869 DemoteStackIdx, Offsets[i]), 10870 HiddenSRetAlign); 10871 ReturnValues[i] = L; 10872 Chains[i] = L.getValue(1); 10873 } 10874 10875 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10876 } else { 10877 // Collect the legal value parts into potentially illegal values 10878 // that correspond to the original function's return values. 10879 std::optional<ISD::NodeType> AssertOp; 10880 if (CLI.RetSExt) 10881 AssertOp = ISD::AssertSext; 10882 else if (CLI.RetZExt) 10883 AssertOp = ISD::AssertZext; 10884 unsigned CurReg = 0; 10885 for (EVT VT : RetTys) { 10886 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10887 CLI.CallConv, VT); 10888 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10889 CLI.CallConv, VT); 10890 10891 ReturnValues.push_back(getCopyFromParts( 10892 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 10893 CLI.Chain, CLI.CallConv, AssertOp)); 10894 CurReg += NumRegs; 10895 } 10896 10897 // For a function returning void, there is no return value. We can't create 10898 // such a node, so we just return a null return value in that case. In 10899 // that case, nothing will actually look at the value. 10900 if (ReturnValues.empty()) 10901 return std::make_pair(SDValue(), CLI.Chain); 10902 } 10903 10904 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10905 CLI.DAG.getVTList(RetTys), ReturnValues); 10906 return std::make_pair(Res, CLI.Chain); 10907 } 10908 10909 /// Places new result values for the node in Results (their number 10910 /// and types must exactly match those of the original return values of 10911 /// the node), or leaves Results empty, which indicates that the node is not 10912 /// to be custom lowered after all. 10913 void TargetLowering::LowerOperationWrapper(SDNode *N, 10914 SmallVectorImpl<SDValue> &Results, 10915 SelectionDAG &DAG) const { 10916 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10917 10918 if (!Res.getNode()) 10919 return; 10920 10921 // If the original node has one result, take the return value from 10922 // LowerOperation as is. It might not be result number 0. 10923 if (N->getNumValues() == 1) { 10924 Results.push_back(Res); 10925 return; 10926 } 10927 10928 // If the original node has multiple results, then the return node should 10929 // have the same number of results. 10930 assert((N->getNumValues() == Res->getNumValues()) && 10931 "Lowering returned the wrong number of results!"); 10932 10933 // Places new result values base on N result number. 10934 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10935 Results.push_back(Res.getValue(I)); 10936 } 10937 10938 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10939 llvm_unreachable("LowerOperation not implemented for this target!"); 10940 } 10941 10942 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10943 unsigned Reg, 10944 ISD::NodeType ExtendType) { 10945 SDValue Op = getNonRegisterValue(V); 10946 assert((Op.getOpcode() != ISD::CopyFromReg || 10947 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10948 "Copy from a reg to the same reg!"); 10949 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10950 10951 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10952 // If this is an InlineAsm we have to match the registers required, not the 10953 // notional registers required by the type. 10954 10955 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10956 std::nullopt); // This is not an ABI copy. 10957 SDValue Chain = DAG.getEntryNode(); 10958 10959 if (ExtendType == ISD::ANY_EXTEND) { 10960 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10961 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10962 ExtendType = PreferredExtendIt->second; 10963 } 10964 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10965 PendingExports.push_back(Chain); 10966 } 10967 10968 #include "llvm/CodeGen/SelectionDAGISel.h" 10969 10970 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10971 /// entry block, return true. This includes arguments used by switches, since 10972 /// the switch may expand into multiple basic blocks. 10973 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10974 // With FastISel active, we may be splitting blocks, so force creation 10975 // of virtual registers for all non-dead arguments. 10976 if (FastISel) 10977 return A->use_empty(); 10978 10979 const BasicBlock &Entry = A->getParent()->front(); 10980 for (const User *U : A->users()) 10981 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10982 return false; // Use not in entry block. 10983 10984 return true; 10985 } 10986 10987 using ArgCopyElisionMapTy = 10988 DenseMap<const Argument *, 10989 std::pair<const AllocaInst *, const StoreInst *>>; 10990 10991 /// Scan the entry block of the function in FuncInfo for arguments that look 10992 /// like copies into a local alloca. Record any copied arguments in 10993 /// ArgCopyElisionCandidates. 10994 static void 10995 findArgumentCopyElisionCandidates(const DataLayout &DL, 10996 FunctionLoweringInfo *FuncInfo, 10997 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10998 // Record the state of every static alloca used in the entry block. Argument 10999 // allocas are all used in the entry block, so we need approximately as many 11000 // entries as we have arguments. 11001 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 11002 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 11003 unsigned NumArgs = FuncInfo->Fn->arg_size(); 11004 StaticAllocas.reserve(NumArgs * 2); 11005 11006 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 11007 if (!V) 11008 return nullptr; 11009 V = V->stripPointerCasts(); 11010 const auto *AI = dyn_cast<AllocaInst>(V); 11011 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 11012 return nullptr; 11013 auto Iter = StaticAllocas.insert({AI, Unknown}); 11014 return &Iter.first->second; 11015 }; 11016 11017 // Look for stores of arguments to static allocas. Look through bitcasts and 11018 // GEPs to handle type coercions, as long as the alloca is fully initialized 11019 // by the store. Any non-store use of an alloca escapes it and any subsequent 11020 // unanalyzed store might write it. 11021 // FIXME: Handle structs initialized with multiple stores. 11022 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 11023 // Look for stores, and handle non-store uses conservatively. 11024 const auto *SI = dyn_cast<StoreInst>(&I); 11025 if (!SI) { 11026 // We will look through cast uses, so ignore them completely. 11027 if (I.isCast()) 11028 continue; 11029 // Ignore debug info and pseudo op intrinsics, they don't escape or store 11030 // to allocas. 11031 if (I.isDebugOrPseudoInst()) 11032 continue; 11033 // This is an unknown instruction. Assume it escapes or writes to all 11034 // static alloca operands. 11035 for (const Use &U : I.operands()) { 11036 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 11037 *Info = StaticAllocaInfo::Clobbered; 11038 } 11039 continue; 11040 } 11041 11042 // If the stored value is a static alloca, mark it as escaped. 11043 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 11044 *Info = StaticAllocaInfo::Clobbered; 11045 11046 // Check if the destination is a static alloca. 11047 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 11048 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 11049 if (!Info) 11050 continue; 11051 const AllocaInst *AI = cast<AllocaInst>(Dst); 11052 11053 // Skip allocas that have been initialized or clobbered. 11054 if (*Info != StaticAllocaInfo::Unknown) 11055 continue; 11056 11057 // Check if the stored value is an argument, and that this store fully 11058 // initializes the alloca. 11059 // If the argument type has padding bits we can't directly forward a pointer 11060 // as the upper bits may contain garbage. 11061 // Don't elide copies from the same argument twice. 11062 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 11063 const auto *Arg = dyn_cast<Argument>(Val); 11064 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 11065 Arg->getType()->isEmptyTy() || 11066 DL.getTypeStoreSize(Arg->getType()) != 11067 DL.getTypeAllocSize(AI->getAllocatedType()) || 11068 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 11069 ArgCopyElisionCandidates.count(Arg)) { 11070 *Info = StaticAllocaInfo::Clobbered; 11071 continue; 11072 } 11073 11074 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 11075 << '\n'); 11076 11077 // Mark this alloca and store for argument copy elision. 11078 *Info = StaticAllocaInfo::Elidable; 11079 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 11080 11081 // Stop scanning if we've seen all arguments. This will happen early in -O0 11082 // builds, which is useful, because -O0 builds have large entry blocks and 11083 // many allocas. 11084 if (ArgCopyElisionCandidates.size() == NumArgs) 11085 break; 11086 } 11087 } 11088 11089 /// Try to elide argument copies from memory into a local alloca. Succeeds if 11090 /// ArgVal is a load from a suitable fixed stack object. 11091 static void tryToElideArgumentCopy( 11092 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 11093 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 11094 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 11095 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 11096 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 11097 // Check if this is a load from a fixed stack object. 11098 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 11099 if (!LNode) 11100 return; 11101 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 11102 if (!FINode) 11103 return; 11104 11105 // Check that the fixed stack object is the right size and alignment. 11106 // Look at the alignment that the user wrote on the alloca instead of looking 11107 // at the stack object. 11108 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 11109 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 11110 const AllocaInst *AI = ArgCopyIter->second.first; 11111 int FixedIndex = FINode->getIndex(); 11112 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 11113 int OldIndex = AllocaIndex; 11114 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 11115 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 11116 LLVM_DEBUG( 11117 dbgs() << " argument copy elision failed due to bad fixed stack " 11118 "object size\n"); 11119 return; 11120 } 11121 Align RequiredAlignment = AI->getAlign(); 11122 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 11123 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 11124 "greater than stack argument alignment (" 11125 << DebugStr(RequiredAlignment) << " vs " 11126 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 11127 return; 11128 } 11129 11130 // Perform the elision. Delete the old stack object and replace its only use 11131 // in the variable info map. Mark the stack object as mutable. 11132 LLVM_DEBUG({ 11133 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 11134 << " Replacing frame index " << OldIndex << " with " << FixedIndex 11135 << '\n'; 11136 }); 11137 MFI.RemoveStackObject(OldIndex); 11138 MFI.setIsImmutableObjectIndex(FixedIndex, false); 11139 AllocaIndex = FixedIndex; 11140 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 11141 for (SDValue ArgVal : ArgVals) 11142 Chains.push_back(ArgVal.getValue(1)); 11143 11144 // Avoid emitting code for the store implementing the copy. 11145 const StoreInst *SI = ArgCopyIter->second.second; 11146 ElidedArgCopyInstrs.insert(SI); 11147 11148 // Check for uses of the argument again so that we can avoid exporting ArgVal 11149 // if it is't used by anything other than the store. 11150 for (const Value *U : Arg.users()) { 11151 if (U != SI) { 11152 ArgHasUses = true; 11153 break; 11154 } 11155 } 11156 } 11157 11158 void SelectionDAGISel::LowerArguments(const Function &F) { 11159 SelectionDAG &DAG = SDB->DAG; 11160 SDLoc dl = SDB->getCurSDLoc(); 11161 const DataLayout &DL = DAG.getDataLayout(); 11162 SmallVector<ISD::InputArg, 16> Ins; 11163 11164 // In Naked functions we aren't going to save any registers. 11165 if (F.hasFnAttribute(Attribute::Naked)) 11166 return; 11167 11168 if (!FuncInfo->CanLowerReturn) { 11169 // Put in an sret pointer parameter before all the other parameters. 11170 SmallVector<EVT, 1> ValueVTs; 11171 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11172 PointerType::get(F.getContext(), 11173 DAG.getDataLayout().getAllocaAddrSpace()), 11174 ValueVTs); 11175 11176 // NOTE: Assuming that a pointer will never break down to more than one VT 11177 // or one register. 11178 ISD::ArgFlagsTy Flags; 11179 Flags.setSRet(); 11180 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 11181 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 11182 ISD::InputArg::NoArgIndex, 0); 11183 Ins.push_back(RetArg); 11184 } 11185 11186 // Look for stores of arguments to static allocas. Mark such arguments with a 11187 // flag to ask the target to give us the memory location of that argument if 11188 // available. 11189 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11190 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11191 ArgCopyElisionCandidates); 11192 11193 // Set up the incoming argument description vector. 11194 for (const Argument &Arg : F.args()) { 11195 unsigned ArgNo = Arg.getArgNo(); 11196 SmallVector<EVT, 4> ValueVTs; 11197 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11198 bool isArgValueUsed = !Arg.use_empty(); 11199 unsigned PartBase = 0; 11200 Type *FinalType = Arg.getType(); 11201 if (Arg.hasAttribute(Attribute::ByVal)) 11202 FinalType = Arg.getParamByValType(); 11203 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11204 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11205 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11206 Value != NumValues; ++Value) { 11207 EVT VT = ValueVTs[Value]; 11208 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11209 ISD::ArgFlagsTy Flags; 11210 11211 11212 if (Arg.getType()->isPointerTy()) { 11213 Flags.setPointer(); 11214 Flags.setPointerAddrSpace( 11215 cast<PointerType>(Arg.getType())->getAddressSpace()); 11216 } 11217 if (Arg.hasAttribute(Attribute::ZExt)) 11218 Flags.setZExt(); 11219 if (Arg.hasAttribute(Attribute::SExt)) 11220 Flags.setSExt(); 11221 if (Arg.hasAttribute(Attribute::InReg)) { 11222 // If we are using vectorcall calling convention, a structure that is 11223 // passed InReg - is surely an HVA 11224 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11225 isa<StructType>(Arg.getType())) { 11226 // The first value of a structure is marked 11227 if (0 == Value) 11228 Flags.setHvaStart(); 11229 Flags.setHva(); 11230 } 11231 // Set InReg Flag 11232 Flags.setInReg(); 11233 } 11234 if (Arg.hasAttribute(Attribute::StructRet)) 11235 Flags.setSRet(); 11236 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11237 Flags.setSwiftSelf(); 11238 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11239 Flags.setSwiftAsync(); 11240 if (Arg.hasAttribute(Attribute::SwiftError)) 11241 Flags.setSwiftError(); 11242 if (Arg.hasAttribute(Attribute::ByVal)) 11243 Flags.setByVal(); 11244 if (Arg.hasAttribute(Attribute::ByRef)) 11245 Flags.setByRef(); 11246 if (Arg.hasAttribute(Attribute::InAlloca)) { 11247 Flags.setInAlloca(); 11248 // Set the byval flag for CCAssignFn callbacks that don't know about 11249 // inalloca. This way we can know how many bytes we should've allocated 11250 // and how many bytes a callee cleanup function will pop. If we port 11251 // inalloca to more targets, we'll have to add custom inalloca handling 11252 // in the various CC lowering callbacks. 11253 Flags.setByVal(); 11254 } 11255 if (Arg.hasAttribute(Attribute::Preallocated)) { 11256 Flags.setPreallocated(); 11257 // Set the byval flag for CCAssignFn callbacks that don't know about 11258 // preallocated. This way we can know how many bytes we should've 11259 // allocated and how many bytes a callee cleanup function will pop. If 11260 // we port preallocated to more targets, we'll have to add custom 11261 // preallocated handling in the various CC lowering callbacks. 11262 Flags.setByVal(); 11263 } 11264 11265 // Certain targets (such as MIPS), may have a different ABI alignment 11266 // for a type depending on the context. Give the target a chance to 11267 // specify the alignment it wants. 11268 const Align OriginalAlignment( 11269 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11270 Flags.setOrigAlign(OriginalAlignment); 11271 11272 Align MemAlign; 11273 Type *ArgMemTy = nullptr; 11274 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11275 Flags.isByRef()) { 11276 if (!ArgMemTy) 11277 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11278 11279 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11280 11281 // For in-memory arguments, size and alignment should be passed from FE. 11282 // BE will guess if this info is not there but there are cases it cannot 11283 // get right. 11284 if (auto ParamAlign = Arg.getParamStackAlign()) 11285 MemAlign = *ParamAlign; 11286 else if ((ParamAlign = Arg.getParamAlign())) 11287 MemAlign = *ParamAlign; 11288 else 11289 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11290 if (Flags.isByRef()) 11291 Flags.setByRefSize(MemSize); 11292 else 11293 Flags.setByValSize(MemSize); 11294 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11295 MemAlign = *ParamAlign; 11296 } else { 11297 MemAlign = OriginalAlignment; 11298 } 11299 Flags.setMemAlign(MemAlign); 11300 11301 if (Arg.hasAttribute(Attribute::Nest)) 11302 Flags.setNest(); 11303 if (NeedsRegBlock) 11304 Flags.setInConsecutiveRegs(); 11305 if (ArgCopyElisionCandidates.count(&Arg)) 11306 Flags.setCopyElisionCandidate(); 11307 if (Arg.hasAttribute(Attribute::Returned)) 11308 Flags.setReturned(); 11309 11310 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11311 *CurDAG->getContext(), F.getCallingConv(), VT); 11312 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11313 *CurDAG->getContext(), F.getCallingConv(), VT); 11314 for (unsigned i = 0; i != NumRegs; ++i) { 11315 // For scalable vectors, use the minimum size; individual targets 11316 // are responsible for handling scalable vector arguments and 11317 // return values. 11318 ISD::InputArg MyFlags( 11319 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11320 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11321 if (NumRegs > 1 && i == 0) 11322 MyFlags.Flags.setSplit(); 11323 // if it isn't first piece, alignment must be 1 11324 else if (i > 0) { 11325 MyFlags.Flags.setOrigAlign(Align(1)); 11326 if (i == NumRegs - 1) 11327 MyFlags.Flags.setSplitEnd(); 11328 } 11329 Ins.push_back(MyFlags); 11330 } 11331 if (NeedsRegBlock && Value == NumValues - 1) 11332 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11333 PartBase += VT.getStoreSize().getKnownMinValue(); 11334 } 11335 } 11336 11337 // Call the target to set up the argument values. 11338 SmallVector<SDValue, 8> InVals; 11339 SDValue NewRoot = TLI->LowerFormalArguments( 11340 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11341 11342 // Verify that the target's LowerFormalArguments behaved as expected. 11343 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11344 "LowerFormalArguments didn't return a valid chain!"); 11345 assert(InVals.size() == Ins.size() && 11346 "LowerFormalArguments didn't emit the correct number of values!"); 11347 LLVM_DEBUG({ 11348 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11349 assert(InVals[i].getNode() && 11350 "LowerFormalArguments emitted a null value!"); 11351 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11352 "LowerFormalArguments emitted a value with the wrong type!"); 11353 } 11354 }); 11355 11356 // Update the DAG with the new chain value resulting from argument lowering. 11357 DAG.setRoot(NewRoot); 11358 11359 // Set up the argument values. 11360 unsigned i = 0; 11361 if (!FuncInfo->CanLowerReturn) { 11362 // Create a virtual register for the sret pointer, and put in a copy 11363 // from the sret argument into it. 11364 SmallVector<EVT, 1> ValueVTs; 11365 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11366 PointerType::get(F.getContext(), 11367 DAG.getDataLayout().getAllocaAddrSpace()), 11368 ValueVTs); 11369 MVT VT = ValueVTs[0].getSimpleVT(); 11370 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11371 std::optional<ISD::NodeType> AssertOp; 11372 SDValue ArgValue = 11373 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11374 F.getCallingConv(), AssertOp); 11375 11376 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11377 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11378 Register SRetReg = 11379 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11380 FuncInfo->DemoteRegister = SRetReg; 11381 NewRoot = 11382 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11383 DAG.setRoot(NewRoot); 11384 11385 // i indexes lowered arguments. Bump it past the hidden sret argument. 11386 ++i; 11387 } 11388 11389 SmallVector<SDValue, 4> Chains; 11390 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11391 for (const Argument &Arg : F.args()) { 11392 SmallVector<SDValue, 4> ArgValues; 11393 SmallVector<EVT, 4> ValueVTs; 11394 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11395 unsigned NumValues = ValueVTs.size(); 11396 if (NumValues == 0) 11397 continue; 11398 11399 bool ArgHasUses = !Arg.use_empty(); 11400 11401 // Elide the copying store if the target loaded this argument from a 11402 // suitable fixed stack object. 11403 if (Ins[i].Flags.isCopyElisionCandidate()) { 11404 unsigned NumParts = 0; 11405 for (EVT VT : ValueVTs) 11406 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11407 F.getCallingConv(), VT); 11408 11409 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11410 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11411 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11412 } 11413 11414 // If this argument is unused then remember its value. It is used to generate 11415 // debugging information. 11416 bool isSwiftErrorArg = 11417 TLI->supportSwiftError() && 11418 Arg.hasAttribute(Attribute::SwiftError); 11419 if (!ArgHasUses && !isSwiftErrorArg) { 11420 SDB->setUnusedArgValue(&Arg, InVals[i]); 11421 11422 // Also remember any frame index for use in FastISel. 11423 if (FrameIndexSDNode *FI = 11424 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11425 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11426 } 11427 11428 for (unsigned Val = 0; Val != NumValues; ++Val) { 11429 EVT VT = ValueVTs[Val]; 11430 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11431 F.getCallingConv(), VT); 11432 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11433 *CurDAG->getContext(), F.getCallingConv(), VT); 11434 11435 // Even an apparent 'unused' swifterror argument needs to be returned. So 11436 // we do generate a copy for it that can be used on return from the 11437 // function. 11438 if (ArgHasUses || isSwiftErrorArg) { 11439 std::optional<ISD::NodeType> AssertOp; 11440 if (Arg.hasAttribute(Attribute::SExt)) 11441 AssertOp = ISD::AssertSext; 11442 else if (Arg.hasAttribute(Attribute::ZExt)) 11443 AssertOp = ISD::AssertZext; 11444 11445 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11446 PartVT, VT, nullptr, NewRoot, 11447 F.getCallingConv(), AssertOp)); 11448 } 11449 11450 i += NumParts; 11451 } 11452 11453 // We don't need to do anything else for unused arguments. 11454 if (ArgValues.empty()) 11455 continue; 11456 11457 // Note down frame index. 11458 if (FrameIndexSDNode *FI = 11459 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11460 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11461 11462 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11463 SDB->getCurSDLoc()); 11464 11465 SDB->setValue(&Arg, Res); 11466 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11467 // We want to associate the argument with the frame index, among 11468 // involved operands, that correspond to the lowest address. The 11469 // getCopyFromParts function, called earlier, is swapping the order of 11470 // the operands to BUILD_PAIR depending on endianness. The result of 11471 // that swapping is that the least significant bits of the argument will 11472 // be in the first operand of the BUILD_PAIR node, and the most 11473 // significant bits will be in the second operand. 11474 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11475 if (LoadSDNode *LNode = 11476 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11477 if (FrameIndexSDNode *FI = 11478 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11479 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11480 } 11481 11482 // Analyses past this point are naive and don't expect an assertion. 11483 if (Res.getOpcode() == ISD::AssertZext) 11484 Res = Res.getOperand(0); 11485 11486 // Update the SwiftErrorVRegDefMap. 11487 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11488 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11489 if (Register::isVirtualRegister(Reg)) 11490 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11491 Reg); 11492 } 11493 11494 // If this argument is live outside of the entry block, insert a copy from 11495 // wherever we got it to the vreg that other BB's will reference it as. 11496 if (Res.getOpcode() == ISD::CopyFromReg) { 11497 // If we can, though, try to skip creating an unnecessary vreg. 11498 // FIXME: This isn't very clean... it would be nice to make this more 11499 // general. 11500 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11501 if (Register::isVirtualRegister(Reg)) { 11502 FuncInfo->ValueMap[&Arg] = Reg; 11503 continue; 11504 } 11505 } 11506 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11507 FuncInfo->InitializeRegForValue(&Arg); 11508 SDB->CopyToExportRegsIfNeeded(&Arg); 11509 } 11510 } 11511 11512 if (!Chains.empty()) { 11513 Chains.push_back(NewRoot); 11514 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11515 } 11516 11517 DAG.setRoot(NewRoot); 11518 11519 assert(i == InVals.size() && "Argument register count mismatch!"); 11520 11521 // If any argument copy elisions occurred and we have debug info, update the 11522 // stale frame indices used in the dbg.declare variable info table. 11523 if (!ArgCopyElisionFrameIndexMap.empty()) { 11524 for (MachineFunction::VariableDbgInfo &VI : 11525 MF->getInStackSlotVariableDbgInfo()) { 11526 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11527 if (I != ArgCopyElisionFrameIndexMap.end()) 11528 VI.updateStackSlot(I->second); 11529 } 11530 } 11531 11532 // Finally, if the target has anything special to do, allow it to do so. 11533 emitFunctionEntryCode(); 11534 } 11535 11536 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11537 /// ensure constants are generated when needed. Remember the virtual registers 11538 /// that need to be added to the Machine PHI nodes as input. We cannot just 11539 /// directly add them, because expansion might result in multiple MBB's for one 11540 /// BB. As such, the start of the BB might correspond to a different MBB than 11541 /// the end. 11542 void 11543 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11544 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11545 11546 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11547 11548 // Check PHI nodes in successors that expect a value to be available from this 11549 // block. 11550 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11551 if (!isa<PHINode>(SuccBB->begin())) continue; 11552 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11553 11554 // If this terminator has multiple identical successors (common for 11555 // switches), only handle each succ once. 11556 if (!SuccsHandled.insert(SuccMBB).second) 11557 continue; 11558 11559 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11560 11561 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11562 // nodes and Machine PHI nodes, but the incoming operands have not been 11563 // emitted yet. 11564 for (const PHINode &PN : SuccBB->phis()) { 11565 // Ignore dead phi's. 11566 if (PN.use_empty()) 11567 continue; 11568 11569 // Skip empty types 11570 if (PN.getType()->isEmptyTy()) 11571 continue; 11572 11573 unsigned Reg; 11574 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11575 11576 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11577 unsigned &RegOut = ConstantsOut[C]; 11578 if (RegOut == 0) { 11579 RegOut = FuncInfo.CreateRegs(C); 11580 // We need to zero/sign extend ConstantInt phi operands to match 11581 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11582 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11583 if (auto *CI = dyn_cast<ConstantInt>(C)) 11584 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11585 : ISD::ZERO_EXTEND; 11586 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11587 } 11588 Reg = RegOut; 11589 } else { 11590 DenseMap<const Value *, Register>::iterator I = 11591 FuncInfo.ValueMap.find(PHIOp); 11592 if (I != FuncInfo.ValueMap.end()) 11593 Reg = I->second; 11594 else { 11595 assert(isa<AllocaInst>(PHIOp) && 11596 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11597 "Didn't codegen value into a register!??"); 11598 Reg = FuncInfo.CreateRegs(PHIOp); 11599 CopyValueToVirtualRegister(PHIOp, Reg); 11600 } 11601 } 11602 11603 // Remember that this register needs to added to the machine PHI node as 11604 // the input for this MBB. 11605 SmallVector<EVT, 4> ValueVTs; 11606 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11607 for (EVT VT : ValueVTs) { 11608 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11609 for (unsigned i = 0; i != NumRegisters; ++i) 11610 FuncInfo.PHINodesToUpdate.push_back( 11611 std::make_pair(&*MBBI++, Reg + i)); 11612 Reg += NumRegisters; 11613 } 11614 } 11615 } 11616 11617 ConstantsOut.clear(); 11618 } 11619 11620 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11621 MachineFunction::iterator I(MBB); 11622 if (++I == FuncInfo.MF->end()) 11623 return nullptr; 11624 return &*I; 11625 } 11626 11627 /// During lowering new call nodes can be created (such as memset, etc.). 11628 /// Those will become new roots of the current DAG, but complications arise 11629 /// when they are tail calls. In such cases, the call lowering will update 11630 /// the root, but the builder still needs to know that a tail call has been 11631 /// lowered in order to avoid generating an additional return. 11632 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11633 // If the node is null, we do have a tail call. 11634 if (MaybeTC.getNode() != nullptr) 11635 DAG.setRoot(MaybeTC); 11636 else 11637 HasTailCall = true; 11638 } 11639 11640 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11641 MachineBasicBlock *SwitchMBB, 11642 MachineBasicBlock *DefaultMBB) { 11643 MachineFunction *CurMF = FuncInfo.MF; 11644 MachineBasicBlock *NextMBB = nullptr; 11645 MachineFunction::iterator BBI(W.MBB); 11646 if (++BBI != FuncInfo.MF->end()) 11647 NextMBB = &*BBI; 11648 11649 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11650 11651 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11652 11653 if (Size == 2 && W.MBB == SwitchMBB) { 11654 // If any two of the cases has the same destination, and if one value 11655 // is the same as the other, but has one bit unset that the other has set, 11656 // use bit manipulation to do two compares at once. For example: 11657 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11658 // TODO: This could be extended to merge any 2 cases in switches with 3 11659 // cases. 11660 // TODO: Handle cases where W.CaseBB != SwitchBB. 11661 CaseCluster &Small = *W.FirstCluster; 11662 CaseCluster &Big = *W.LastCluster; 11663 11664 if (Small.Low == Small.High && Big.Low == Big.High && 11665 Small.MBB == Big.MBB) { 11666 const APInt &SmallValue = Small.Low->getValue(); 11667 const APInt &BigValue = Big.Low->getValue(); 11668 11669 // Check that there is only one bit different. 11670 APInt CommonBit = BigValue ^ SmallValue; 11671 if (CommonBit.isPowerOf2()) { 11672 SDValue CondLHS = getValue(Cond); 11673 EVT VT = CondLHS.getValueType(); 11674 SDLoc DL = getCurSDLoc(); 11675 11676 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11677 DAG.getConstant(CommonBit, DL, VT)); 11678 SDValue Cond = DAG.getSetCC( 11679 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11680 ISD::SETEQ); 11681 11682 // Update successor info. 11683 // Both Small and Big will jump to Small.BB, so we sum up the 11684 // probabilities. 11685 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11686 if (BPI) 11687 addSuccessorWithProb( 11688 SwitchMBB, DefaultMBB, 11689 // The default destination is the first successor in IR. 11690 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11691 else 11692 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11693 11694 // Insert the true branch. 11695 SDValue BrCond = 11696 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11697 DAG.getBasicBlock(Small.MBB)); 11698 // Insert the false branch. 11699 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11700 DAG.getBasicBlock(DefaultMBB)); 11701 11702 DAG.setRoot(BrCond); 11703 return; 11704 } 11705 } 11706 } 11707 11708 if (TM.getOptLevel() != CodeGenOptLevel::None) { 11709 // Here, we order cases by probability so the most likely case will be 11710 // checked first. However, two clusters can have the same probability in 11711 // which case their relative ordering is non-deterministic. So we use Low 11712 // as a tie-breaker as clusters are guaranteed to never overlap. 11713 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11714 [](const CaseCluster &a, const CaseCluster &b) { 11715 return a.Prob != b.Prob ? 11716 a.Prob > b.Prob : 11717 a.Low->getValue().slt(b.Low->getValue()); 11718 }); 11719 11720 // Rearrange the case blocks so that the last one falls through if possible 11721 // without changing the order of probabilities. 11722 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11723 --I; 11724 if (I->Prob > W.LastCluster->Prob) 11725 break; 11726 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11727 std::swap(*I, *W.LastCluster); 11728 break; 11729 } 11730 } 11731 } 11732 11733 // Compute total probability. 11734 BranchProbability DefaultProb = W.DefaultProb; 11735 BranchProbability UnhandledProbs = DefaultProb; 11736 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11737 UnhandledProbs += I->Prob; 11738 11739 MachineBasicBlock *CurMBB = W.MBB; 11740 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11741 bool FallthroughUnreachable = false; 11742 MachineBasicBlock *Fallthrough; 11743 if (I == W.LastCluster) { 11744 // For the last cluster, fall through to the default destination. 11745 Fallthrough = DefaultMBB; 11746 FallthroughUnreachable = isa<UnreachableInst>( 11747 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11748 } else { 11749 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11750 CurMF->insert(BBI, Fallthrough); 11751 // Put Cond in a virtual register to make it available from the new blocks. 11752 ExportFromCurrentBlock(Cond); 11753 } 11754 UnhandledProbs -= I->Prob; 11755 11756 switch (I->Kind) { 11757 case CC_JumpTable: { 11758 // FIXME: Optimize away range check based on pivot comparisons. 11759 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11760 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11761 11762 // The jump block hasn't been inserted yet; insert it here. 11763 MachineBasicBlock *JumpMBB = JT->MBB; 11764 CurMF->insert(BBI, JumpMBB); 11765 11766 auto JumpProb = I->Prob; 11767 auto FallthroughProb = UnhandledProbs; 11768 11769 // If the default statement is a target of the jump table, we evenly 11770 // distribute the default probability to successors of CurMBB. Also 11771 // update the probability on the edge from JumpMBB to Fallthrough. 11772 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11773 SE = JumpMBB->succ_end(); 11774 SI != SE; ++SI) { 11775 if (*SI == DefaultMBB) { 11776 JumpProb += DefaultProb / 2; 11777 FallthroughProb -= DefaultProb / 2; 11778 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11779 JumpMBB->normalizeSuccProbs(); 11780 break; 11781 } 11782 } 11783 11784 // If the default clause is unreachable, propagate that knowledge into 11785 // JTH->FallthroughUnreachable which will use it to suppress the range 11786 // check. 11787 // 11788 // However, don't do this if we're doing branch target enforcement, 11789 // because a table branch _without_ a range check can be a tempting JOP 11790 // gadget - out-of-bounds inputs that are impossible in correct 11791 // execution become possible again if an attacker can influence the 11792 // control flow. So if an attacker doesn't already have a BTI bypass 11793 // available, we don't want them to be able to get one out of this 11794 // table branch. 11795 if (FallthroughUnreachable) { 11796 Function &CurFunc = CurMF->getFunction(); 11797 bool HasBranchTargetEnforcement = false; 11798 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11799 HasBranchTargetEnforcement = 11800 CurFunc.getFnAttribute("branch-target-enforcement") 11801 .getValueAsBool(); 11802 } else { 11803 HasBranchTargetEnforcement = 11804 CurMF->getMMI().getModule()->getModuleFlag( 11805 "branch-target-enforcement"); 11806 } 11807 if (!HasBranchTargetEnforcement) 11808 JTH->FallthroughUnreachable = true; 11809 } 11810 11811 if (!JTH->FallthroughUnreachable) 11812 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11813 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11814 CurMBB->normalizeSuccProbs(); 11815 11816 // The jump table header will be inserted in our current block, do the 11817 // range check, and fall through to our fallthrough block. 11818 JTH->HeaderBB = CurMBB; 11819 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11820 11821 // If we're in the right place, emit the jump table header right now. 11822 if (CurMBB == SwitchMBB) { 11823 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11824 JTH->Emitted = true; 11825 } 11826 break; 11827 } 11828 case CC_BitTests: { 11829 // FIXME: Optimize away range check based on pivot comparisons. 11830 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11831 11832 // The bit test blocks haven't been inserted yet; insert them here. 11833 for (BitTestCase &BTC : BTB->Cases) 11834 CurMF->insert(BBI, BTC.ThisBB); 11835 11836 // Fill in fields of the BitTestBlock. 11837 BTB->Parent = CurMBB; 11838 BTB->Default = Fallthrough; 11839 11840 BTB->DefaultProb = UnhandledProbs; 11841 // If the cases in bit test don't form a contiguous range, we evenly 11842 // distribute the probability on the edge to Fallthrough to two 11843 // successors of CurMBB. 11844 if (!BTB->ContiguousRange) { 11845 BTB->Prob += DefaultProb / 2; 11846 BTB->DefaultProb -= DefaultProb / 2; 11847 } 11848 11849 if (FallthroughUnreachable) 11850 BTB->FallthroughUnreachable = true; 11851 11852 // If we're in the right place, emit the bit test header right now. 11853 if (CurMBB == SwitchMBB) { 11854 visitBitTestHeader(*BTB, SwitchMBB); 11855 BTB->Emitted = true; 11856 } 11857 break; 11858 } 11859 case CC_Range: { 11860 const Value *RHS, *LHS, *MHS; 11861 ISD::CondCode CC; 11862 if (I->Low == I->High) { 11863 // Check Cond == I->Low. 11864 CC = ISD::SETEQ; 11865 LHS = Cond; 11866 RHS=I->Low; 11867 MHS = nullptr; 11868 } else { 11869 // Check I->Low <= Cond <= I->High. 11870 CC = ISD::SETLE; 11871 LHS = I->Low; 11872 MHS = Cond; 11873 RHS = I->High; 11874 } 11875 11876 // If Fallthrough is unreachable, fold away the comparison. 11877 if (FallthroughUnreachable) 11878 CC = ISD::SETTRUE; 11879 11880 // The false probability is the sum of all unhandled cases. 11881 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11882 getCurSDLoc(), I->Prob, UnhandledProbs); 11883 11884 if (CurMBB == SwitchMBB) 11885 visitSwitchCase(CB, SwitchMBB); 11886 else 11887 SL->SwitchCases.push_back(CB); 11888 11889 break; 11890 } 11891 } 11892 CurMBB = Fallthrough; 11893 } 11894 } 11895 11896 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11897 const SwitchWorkListItem &W, 11898 Value *Cond, 11899 MachineBasicBlock *SwitchMBB) { 11900 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11901 "Clusters not sorted?"); 11902 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11903 11904 auto [LastLeft, FirstRight, LeftProb, RightProb] = 11905 SL->computeSplitWorkItemInfo(W); 11906 11907 // Use the first element on the right as pivot since we will make less-than 11908 // comparisons against it. 11909 CaseClusterIt PivotCluster = FirstRight; 11910 assert(PivotCluster > W.FirstCluster); 11911 assert(PivotCluster <= W.LastCluster); 11912 11913 CaseClusterIt FirstLeft = W.FirstCluster; 11914 CaseClusterIt LastRight = W.LastCluster; 11915 11916 const ConstantInt *Pivot = PivotCluster->Low; 11917 11918 // New blocks will be inserted immediately after the current one. 11919 MachineFunction::iterator BBI(W.MBB); 11920 ++BBI; 11921 11922 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11923 // we can branch to its destination directly if it's squeezed exactly in 11924 // between the known lower bound and Pivot - 1. 11925 MachineBasicBlock *LeftMBB; 11926 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11927 FirstLeft->Low == W.GE && 11928 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11929 LeftMBB = FirstLeft->MBB; 11930 } else { 11931 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11932 FuncInfo.MF->insert(BBI, LeftMBB); 11933 WorkList.push_back( 11934 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11935 // Put Cond in a virtual register to make it available from the new blocks. 11936 ExportFromCurrentBlock(Cond); 11937 } 11938 11939 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11940 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11941 // directly if RHS.High equals the current upper bound. 11942 MachineBasicBlock *RightMBB; 11943 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11944 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11945 RightMBB = FirstRight->MBB; 11946 } else { 11947 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11948 FuncInfo.MF->insert(BBI, RightMBB); 11949 WorkList.push_back( 11950 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11951 // Put Cond in a virtual register to make it available from the new blocks. 11952 ExportFromCurrentBlock(Cond); 11953 } 11954 11955 // Create the CaseBlock record that will be used to lower the branch. 11956 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11957 getCurSDLoc(), LeftProb, RightProb); 11958 11959 if (W.MBB == SwitchMBB) 11960 visitSwitchCase(CB, SwitchMBB); 11961 else 11962 SL->SwitchCases.push_back(CB); 11963 } 11964 11965 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11966 // from the swith statement. 11967 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11968 BranchProbability PeeledCaseProb) { 11969 if (PeeledCaseProb == BranchProbability::getOne()) 11970 return BranchProbability::getZero(); 11971 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11972 11973 uint32_t Numerator = CaseProb.getNumerator(); 11974 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11975 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11976 } 11977 11978 // Try to peel the top probability case if it exceeds the threshold. 11979 // Return current MachineBasicBlock for the switch statement if the peeling 11980 // does not occur. 11981 // If the peeling is performed, return the newly created MachineBasicBlock 11982 // for the peeled switch statement. Also update Clusters to remove the peeled 11983 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11984 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11985 const SwitchInst &SI, CaseClusterVector &Clusters, 11986 BranchProbability &PeeledCaseProb) { 11987 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11988 // Don't perform if there is only one cluster or optimizing for size. 11989 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11990 TM.getOptLevel() == CodeGenOptLevel::None || 11991 SwitchMBB->getParent()->getFunction().hasMinSize()) 11992 return SwitchMBB; 11993 11994 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11995 unsigned PeeledCaseIndex = 0; 11996 bool SwitchPeeled = false; 11997 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11998 CaseCluster &CC = Clusters[Index]; 11999 if (CC.Prob < TopCaseProb) 12000 continue; 12001 TopCaseProb = CC.Prob; 12002 PeeledCaseIndex = Index; 12003 SwitchPeeled = true; 12004 } 12005 if (!SwitchPeeled) 12006 return SwitchMBB; 12007 12008 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 12009 << TopCaseProb << "\n"); 12010 12011 // Record the MBB for the peeled switch statement. 12012 MachineFunction::iterator BBI(SwitchMBB); 12013 ++BBI; 12014 MachineBasicBlock *PeeledSwitchMBB = 12015 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 12016 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 12017 12018 ExportFromCurrentBlock(SI.getCondition()); 12019 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 12020 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 12021 nullptr, nullptr, TopCaseProb.getCompl()}; 12022 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 12023 12024 Clusters.erase(PeeledCaseIt); 12025 for (CaseCluster &CC : Clusters) { 12026 LLVM_DEBUG( 12027 dbgs() << "Scale the probablity for one cluster, before scaling: " 12028 << CC.Prob << "\n"); 12029 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 12030 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 12031 } 12032 PeeledCaseProb = TopCaseProb; 12033 return PeeledSwitchMBB; 12034 } 12035 12036 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 12037 // Extract cases from the switch. 12038 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12039 CaseClusterVector Clusters; 12040 Clusters.reserve(SI.getNumCases()); 12041 for (auto I : SI.cases()) { 12042 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 12043 const ConstantInt *CaseVal = I.getCaseValue(); 12044 BranchProbability Prob = 12045 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 12046 : BranchProbability(1, SI.getNumCases() + 1); 12047 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 12048 } 12049 12050 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 12051 12052 // Cluster adjacent cases with the same destination. We do this at all 12053 // optimization levels because it's cheap to do and will make codegen faster 12054 // if there are many clusters. 12055 sortAndRangeify(Clusters); 12056 12057 // The branch probablity of the peeled case. 12058 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 12059 MachineBasicBlock *PeeledSwitchMBB = 12060 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 12061 12062 // If there is only the default destination, jump there directly. 12063 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12064 if (Clusters.empty()) { 12065 assert(PeeledSwitchMBB == SwitchMBB); 12066 SwitchMBB->addSuccessor(DefaultMBB); 12067 if (DefaultMBB != NextBlock(SwitchMBB)) { 12068 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 12069 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 12070 } 12071 return; 12072 } 12073 12074 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 12075 DAG.getBFI()); 12076 SL->findBitTestClusters(Clusters, &SI); 12077 12078 LLVM_DEBUG({ 12079 dbgs() << "Case clusters: "; 12080 for (const CaseCluster &C : Clusters) { 12081 if (C.Kind == CC_JumpTable) 12082 dbgs() << "JT:"; 12083 if (C.Kind == CC_BitTests) 12084 dbgs() << "BT:"; 12085 12086 C.Low->getValue().print(dbgs(), true); 12087 if (C.Low != C.High) { 12088 dbgs() << '-'; 12089 C.High->getValue().print(dbgs(), true); 12090 } 12091 dbgs() << ' '; 12092 } 12093 dbgs() << '\n'; 12094 }); 12095 12096 assert(!Clusters.empty()); 12097 SwitchWorkList WorkList; 12098 CaseClusterIt First = Clusters.begin(); 12099 CaseClusterIt Last = Clusters.end() - 1; 12100 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 12101 // Scale the branchprobability for DefaultMBB if the peel occurs and 12102 // DefaultMBB is not replaced. 12103 if (PeeledCaseProb != BranchProbability::getZero() && 12104 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 12105 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 12106 WorkList.push_back( 12107 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 12108 12109 while (!WorkList.empty()) { 12110 SwitchWorkListItem W = WorkList.pop_back_val(); 12111 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 12112 12113 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 12114 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 12115 // For optimized builds, lower large range as a balanced binary tree. 12116 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 12117 continue; 12118 } 12119 12120 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 12121 } 12122 } 12123 12124 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 12125 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12126 auto DL = getCurSDLoc(); 12127 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12128 setValue(&I, DAG.getStepVector(DL, ResultVT)); 12129 } 12130 12131 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 12132 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12133 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12134 12135 SDLoc DL = getCurSDLoc(); 12136 SDValue V = getValue(I.getOperand(0)); 12137 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 12138 12139 if (VT.isScalableVector()) { 12140 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 12141 return; 12142 } 12143 12144 // Use VECTOR_SHUFFLE for the fixed-length vector 12145 // to maintain existing behavior. 12146 SmallVector<int, 8> Mask; 12147 unsigned NumElts = VT.getVectorMinNumElements(); 12148 for (unsigned i = 0; i != NumElts; ++i) 12149 Mask.push_back(NumElts - 1 - i); 12150 12151 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 12152 } 12153 12154 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 12155 auto DL = getCurSDLoc(); 12156 SDValue InVec = getValue(I.getOperand(0)); 12157 EVT OutVT = 12158 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 12159 12160 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 12161 12162 // ISD Node needs the input vectors split into two equal parts 12163 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12164 DAG.getVectorIdxConstant(0, DL)); 12165 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12166 DAG.getVectorIdxConstant(OutNumElts, DL)); 12167 12168 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12169 // legalisation and combines. 12170 if (OutVT.isFixedLengthVector()) { 12171 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12172 createStrideMask(0, 2, OutNumElts)); 12173 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12174 createStrideMask(1, 2, OutNumElts)); 12175 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 12176 setValue(&I, Res); 12177 return; 12178 } 12179 12180 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12181 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12182 setValue(&I, Res); 12183 } 12184 12185 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12186 auto DL = getCurSDLoc(); 12187 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12188 SDValue InVec0 = getValue(I.getOperand(0)); 12189 SDValue InVec1 = getValue(I.getOperand(1)); 12190 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12191 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12192 12193 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12194 // legalisation and combines. 12195 if (OutVT.isFixedLengthVector()) { 12196 unsigned NumElts = InVT.getVectorMinNumElements(); 12197 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12198 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12199 createInterleaveMask(NumElts, 2))); 12200 return; 12201 } 12202 12203 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12204 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12205 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12206 Res.getValue(1)); 12207 setValue(&I, Res); 12208 } 12209 12210 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12211 SmallVector<EVT, 4> ValueVTs; 12212 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12213 ValueVTs); 12214 unsigned NumValues = ValueVTs.size(); 12215 if (NumValues == 0) return; 12216 12217 SmallVector<SDValue, 4> Values(NumValues); 12218 SDValue Op = getValue(I.getOperand(0)); 12219 12220 for (unsigned i = 0; i != NumValues; ++i) 12221 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12222 SDValue(Op.getNode(), Op.getResNo() + i)); 12223 12224 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12225 DAG.getVTList(ValueVTs), Values)); 12226 } 12227 12228 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12229 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12230 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12231 12232 SDLoc DL = getCurSDLoc(); 12233 SDValue V1 = getValue(I.getOperand(0)); 12234 SDValue V2 = getValue(I.getOperand(1)); 12235 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12236 12237 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12238 if (VT.isScalableVector()) { 12239 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 12240 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12241 DAG.getConstant(Imm, DL, IdxVT))); 12242 return; 12243 } 12244 12245 unsigned NumElts = VT.getVectorNumElements(); 12246 12247 uint64_t Idx = (NumElts + Imm) % NumElts; 12248 12249 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12250 SmallVector<int, 8> Mask; 12251 for (unsigned i = 0; i < NumElts; ++i) 12252 Mask.push_back(Idx + i); 12253 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12254 } 12255 12256 // Consider the following MIR after SelectionDAG, which produces output in 12257 // phyregs in the first case or virtregs in the second case. 12258 // 12259 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12260 // %5:gr32 = COPY $ebx 12261 // %6:gr32 = COPY $edx 12262 // %1:gr32 = COPY %6:gr32 12263 // %0:gr32 = COPY %5:gr32 12264 // 12265 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12266 // %1:gr32 = COPY %6:gr32 12267 // %0:gr32 = COPY %5:gr32 12268 // 12269 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12270 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12271 // 12272 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12273 // to a single virtreg (such as %0). The remaining outputs monotonically 12274 // increase in virtreg number from there. If a callbr has no outputs, then it 12275 // should not have a corresponding callbr landingpad; in fact, the callbr 12276 // landingpad would not even be able to refer to such a callbr. 12277 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12278 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12279 // There is definitely at least one copy. 12280 assert(MI->getOpcode() == TargetOpcode::COPY && 12281 "start of copy chain MUST be COPY"); 12282 Reg = MI->getOperand(1).getReg(); 12283 MI = MRI.def_begin(Reg)->getParent(); 12284 // There may be an optional second copy. 12285 if (MI->getOpcode() == TargetOpcode::COPY) { 12286 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12287 Reg = MI->getOperand(1).getReg(); 12288 assert(Reg.isPhysical() && "expected COPY of physical register"); 12289 MI = MRI.def_begin(Reg)->getParent(); 12290 } 12291 // The start of the chain must be an INLINEASM_BR. 12292 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12293 "end of copy chain MUST be INLINEASM_BR"); 12294 return Reg; 12295 } 12296 12297 // We must do this walk rather than the simpler 12298 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12299 // otherwise we will end up with copies of virtregs only valid along direct 12300 // edges. 12301 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12302 SmallVector<EVT, 8> ResultVTs; 12303 SmallVector<SDValue, 8> ResultValues; 12304 const auto *CBR = 12305 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12306 12307 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12308 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12309 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12310 12311 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12312 SDValue Chain = DAG.getRoot(); 12313 12314 // Re-parse the asm constraints string. 12315 TargetLowering::AsmOperandInfoVector TargetConstraints = 12316 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12317 for (auto &T : TargetConstraints) { 12318 SDISelAsmOperandInfo OpInfo(T); 12319 if (OpInfo.Type != InlineAsm::isOutput) 12320 continue; 12321 12322 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12323 // individual constraint. 12324 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12325 12326 switch (OpInfo.ConstraintType) { 12327 case TargetLowering::C_Register: 12328 case TargetLowering::C_RegisterClass: { 12329 // Fill in OpInfo.AssignedRegs.Regs. 12330 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12331 12332 // getRegistersForValue may produce 1 to many registers based on whether 12333 // the OpInfo.ConstraintVT is legal on the target or not. 12334 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 12335 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12336 if (Register::isPhysicalRegister(OriginalDef)) 12337 FuncInfo.MBB->addLiveIn(OriginalDef); 12338 // Update the assigned registers to use the original defs. 12339 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 12340 } 12341 12342 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12343 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12344 ResultValues.push_back(V); 12345 ResultVTs.push_back(OpInfo.ConstraintVT); 12346 break; 12347 } 12348 case TargetLowering::C_Other: { 12349 SDValue Flag; 12350 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12351 OpInfo, DAG); 12352 ++InitialDef; 12353 ResultValues.push_back(V); 12354 ResultVTs.push_back(OpInfo.ConstraintVT); 12355 break; 12356 } 12357 default: 12358 break; 12359 } 12360 } 12361 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12362 DAG.getVTList(ResultVTs), ResultValues); 12363 setValue(&I, V); 12364 } 12365