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/MemoryModelRelaxationAnnotations.h" 84 #include "llvm/IR/Metadata.h" 85 #include "llvm/IR/Module.h" 86 #include "llvm/IR/Operator.h" 87 #include "llvm/IR/PatternMatch.h" 88 #include "llvm/IR/Statepoint.h" 89 #include "llvm/IR/Type.h" 90 #include "llvm/IR/User.h" 91 #include "llvm/IR/Value.h" 92 #include "llvm/MC/MCContext.h" 93 #include "llvm/Support/AtomicOrdering.h" 94 #include "llvm/Support/Casting.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/InstructionCost.h" 99 #include "llvm/Support/MathExtras.h" 100 #include "llvm/Support/raw_ostream.h" 101 #include "llvm/Target/TargetIntrinsicInfo.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.h" 104 #include "llvm/TargetParser/Triple.h" 105 #include "llvm/Transforms/Utils/Local.h" 106 #include <cstddef> 107 #include <iterator> 108 #include <limits> 109 #include <optional> 110 #include <tuple> 111 112 using namespace llvm; 113 using namespace PatternMatch; 114 using namespace SwitchCG; 115 116 #define DEBUG_TYPE "isel" 117 118 /// LimitFloatPrecision - Generate low-precision inline sequences for 119 /// some float libcalls (6, 8 or 12 bits). 120 static unsigned LimitFloatPrecision; 121 122 static cl::opt<bool> 123 InsertAssertAlign("insert-assert-align", cl::init(true), 124 cl::desc("Insert the experimental `assertalign` node."), 125 cl::ReallyHidden); 126 127 static cl::opt<unsigned, true> 128 LimitFPPrecision("limit-float-precision", 129 cl::desc("Generate low-precision inline sequences " 130 "for some float libcalls"), 131 cl::location(LimitFloatPrecision), cl::Hidden, 132 cl::init(0)); 133 134 static cl::opt<unsigned> SwitchPeelThreshold( 135 "switch-peel-threshold", cl::Hidden, cl::init(66), 136 cl::desc("Set the case probability threshold for peeling the case from a " 137 "switch statement. A value greater than 100 will void this " 138 "optimization")); 139 140 // Limit the width of DAG chains. This is important in general to prevent 141 // DAG-based analysis from blowing up. For example, alias analysis and 142 // load clustering may not complete in reasonable time. It is difficult to 143 // recognize and avoid this situation within each individual analysis, and 144 // future analyses are likely to have the same behavior. Limiting DAG width is 145 // the safe approach and will be especially important with global DAGs. 146 // 147 // MaxParallelChains default is arbitrarily high to avoid affecting 148 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 149 // sequence over this should have been converted to llvm.memcpy by the 150 // frontend. It is easy to induce this behavior with .ll code such as: 151 // %buffer = alloca [4096 x i8] 152 // %data = load [4096 x i8]* %argPtr 153 // store [4096 x i8] %data, [4096 x i8]* %buffer 154 static const unsigned MaxParallelChains = 64; 155 156 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 157 const SDValue *Parts, unsigned NumParts, 158 MVT PartVT, EVT ValueVT, const Value *V, 159 SDValue InChain, 160 std::optional<CallingConv::ID> CC); 161 162 /// getCopyFromParts - Create a value that contains the specified legal parts 163 /// combined into the value they represent. If the parts combine to a type 164 /// larger than ValueVT then AssertOp can be used to specify whether the extra 165 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 166 /// (ISD::AssertSext). 167 static SDValue 168 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 169 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 170 SDValue InChain, 171 std::optional<CallingConv::ID> CC = std::nullopt, 172 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 173 // Let the target assemble the parts if it wants to 174 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 175 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 176 PartVT, ValueVT, CC)) 177 return Val; 178 179 if (ValueVT.isVector()) 180 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 181 InChain, CC); 182 183 assert(NumParts > 0 && "No parts to assemble!"); 184 SDValue Val = Parts[0]; 185 186 if (NumParts > 1) { 187 // Assemble the value from multiple parts. 188 if (ValueVT.isInteger()) { 189 unsigned PartBits = PartVT.getSizeInBits(); 190 unsigned ValueBits = ValueVT.getSizeInBits(); 191 192 // Assemble the power of 2 part. 193 unsigned RoundParts = llvm::bit_floor(NumParts); 194 unsigned RoundBits = PartBits * RoundParts; 195 EVT RoundVT = RoundBits == ValueBits ? 196 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 197 SDValue Lo, Hi; 198 199 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 200 201 if (RoundParts > 2) { 202 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V, 203 InChain); 204 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2, 205 PartVT, HalfVT, V, InChain); 206 } else { 207 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 208 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 209 } 210 211 if (DAG.getDataLayout().isBigEndian()) 212 std::swap(Lo, Hi); 213 214 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 215 216 if (RoundParts < NumParts) { 217 // Assemble the trailing non-power-of-2 part. 218 unsigned OddParts = NumParts - RoundParts; 219 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 220 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 221 OddVT, V, InChain, CC); 222 223 // Combine the round and odd parts. 224 Lo = Val; 225 if (DAG.getDataLayout().isBigEndian()) 226 std::swap(Lo, Hi); 227 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 228 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 229 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 230 DAG.getConstant(Lo.getValueSizeInBits(), DL, 231 TLI.getShiftAmountTy( 232 TotalVT, DAG.getDataLayout()))); 233 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 234 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 235 } 236 } else if (PartVT.isFloatingPoint()) { 237 // FP split into multiple FP parts (for ppcf128) 238 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 239 "Unexpected split"); 240 SDValue Lo, Hi; 241 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 242 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 243 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 244 std::swap(Lo, Hi); 245 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 246 } else { 247 // FP split into integer parts (soft fp) 248 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 249 !PartVT.isVector() && "Unexpected split"); 250 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 251 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, 252 InChain, CC); 253 } 254 } 255 256 // There is now one part, held in Val. Correct it to match ValueVT. 257 // PartEVT is the type of the register class that holds the value. 258 // ValueVT is the type of the inline asm operation. 259 EVT PartEVT = Val.getValueType(); 260 261 if (PartEVT == ValueVT) 262 return Val; 263 264 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 265 ValueVT.bitsLT(PartEVT)) { 266 // For an FP value in an integer part, we need to truncate to the right 267 // width first. 268 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 269 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 270 } 271 272 // Handle types that have the same size. 273 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 274 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 275 276 // Handle types with different sizes. 277 if (PartEVT.isInteger() && ValueVT.isInteger()) { 278 if (ValueVT.bitsLT(PartEVT)) { 279 // For a truncate, see if we have any information to 280 // indicate whether the truncated bits will always be 281 // zero or sign-extension. 282 if (AssertOp) 283 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 284 DAG.getValueType(ValueVT)); 285 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 286 } 287 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 288 } 289 290 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 291 // FP_ROUND's are always exact here. 292 if (ValueVT.bitsLT(Val.getValueType())) { 293 294 SDValue NoChange = 295 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 296 297 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr( 298 llvm::Attribute::StrictFP)) { 299 return DAG.getNode(ISD::STRICT_FP_ROUND, DL, 300 DAG.getVTList(ValueVT, MVT::Other), InChain, Val, 301 NoChange); 302 } 303 304 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange); 305 } 306 307 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 308 } 309 310 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 311 // then truncating. 312 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 313 ValueVT.bitsLT(PartEVT)) { 314 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 315 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 316 } 317 318 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 319 } 320 321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 322 const Twine &ErrMsg) { 323 const Instruction *I = dyn_cast_or_null<Instruction>(V); 324 if (!V) 325 return Ctx.emitError(ErrMsg); 326 327 const char *AsmError = ", possible invalid constraint for vector type"; 328 if (const CallInst *CI = dyn_cast<CallInst>(I)) 329 if (CI->isInlineAsm()) 330 return Ctx.emitError(I, ErrMsg + AsmError); 331 332 return Ctx.emitError(I, ErrMsg); 333 } 334 335 /// getCopyFromPartsVector - Create a value that contains the specified legal 336 /// parts combined into the value they represent. If the parts combine to a 337 /// type larger than ValueVT then AssertOp can be used to specify whether the 338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 339 /// ValueVT (ISD::AssertSext). 340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 341 const SDValue *Parts, unsigned NumParts, 342 MVT PartVT, EVT ValueVT, const Value *V, 343 SDValue InChain, 344 std::optional<CallingConv::ID> CallConv) { 345 assert(ValueVT.isVector() && "Not a vector value"); 346 assert(NumParts > 0 && "No parts to assemble!"); 347 const bool IsABIRegCopy = CallConv.has_value(); 348 349 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 350 SDValue Val = Parts[0]; 351 352 // Handle a multi-element vector. 353 if (NumParts > 1) { 354 EVT IntermediateVT; 355 MVT RegisterVT; 356 unsigned NumIntermediates; 357 unsigned NumRegs; 358 359 if (IsABIRegCopy) { 360 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 361 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 362 NumIntermediates, RegisterVT); 363 } else { 364 NumRegs = 365 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 366 NumIntermediates, RegisterVT); 367 } 368 369 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 370 NumParts = NumRegs; // Silence a compiler warning. 371 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 372 assert(RegisterVT.getSizeInBits() == 373 Parts[0].getSimpleValueType().getSizeInBits() && 374 "Part type sizes don't match!"); 375 376 // Assemble the parts into intermediate operands. 377 SmallVector<SDValue, 8> Ops(NumIntermediates); 378 if (NumIntermediates == NumParts) { 379 // If the register was not expanded, truncate or copy the value, 380 // as appropriate. 381 for (unsigned i = 0; i != NumParts; ++i) 382 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT, 383 V, InChain, CallConv); 384 } else if (NumParts > 0) { 385 // If the intermediate type was expanded, build the intermediate 386 // operands from the parts. 387 assert(NumParts % NumIntermediates == 0 && 388 "Must expand into a divisible number of parts!"); 389 unsigned Factor = NumParts / NumIntermediates; 390 for (unsigned i = 0; i != NumIntermediates; ++i) 391 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT, 392 IntermediateVT, V, InChain, CallConv); 393 } 394 395 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 396 // intermediate operands. 397 EVT BuiltVectorTy = 398 IntermediateVT.isVector() 399 ? EVT::getVectorVT( 400 *DAG.getContext(), IntermediateVT.getScalarType(), 401 IntermediateVT.getVectorElementCount() * NumParts) 402 : EVT::getVectorVT(*DAG.getContext(), 403 IntermediateVT.getScalarType(), 404 NumIntermediates); 405 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 406 : ISD::BUILD_VECTOR, 407 DL, BuiltVectorTy, Ops); 408 } 409 410 // There is now one part, held in Val. Correct it to match ValueVT. 411 EVT PartEVT = Val.getValueType(); 412 413 if (PartEVT == ValueVT) 414 return Val; 415 416 if (PartEVT.isVector()) { 417 // Vector/Vector bitcast. 418 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 420 421 // If the parts vector has more elements than the value vector, then we 422 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 423 // Extract the elements we want. 424 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 425 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 426 ValueVT.getVectorElementCount().getKnownMinValue()) && 427 (PartEVT.getVectorElementCount().isScalable() == 428 ValueVT.getVectorElementCount().isScalable()) && 429 "Cannot narrow, it would be a lossy transformation"); 430 PartEVT = 431 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 432 ValueVT.getVectorElementCount()); 433 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 434 DAG.getVectorIdxConstant(0, DL)); 435 if (PartEVT == ValueVT) 436 return Val; 437 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 438 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 439 440 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 441 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 442 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 443 } 444 445 // Promoted vector extract 446 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 447 } 448 449 // Trivial bitcast if the types are the same size and the destination 450 // vector type is legal. 451 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 452 TLI.isTypeLegal(ValueVT)) 453 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 454 455 if (ValueVT.getVectorNumElements() != 1) { 456 // Certain ABIs require that vectors are passed as integers. For vectors 457 // are the same size, this is an obvious bitcast. 458 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 459 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 460 } else if (ValueVT.bitsLT(PartEVT)) { 461 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 462 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 463 // Drop the extra bits. 464 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 465 return DAG.getBitcast(ValueVT, Val); 466 } 467 468 diagnosePossiblyInvalidConstraint( 469 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 470 return DAG.getUNDEF(ValueVT); 471 } 472 473 // Handle cases such as i8 -> <1 x i1> 474 EVT ValueSVT = ValueVT.getVectorElementType(); 475 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 476 unsigned ValueSize = ValueSVT.getSizeInBits(); 477 if (ValueSize == PartEVT.getSizeInBits()) { 478 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 479 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 480 // It's possible a scalar floating point type gets softened to integer and 481 // then promoted to a larger integer. If PartEVT is the larger integer 482 // we need to truncate it and then bitcast to the FP type. 483 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 484 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 485 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 486 Val = DAG.getBitcast(ValueSVT, Val); 487 } else { 488 Val = ValueVT.isFloatingPoint() 489 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 490 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 491 } 492 } 493 494 return DAG.getBuildVector(ValueVT, DL, Val); 495 } 496 497 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 498 SDValue Val, SDValue *Parts, unsigned NumParts, 499 MVT PartVT, const Value *V, 500 std::optional<CallingConv::ID> CallConv); 501 502 /// getCopyToParts - Create a series of nodes that contain the specified value 503 /// split into legal parts. If the parts contain more bits than Val, then, for 504 /// integers, ExtendKind can be used to specify how to generate the extra bits. 505 static void 506 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 507 unsigned NumParts, MVT PartVT, const Value *V, 508 std::optional<CallingConv::ID> CallConv = std::nullopt, 509 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 510 // Let the target split the parts if it wants to 511 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 512 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 513 CallConv)) 514 return; 515 EVT ValueVT = Val.getValueType(); 516 517 // Handle the vector case separately. 518 if (ValueVT.isVector()) 519 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 520 CallConv); 521 522 unsigned OrigNumParts = NumParts; 523 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 524 "Copying to an illegal type!"); 525 526 if (NumParts == 0) 527 return; 528 529 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 530 EVT PartEVT = PartVT; 531 if (PartEVT == ValueVT) { 532 assert(NumParts == 1 && "No-op copy with multiple parts!"); 533 Parts[0] = Val; 534 return; 535 } 536 537 unsigned PartBits = PartVT.getSizeInBits(); 538 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 539 // If the parts cover more bits than the value has, promote the value. 540 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 541 assert(NumParts == 1 && "Do not know what to promote to!"); 542 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 543 } else { 544 if (ValueVT.isFloatingPoint()) { 545 // FP values need to be bitcast, then extended if they are being put 546 // into a larger container. 547 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 548 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 549 } 550 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 551 ValueVT.isInteger() && 552 "Unknown mismatch!"); 553 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 554 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 555 if (PartVT == MVT::x86mmx) 556 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 557 } 558 } else if (PartBits == ValueVT.getSizeInBits()) { 559 // Different types of the same size. 560 assert(NumParts == 1 && PartEVT != ValueVT); 561 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 562 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 563 // If the parts cover less bits than value has, truncate the value. 564 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 565 ValueVT.isInteger() && 566 "Unknown mismatch!"); 567 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 568 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 569 if (PartVT == MVT::x86mmx) 570 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 571 } 572 573 // The value may have changed - recompute ValueVT. 574 ValueVT = Val.getValueType(); 575 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 576 "Failed to tile the value with PartVT!"); 577 578 if (NumParts == 1) { 579 if (PartEVT != ValueVT) { 580 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 581 "scalar-to-vector conversion failed"); 582 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 583 } 584 585 Parts[0] = Val; 586 return; 587 } 588 589 // Expand the value into multiple parts. 590 if (NumParts & (NumParts - 1)) { 591 // The number of parts is not a power of 2. Split off and copy the tail. 592 assert(PartVT.isInteger() && ValueVT.isInteger() && 593 "Do not know what to expand to!"); 594 unsigned RoundParts = llvm::bit_floor(NumParts); 595 unsigned RoundBits = RoundParts * PartBits; 596 unsigned OddParts = NumParts - RoundParts; 597 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 598 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 599 600 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 601 CallConv); 602 603 if (DAG.getDataLayout().isBigEndian()) 604 // The odd parts were reversed by getCopyToParts - unreverse them. 605 std::reverse(Parts + RoundParts, Parts + NumParts); 606 607 NumParts = RoundParts; 608 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 609 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 610 } 611 612 // The number of parts is a power of 2. Repeatedly bisect the value using 613 // EXTRACT_ELEMENT. 614 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 615 EVT::getIntegerVT(*DAG.getContext(), 616 ValueVT.getSizeInBits()), 617 Val); 618 619 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 620 for (unsigned i = 0; i < NumParts; i += StepSize) { 621 unsigned ThisBits = StepSize * PartBits / 2; 622 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 623 SDValue &Part0 = Parts[i]; 624 SDValue &Part1 = Parts[i+StepSize/2]; 625 626 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 627 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 628 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 629 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 630 631 if (ThisBits == PartBits && ThisVT != PartVT) { 632 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 633 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 634 } 635 } 636 } 637 638 if (DAG.getDataLayout().isBigEndian()) 639 std::reverse(Parts, Parts + OrigNumParts); 640 } 641 642 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 643 const SDLoc &DL, EVT PartVT) { 644 if (!PartVT.isVector()) 645 return SDValue(); 646 647 EVT ValueVT = Val.getValueType(); 648 EVT PartEVT = PartVT.getVectorElementType(); 649 EVT ValueEVT = ValueVT.getVectorElementType(); 650 ElementCount PartNumElts = PartVT.getVectorElementCount(); 651 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 652 653 // We only support widening vectors with equivalent element types and 654 // fixed/scalable properties. If a target needs to widen a fixed-length type 655 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 656 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 657 PartNumElts.isScalable() != ValueNumElts.isScalable()) 658 return SDValue(); 659 660 // Have a try for bf16 because some targets share its ABI with fp16. 661 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 662 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 663 "Cannot widen to illegal type"); 664 Val = DAG.getNode(ISD::BITCAST, DL, 665 ValueVT.changeVectorElementType(MVT::f16), Val); 666 } else if (PartEVT != ValueEVT) { 667 return SDValue(); 668 } 669 670 // Widening a scalable vector to another scalable vector is done by inserting 671 // the vector into a larger undef one. 672 if (PartNumElts.isScalable()) 673 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 674 Val, DAG.getVectorIdxConstant(0, DL)); 675 676 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 677 // undef elements. 678 SmallVector<SDValue, 16> Ops; 679 DAG.ExtractVectorElements(Val, Ops); 680 SDValue EltUndef = DAG.getUNDEF(PartEVT); 681 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 682 683 // FIXME: Use CONCAT for 2x -> 4x. 684 return DAG.getBuildVector(PartVT, DL, Ops); 685 } 686 687 /// getCopyToPartsVector - Create a series of nodes that contain the specified 688 /// value split into legal parts. 689 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 690 SDValue Val, SDValue *Parts, unsigned NumParts, 691 MVT PartVT, const Value *V, 692 std::optional<CallingConv::ID> CallConv) { 693 EVT ValueVT = Val.getValueType(); 694 assert(ValueVT.isVector() && "Not a vector"); 695 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 696 const bool IsABIRegCopy = CallConv.has_value(); 697 698 if (NumParts == 1) { 699 EVT PartEVT = PartVT; 700 if (PartEVT == ValueVT) { 701 // Nothing to do. 702 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 703 // Bitconvert vector->vector case. 704 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 705 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 706 Val = Widened; 707 } else if (PartVT.isVector() && 708 PartEVT.getVectorElementType().bitsGE( 709 ValueVT.getVectorElementType()) && 710 PartEVT.getVectorElementCount() == 711 ValueVT.getVectorElementCount()) { 712 713 // Promoted vector extract 714 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 715 } else if (PartEVT.isVector() && 716 PartEVT.getVectorElementType() != 717 ValueVT.getVectorElementType() && 718 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 719 TargetLowering::TypeWidenVector) { 720 // Combination of widening and promotion. 721 EVT WidenVT = 722 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 723 PartVT.getVectorElementCount()); 724 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 725 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 726 } else { 727 // Don't extract an integer from a float vector. This can happen if the 728 // FP type gets softened to integer and then promoted. The promotion 729 // prevents it from being picked up by the earlier bitcast case. 730 if (ValueVT.getVectorElementCount().isScalar() && 731 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 732 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 733 DAG.getVectorIdxConstant(0, DL)); 734 } else { 735 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 736 assert(PartVT.getFixedSizeInBits() > ValueSize && 737 "lossy conversion of vector to scalar type"); 738 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 739 Val = DAG.getBitcast(IntermediateType, Val); 740 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 741 } 742 } 743 744 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 745 Parts[0] = Val; 746 return; 747 } 748 749 // Handle a multi-element vector. 750 EVT IntermediateVT; 751 MVT RegisterVT; 752 unsigned NumIntermediates; 753 unsigned NumRegs; 754 if (IsABIRegCopy) { 755 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 756 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 757 RegisterVT); 758 } else { 759 NumRegs = 760 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 761 NumIntermediates, RegisterVT); 762 } 763 764 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 765 NumParts = NumRegs; // Silence a compiler warning. 766 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 767 768 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 769 "Mixing scalable and fixed vectors when copying in parts"); 770 771 std::optional<ElementCount> DestEltCnt; 772 773 if (IntermediateVT.isVector()) 774 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 775 else 776 DestEltCnt = ElementCount::getFixed(NumIntermediates); 777 778 EVT BuiltVectorTy = EVT::getVectorVT( 779 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 780 781 if (ValueVT == BuiltVectorTy) { 782 // Nothing to do. 783 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 784 // Bitconvert vector->vector case. 785 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 786 } else { 787 if (BuiltVectorTy.getVectorElementType().bitsGT( 788 ValueVT.getVectorElementType())) { 789 // Integer promotion. 790 ValueVT = EVT::getVectorVT(*DAG.getContext(), 791 BuiltVectorTy.getVectorElementType(), 792 ValueVT.getVectorElementCount()); 793 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 794 } 795 796 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 797 Val = Widened; 798 } 799 } 800 801 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 802 803 // Split the vector into intermediate operands. 804 SmallVector<SDValue, 8> Ops(NumIntermediates); 805 for (unsigned i = 0; i != NumIntermediates; ++i) { 806 if (IntermediateVT.isVector()) { 807 // This does something sensible for scalable vectors - see the 808 // definition of EXTRACT_SUBVECTOR for further details. 809 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 810 Ops[i] = 811 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 812 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 813 } else { 814 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 815 DAG.getVectorIdxConstant(i, DL)); 816 } 817 } 818 819 // Split the intermediate operands into legal parts. 820 if (NumParts == NumIntermediates) { 821 // If the register was not expanded, promote or copy the value, 822 // as appropriate. 823 for (unsigned i = 0; i != NumParts; ++i) 824 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 825 } else if (NumParts > 0) { 826 // If the intermediate type was expanded, split each the value into 827 // legal parts. 828 assert(NumIntermediates != 0 && "division by zero"); 829 assert(NumParts % NumIntermediates == 0 && 830 "Must expand into a divisible number of parts!"); 831 unsigned Factor = NumParts / NumIntermediates; 832 for (unsigned i = 0; i != NumIntermediates; ++i) 833 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 834 CallConv); 835 } 836 } 837 838 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 839 EVT valuevt, std::optional<CallingConv::ID> CC) 840 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 841 RegCount(1, regs.size()), CallConv(CC) {} 842 843 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 844 const DataLayout &DL, unsigned Reg, Type *Ty, 845 std::optional<CallingConv::ID> CC) { 846 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 847 848 CallConv = CC; 849 850 for (EVT ValueVT : ValueVTs) { 851 unsigned NumRegs = 852 isABIMangled() 853 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 854 : TLI.getNumRegisters(Context, ValueVT); 855 MVT RegisterVT = 856 isABIMangled() 857 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 858 : TLI.getRegisterType(Context, ValueVT); 859 for (unsigned i = 0; i != NumRegs; ++i) 860 Regs.push_back(Reg + i); 861 RegVTs.push_back(RegisterVT); 862 RegCount.push_back(NumRegs); 863 Reg += NumRegs; 864 } 865 } 866 867 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 868 FunctionLoweringInfo &FuncInfo, 869 const SDLoc &dl, SDValue &Chain, 870 SDValue *Glue, const Value *V) const { 871 // A Value with type {} or [0 x %t] needs no registers. 872 if (ValueVTs.empty()) 873 return SDValue(); 874 875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 876 877 // Assemble the legal parts into the final values. 878 SmallVector<SDValue, 4> Values(ValueVTs.size()); 879 SmallVector<SDValue, 8> Parts; 880 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 881 // Copy the legal parts from the registers. 882 EVT ValueVT = ValueVTs[Value]; 883 unsigned NumRegs = RegCount[Value]; 884 MVT RegisterVT = isABIMangled() 885 ? TLI.getRegisterTypeForCallingConv( 886 *DAG.getContext(), *CallConv, RegVTs[Value]) 887 : RegVTs[Value]; 888 889 Parts.resize(NumRegs); 890 for (unsigned i = 0; i != NumRegs; ++i) { 891 SDValue P; 892 if (!Glue) { 893 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 894 } else { 895 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 896 *Glue = P.getValue(2); 897 } 898 899 Chain = P.getValue(1); 900 Parts[i] = P; 901 902 // If the source register was virtual and if we know something about it, 903 // add an assert node. 904 if (!Register::isVirtualRegister(Regs[Part + i]) || 905 !RegisterVT.isInteger()) 906 continue; 907 908 const FunctionLoweringInfo::LiveOutInfo *LOI = 909 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 910 if (!LOI) 911 continue; 912 913 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 914 unsigned NumSignBits = LOI->NumSignBits; 915 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 916 917 if (NumZeroBits == RegSize) { 918 // The current value is a zero. 919 // Explicitly express that as it would be easier for 920 // optimizations to kick in. 921 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 922 continue; 923 } 924 925 // FIXME: We capture more information than the dag can represent. For 926 // now, just use the tightest assertzext/assertsext possible. 927 bool isSExt; 928 EVT FromVT(MVT::Other); 929 if (NumZeroBits) { 930 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 931 isSExt = false; 932 } else if (NumSignBits > 1) { 933 FromVT = 934 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 935 isSExt = true; 936 } else { 937 continue; 938 } 939 // Add an assertion node. 940 assert(FromVT != MVT::Other); 941 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 942 RegisterVT, P, DAG.getValueType(FromVT)); 943 } 944 945 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 946 RegisterVT, ValueVT, V, Chain, CallConv); 947 Part += NumRegs; 948 Parts.clear(); 949 } 950 951 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 952 } 953 954 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 955 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 956 const Value *V, 957 ISD::NodeType PreferredExtendType) const { 958 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 959 ISD::NodeType ExtendKind = PreferredExtendType; 960 961 // Get the list of the values's legal parts. 962 unsigned NumRegs = Regs.size(); 963 SmallVector<SDValue, 8> Parts(NumRegs); 964 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 965 unsigned NumParts = RegCount[Value]; 966 967 MVT RegisterVT = isABIMangled() 968 ? TLI.getRegisterTypeForCallingConv( 969 *DAG.getContext(), *CallConv, RegVTs[Value]) 970 : RegVTs[Value]; 971 972 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 973 ExtendKind = ISD::ZERO_EXTEND; 974 975 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 976 NumParts, RegisterVT, V, CallConv, ExtendKind); 977 Part += NumParts; 978 } 979 980 // Copy the parts into the registers. 981 SmallVector<SDValue, 8> Chains(NumRegs); 982 for (unsigned i = 0; i != NumRegs; ++i) { 983 SDValue Part; 984 if (!Glue) { 985 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 986 } else { 987 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 988 *Glue = Part.getValue(1); 989 } 990 991 Chains[i] = Part.getValue(0); 992 } 993 994 if (NumRegs == 1 || Glue) 995 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 996 // flagged to it. That is the CopyToReg nodes and the user are considered 997 // a single scheduling unit. If we create a TokenFactor and return it as 998 // chain, then the TokenFactor is both a predecessor (operand) of the 999 // user as well as a successor (the TF operands are flagged to the user). 1000 // c1, f1 = CopyToReg 1001 // c2, f2 = CopyToReg 1002 // c3 = TokenFactor c1, c2 1003 // ... 1004 // = op c3, ..., f2 1005 Chain = Chains[NumRegs-1]; 1006 else 1007 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 1008 } 1009 1010 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 1011 unsigned MatchingIdx, const SDLoc &dl, 1012 SelectionDAG &DAG, 1013 std::vector<SDValue> &Ops) const { 1014 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1015 1016 InlineAsm::Flag Flag(Code, Regs.size()); 1017 if (HasMatching) 1018 Flag.setMatchingOp(MatchingIdx); 1019 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1020 // Put the register class of the virtual registers in the flag word. That 1021 // way, later passes can recompute register class constraints for inline 1022 // assembly as well as normal instructions. 1023 // Don't do this for tied operands that can use the regclass information 1024 // from the def. 1025 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1026 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1027 Flag.setRegClass(RC->getID()); 1028 } 1029 1030 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1031 Ops.push_back(Res); 1032 1033 if (Code == InlineAsm::Kind::Clobber) { 1034 // Clobbers should always have a 1:1 mapping with registers, and may 1035 // reference registers that have illegal (e.g. vector) types. Hence, we 1036 // shouldn't try to apply any sort of splitting logic to them. 1037 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1038 "No 1:1 mapping from clobbers to regs?"); 1039 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1040 (void)SP; 1041 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1042 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1043 assert( 1044 (Regs[I] != SP || 1045 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1046 "If we clobbered the stack pointer, MFI should know about it."); 1047 } 1048 return; 1049 } 1050 1051 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1052 MVT RegisterVT = RegVTs[Value]; 1053 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1054 RegisterVT); 1055 for (unsigned i = 0; i != NumRegs; ++i) { 1056 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1057 unsigned TheReg = Regs[Reg++]; 1058 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1059 } 1060 } 1061 } 1062 1063 SmallVector<std::pair<unsigned, TypeSize>, 4> 1064 RegsForValue::getRegsAndSizes() const { 1065 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1066 unsigned I = 0; 1067 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1068 unsigned RegCount = std::get<0>(CountAndVT); 1069 MVT RegisterVT = std::get<1>(CountAndVT); 1070 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1071 for (unsigned E = I + RegCount; I != E; ++I) 1072 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1073 } 1074 return OutVec; 1075 } 1076 1077 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1078 AssumptionCache *ac, 1079 const TargetLibraryInfo *li) { 1080 AA = aa; 1081 AC = ac; 1082 GFI = gfi; 1083 LibInfo = li; 1084 Context = DAG.getContext(); 1085 LPadToCallSiteMap.clear(); 1086 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1087 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1088 *DAG.getMachineFunction().getFunction().getParent()); 1089 } 1090 1091 void SelectionDAGBuilder::clear() { 1092 NodeMap.clear(); 1093 UnusedArgNodeMap.clear(); 1094 PendingLoads.clear(); 1095 PendingExports.clear(); 1096 PendingConstrainedFP.clear(); 1097 PendingConstrainedFPStrict.clear(); 1098 CurInst = nullptr; 1099 HasTailCall = false; 1100 SDNodeOrder = LowestSDNodeOrder; 1101 StatepointLowering.clear(); 1102 } 1103 1104 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1105 DanglingDebugInfoMap.clear(); 1106 } 1107 1108 // Update DAG root to include dependencies on Pending chains. 1109 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1110 SDValue Root = DAG.getRoot(); 1111 1112 if (Pending.empty()) 1113 return Root; 1114 1115 // Add current root to PendingChains, unless we already indirectly 1116 // depend on it. 1117 if (Root.getOpcode() != ISD::EntryToken) { 1118 unsigned i = 0, e = Pending.size(); 1119 for (; i != e; ++i) { 1120 assert(Pending[i].getNode()->getNumOperands() > 1); 1121 if (Pending[i].getNode()->getOperand(0) == Root) 1122 break; // Don't add the root if we already indirectly depend on it. 1123 } 1124 1125 if (i == e) 1126 Pending.push_back(Root); 1127 } 1128 1129 if (Pending.size() == 1) 1130 Root = Pending[0]; 1131 else 1132 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1133 1134 DAG.setRoot(Root); 1135 Pending.clear(); 1136 return Root; 1137 } 1138 1139 SDValue SelectionDAGBuilder::getMemoryRoot() { 1140 return updateRoot(PendingLoads); 1141 } 1142 1143 SDValue SelectionDAGBuilder::getRoot() { 1144 // Chain up all pending constrained intrinsics together with all 1145 // pending loads, by simply appending them to PendingLoads and 1146 // then calling getMemoryRoot(). 1147 PendingLoads.reserve(PendingLoads.size() + 1148 PendingConstrainedFP.size() + 1149 PendingConstrainedFPStrict.size()); 1150 PendingLoads.append(PendingConstrainedFP.begin(), 1151 PendingConstrainedFP.end()); 1152 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1153 PendingConstrainedFPStrict.end()); 1154 PendingConstrainedFP.clear(); 1155 PendingConstrainedFPStrict.clear(); 1156 return getMemoryRoot(); 1157 } 1158 1159 SDValue SelectionDAGBuilder::getControlRoot() { 1160 // We need to emit pending fpexcept.strict constrained intrinsics, 1161 // so append them to the PendingExports list. 1162 PendingExports.append(PendingConstrainedFPStrict.begin(), 1163 PendingConstrainedFPStrict.end()); 1164 PendingConstrainedFPStrict.clear(); 1165 return updateRoot(PendingExports); 1166 } 1167 1168 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1169 DILocalVariable *Variable, 1170 DIExpression *Expression, 1171 DebugLoc DL) { 1172 assert(Variable && "Missing variable"); 1173 1174 // Check if address has undef value. 1175 if (!Address || isa<UndefValue>(Address) || 1176 (Address->use_empty() && !isa<Argument>(Address))) { 1177 LLVM_DEBUG( 1178 dbgs() 1179 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1180 return; 1181 } 1182 1183 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1184 1185 SDValue &N = NodeMap[Address]; 1186 if (!N.getNode() && isa<Argument>(Address)) 1187 // Check unused arguments map. 1188 N = UnusedArgNodeMap[Address]; 1189 SDDbgValue *SDV; 1190 if (N.getNode()) { 1191 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1192 Address = BCI->getOperand(0); 1193 // Parameters are handled specially. 1194 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1195 if (IsParameter && FINode) { 1196 // Byval parameter. We have a frame index at this point. 1197 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1198 /*IsIndirect*/ true, DL, SDNodeOrder); 1199 } else if (isa<Argument>(Address)) { 1200 // Address is an argument, so try to emit its dbg value using 1201 // virtual register info from the FuncInfo.ValueMap. 1202 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1203 FuncArgumentDbgValueKind::Declare, N); 1204 return; 1205 } else { 1206 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1207 true, DL, SDNodeOrder); 1208 } 1209 DAG.AddDbgValue(SDV, IsParameter); 1210 } else { 1211 // If Address is an argument then try to emit its dbg value using 1212 // virtual register info from the FuncInfo.ValueMap. 1213 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1214 FuncArgumentDbgValueKind::Declare, N)) { 1215 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1216 << " (could not emit func-arg dbg_value)\n"); 1217 } 1218 } 1219 return; 1220 } 1221 1222 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1223 // Add SDDbgValue nodes for any var locs here. Do so before updating 1224 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1225 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1226 // Add SDDbgValue nodes for any var locs here. Do so before updating 1227 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1228 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1229 It != End; ++It) { 1230 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1231 dropDanglingDebugInfo(Var, It->Expr); 1232 if (It->Values.isKillLocation(It->Expr)) { 1233 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1234 continue; 1235 } 1236 SmallVector<Value *> Values(It->Values.location_ops()); 1237 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1238 It->Values.hasArgList())) { 1239 SmallVector<Value *, 4> Vals; 1240 for (Value *V : It->Values.location_ops()) 1241 Vals.push_back(V); 1242 addDanglingDebugInfo(Vals, 1243 FnVarLocs->getDILocalVariable(It->VariableID), 1244 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1245 } 1246 } 1247 } 1248 1249 // We must skip DbgVariableRecords if they've already been processed above as 1250 // we have just emitted the debug values resulting from assignment tracking 1251 // analysis, making any existing DbgVariableRecords redundant (and probably 1252 // less correct). We still need to process DbgLabelRecords. This does sink 1253 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't 1254 // be important as it does so deterministcally and ordering between 1255 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR 1256 // printing). 1257 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs(); 1258 // Is there is any debug-info attached to this instruction, in the form of 1259 // DbgRecord non-instruction debug-info records. 1260 for (DbgRecord &DR : I.getDbgRecordRange()) { 1261 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 1262 assert(DLR->getLabel() && "Missing label"); 1263 SDDbgLabel *SDV = 1264 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder); 1265 DAG.AddDbgLabel(SDV); 1266 continue; 1267 } 1268 1269 if (SkipDbgVariableRecords) 1270 continue; 1271 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 1272 DILocalVariable *Variable = DVR.getVariable(); 1273 DIExpression *Expression = DVR.getExpression(); 1274 dropDanglingDebugInfo(Variable, Expression); 1275 1276 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) { 1277 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR)) 1278 continue; 1279 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR 1280 << "\n"); 1281 handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression, 1282 DVR.getDebugLoc()); 1283 continue; 1284 } 1285 1286 // A DbgVariableRecord with no locations is a kill location. 1287 SmallVector<Value *, 4> Values(DVR.location_ops()); 1288 if (Values.empty()) { 1289 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1290 SDNodeOrder); 1291 continue; 1292 } 1293 1294 // A DbgVariableRecord with an undef or absent location is also a kill 1295 // location. 1296 if (llvm::any_of(Values, 1297 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1298 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1299 SDNodeOrder); 1300 continue; 1301 } 1302 1303 bool IsVariadic = DVR.hasArgList(); 1304 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(), 1305 SDNodeOrder, IsVariadic)) { 1306 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1307 DVR.getDebugLoc(), SDNodeOrder); 1308 } 1309 } 1310 } 1311 1312 void SelectionDAGBuilder::visit(const Instruction &I) { 1313 visitDbgInfo(I); 1314 1315 // Set up outgoing PHI node register values before emitting the terminator. 1316 if (I.isTerminator()) { 1317 HandlePHINodesInSuccessorBlocks(I.getParent()); 1318 } 1319 1320 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1321 if (!isa<DbgInfoIntrinsic>(I)) 1322 ++SDNodeOrder; 1323 1324 CurInst = &I; 1325 1326 // Set inserted listener only if required. 1327 bool NodeInserted = false; 1328 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1329 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1330 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra); 1331 if (PCSectionsMD || MMRA) { 1332 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1333 DAG, [&](SDNode *) { NodeInserted = true; }); 1334 } 1335 1336 visit(I.getOpcode(), I); 1337 1338 if (!I.isTerminator() && !HasTailCall && 1339 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1340 CopyToExportRegsIfNeeded(&I); 1341 1342 // Handle metadata. 1343 if (PCSectionsMD || MMRA) { 1344 auto It = NodeMap.find(&I); 1345 if (It != NodeMap.end()) { 1346 if (PCSectionsMD) 1347 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1348 if (MMRA) 1349 DAG.addMMRAMetadata(It->second.getNode(), MMRA); 1350 } else if (NodeInserted) { 1351 // This should not happen; if it does, don't let it go unnoticed so we can 1352 // fix it. Relevant visit*() function is probably missing a setValue(). 1353 errs() << "warning: loosing !pcsections and/or !mmra metadata [" 1354 << I.getModule()->getName() << "]\n"; 1355 LLVM_DEBUG(I.dump()); 1356 assert(false); 1357 } 1358 } 1359 1360 CurInst = nullptr; 1361 } 1362 1363 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1364 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1365 } 1366 1367 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1368 // Note: this doesn't use InstVisitor, because it has to work with 1369 // ConstantExpr's in addition to instructions. 1370 switch (Opcode) { 1371 default: llvm_unreachable("Unknown instruction type encountered!"); 1372 // Build the switch statement using the Instruction.def file. 1373 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1374 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1375 #include "llvm/IR/Instruction.def" 1376 } 1377 } 1378 1379 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1380 DILocalVariable *Variable, 1381 DebugLoc DL, unsigned Order, 1382 SmallVectorImpl<Value *> &Values, 1383 DIExpression *Expression) { 1384 // For variadic dbg_values we will now insert an undef. 1385 // FIXME: We can potentially recover these! 1386 SmallVector<SDDbgOperand, 2> Locs; 1387 for (const Value *V : Values) { 1388 auto *Undef = UndefValue::get(V->getType()); 1389 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1390 } 1391 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1392 /*IsIndirect=*/false, DL, Order, 1393 /*IsVariadic=*/true); 1394 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1395 return true; 1396 } 1397 1398 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1399 DILocalVariable *Var, 1400 DIExpression *Expr, 1401 bool IsVariadic, DebugLoc DL, 1402 unsigned Order) { 1403 if (IsVariadic) { 1404 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1405 return; 1406 } 1407 // TODO: Dangling debug info will eventually either be resolved or produce 1408 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1409 // between the original dbg.value location and its resolved DBG_VALUE, 1410 // which we should ideally fill with an extra Undef DBG_VALUE. 1411 assert(Values.size() == 1); 1412 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1413 } 1414 1415 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1416 const DIExpression *Expr) { 1417 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1418 DIVariable *DanglingVariable = DDI.getVariable(); 1419 DIExpression *DanglingExpr = DDI.getExpression(); 1420 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1421 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1422 << printDDI(nullptr, DDI) << "\n"); 1423 return true; 1424 } 1425 return false; 1426 }; 1427 1428 for (auto &DDIMI : DanglingDebugInfoMap) { 1429 DanglingDebugInfoVector &DDIV = DDIMI.second; 1430 1431 // If debug info is to be dropped, run it through final checks to see 1432 // whether it can be salvaged. 1433 for (auto &DDI : DDIV) 1434 if (isMatchingDbgValue(DDI)) 1435 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1436 1437 erase_if(DDIV, isMatchingDbgValue); 1438 } 1439 } 1440 1441 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1442 // generate the debug data structures now that we've seen its definition. 1443 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1444 SDValue Val) { 1445 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1446 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1447 return; 1448 1449 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1450 for (auto &DDI : DDIV) { 1451 DebugLoc DL = DDI.getDebugLoc(); 1452 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1453 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1454 DILocalVariable *Variable = DDI.getVariable(); 1455 DIExpression *Expr = DDI.getExpression(); 1456 assert(Variable->isValidLocationForIntrinsic(DL) && 1457 "Expected inlined-at fields to agree"); 1458 SDDbgValue *SDV; 1459 if (Val.getNode()) { 1460 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1461 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1462 // we couldn't resolve it directly when examining the DbgValue intrinsic 1463 // in the first place we should not be more successful here). Unless we 1464 // have some test case that prove this to be correct we should avoid 1465 // calling EmitFuncArgumentDbgValue here. 1466 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1467 FuncArgumentDbgValueKind::Value, Val)) { 1468 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1469 << printDDI(V, DDI) << "\n"); 1470 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1471 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1472 // inserted after the definition of Val when emitting the instructions 1473 // after ISel. An alternative could be to teach 1474 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1475 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1476 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1477 << ValSDNodeOrder << "\n"); 1478 SDV = getDbgValue(Val, Variable, Expr, DL, 1479 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1480 DAG.AddDbgValue(SDV, false); 1481 } else 1482 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1483 << printDDI(V, DDI) 1484 << " in EmitFuncArgumentDbgValue\n"); 1485 } else { 1486 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1487 << "\n"); 1488 auto Undef = UndefValue::get(V->getType()); 1489 auto SDV = 1490 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1491 DAG.AddDbgValue(SDV, false); 1492 } 1493 } 1494 DDIV.clear(); 1495 } 1496 1497 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1498 DanglingDebugInfo &DDI) { 1499 // TODO: For the variadic implementation, instead of only checking the fail 1500 // state of `handleDebugValue`, we need know specifically which values were 1501 // invalid, so that we attempt to salvage only those values when processing 1502 // a DIArgList. 1503 const Value *OrigV = V; 1504 DILocalVariable *Var = DDI.getVariable(); 1505 DIExpression *Expr = DDI.getExpression(); 1506 DebugLoc DL = DDI.getDebugLoc(); 1507 unsigned SDOrder = DDI.getSDNodeOrder(); 1508 1509 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1510 // that DW_OP_stack_value is desired. 1511 bool StackValue = true; 1512 1513 // Can this Value can be encoded without any further work? 1514 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1515 return; 1516 1517 // Attempt to salvage back through as many instructions as possible. Bail if 1518 // a non-instruction is seen, such as a constant expression or global 1519 // variable. FIXME: Further work could recover those too. 1520 while (isa<Instruction>(V)) { 1521 const Instruction &VAsInst = *cast<const Instruction>(V); 1522 // Temporary "0", awaiting real implementation. 1523 SmallVector<uint64_t, 16> Ops; 1524 SmallVector<Value *, 4> AdditionalValues; 1525 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1526 Expr->getNumLocationOperands(), Ops, 1527 AdditionalValues); 1528 // If we cannot salvage any further, and haven't yet found a suitable debug 1529 // expression, bail out. 1530 if (!V) 1531 break; 1532 1533 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1534 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1535 // here for variadic dbg_values, remove that condition. 1536 if (!AdditionalValues.empty()) 1537 break; 1538 1539 // New value and expr now represent this debuginfo. 1540 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1541 1542 // Some kind of simplification occurred: check whether the operand of the 1543 // salvaged debug expression can be encoded in this DAG. 1544 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1545 LLVM_DEBUG( 1546 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1547 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1548 return; 1549 } 1550 } 1551 1552 // This was the final opportunity to salvage this debug information, and it 1553 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1554 // any earlier variable location. 1555 assert(OrigV && "V shouldn't be null"); 1556 auto *Undef = UndefValue::get(OrigV->getType()); 1557 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1558 DAG.AddDbgValue(SDV, false); 1559 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1560 << printDDI(OrigV, DDI) << "\n"); 1561 } 1562 1563 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1564 DIExpression *Expr, 1565 DebugLoc DbgLoc, 1566 unsigned Order) { 1567 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1568 DIExpression *NewExpr = 1569 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1570 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1571 /*IsVariadic*/ false); 1572 } 1573 1574 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1575 DILocalVariable *Var, 1576 DIExpression *Expr, DebugLoc DbgLoc, 1577 unsigned Order, bool IsVariadic) { 1578 if (Values.empty()) 1579 return true; 1580 1581 // Filter EntryValue locations out early. 1582 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1583 return true; 1584 1585 SmallVector<SDDbgOperand> LocationOps; 1586 SmallVector<SDNode *> Dependencies; 1587 for (const Value *V : Values) { 1588 // Constant value. 1589 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1590 isa<ConstantPointerNull>(V)) { 1591 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1592 continue; 1593 } 1594 1595 // Look through IntToPtr constants. 1596 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1597 if (CE->getOpcode() == Instruction::IntToPtr) { 1598 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1599 continue; 1600 } 1601 1602 // If the Value is a frame index, we can create a FrameIndex debug value 1603 // without relying on the DAG at all. 1604 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1605 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1606 if (SI != FuncInfo.StaticAllocaMap.end()) { 1607 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1608 continue; 1609 } 1610 } 1611 1612 // Do not use getValue() in here; we don't want to generate code at 1613 // this point if it hasn't been done yet. 1614 SDValue N = NodeMap[V]; 1615 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1616 N = UnusedArgNodeMap[V]; 1617 if (N.getNode()) { 1618 // Only emit func arg dbg value for non-variadic dbg.values for now. 1619 if (!IsVariadic && 1620 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1621 FuncArgumentDbgValueKind::Value, N)) 1622 return true; 1623 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1624 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1625 // describe stack slot locations. 1626 // 1627 // Consider "int x = 0; int *px = &x;". There are two kinds of 1628 // interesting debug values here after optimization: 1629 // 1630 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1631 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1632 // 1633 // Both describe the direct values of their associated variables. 1634 Dependencies.push_back(N.getNode()); 1635 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1636 continue; 1637 } 1638 LocationOps.emplace_back( 1639 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1640 continue; 1641 } 1642 1643 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1644 // Special rules apply for the first dbg.values of parameter variables in a 1645 // function. Identify them by the fact they reference Argument Values, that 1646 // they're parameters, and they are parameters of the current function. We 1647 // need to let them dangle until they get an SDNode. 1648 bool IsParamOfFunc = 1649 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1650 if (IsParamOfFunc) 1651 return false; 1652 1653 // The value is not used in this block yet (or it would have an SDNode). 1654 // We still want the value to appear for the user if possible -- if it has 1655 // an associated VReg, we can refer to that instead. 1656 auto VMI = FuncInfo.ValueMap.find(V); 1657 if (VMI != FuncInfo.ValueMap.end()) { 1658 unsigned Reg = VMI->second; 1659 // If this is a PHI node, it may be split up into several MI PHI nodes 1660 // (in FunctionLoweringInfo::set). 1661 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1662 V->getType(), std::nullopt); 1663 if (RFV.occupiesMultipleRegs()) { 1664 // FIXME: We could potentially support variadic dbg_values here. 1665 if (IsVariadic) 1666 return false; 1667 unsigned Offset = 0; 1668 unsigned BitsToDescribe = 0; 1669 if (auto VarSize = Var->getSizeInBits()) 1670 BitsToDescribe = *VarSize; 1671 if (auto Fragment = Expr->getFragmentInfo()) 1672 BitsToDescribe = Fragment->SizeInBits; 1673 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1674 // Bail out if all bits are described already. 1675 if (Offset >= BitsToDescribe) 1676 break; 1677 // TODO: handle scalable vectors. 1678 unsigned RegisterSize = RegAndSize.second; 1679 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1680 ? BitsToDescribe - Offset 1681 : RegisterSize; 1682 auto FragmentExpr = DIExpression::createFragmentExpression( 1683 Expr, Offset, FragmentSize); 1684 if (!FragmentExpr) 1685 continue; 1686 SDDbgValue *SDV = DAG.getVRegDbgValue( 1687 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1688 DAG.AddDbgValue(SDV, false); 1689 Offset += RegisterSize; 1690 } 1691 return true; 1692 } 1693 // We can use simple vreg locations for variadic dbg_values as well. 1694 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1695 continue; 1696 } 1697 // We failed to create a SDDbgOperand for V. 1698 return false; 1699 } 1700 1701 // We have created a SDDbgOperand for each Value in Values. 1702 // Should use Order instead of SDNodeOrder? 1703 assert(!LocationOps.empty()); 1704 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1705 /*IsIndirect=*/false, DbgLoc, 1706 SDNodeOrder, IsVariadic); 1707 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1708 return true; 1709 } 1710 1711 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1712 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1713 for (auto &Pair : DanglingDebugInfoMap) 1714 for (auto &DDI : Pair.second) 1715 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1716 clearDanglingDebugInfo(); 1717 } 1718 1719 /// getCopyFromRegs - If there was virtual register allocated for the value V 1720 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1721 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1722 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1723 SDValue Result; 1724 1725 if (It != FuncInfo.ValueMap.end()) { 1726 Register InReg = It->second; 1727 1728 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1729 DAG.getDataLayout(), InReg, Ty, 1730 std::nullopt); // This is not an ABI copy. 1731 SDValue Chain = DAG.getEntryNode(); 1732 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1733 V); 1734 resolveDanglingDebugInfo(V, Result); 1735 } 1736 1737 return Result; 1738 } 1739 1740 /// getValue - Return an SDValue for the given Value. 1741 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1742 // If we already have an SDValue for this value, use it. It's important 1743 // to do this first, so that we don't create a CopyFromReg if we already 1744 // have a regular SDValue. 1745 SDValue &N = NodeMap[V]; 1746 if (N.getNode()) return N; 1747 1748 // If there's a virtual register allocated and initialized for this 1749 // value, use it. 1750 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1751 return copyFromReg; 1752 1753 // Otherwise create a new SDValue and remember it. 1754 SDValue Val = getValueImpl(V); 1755 NodeMap[V] = Val; 1756 resolveDanglingDebugInfo(V, Val); 1757 return Val; 1758 } 1759 1760 /// getNonRegisterValue - Return an SDValue for the given Value, but 1761 /// don't look in FuncInfo.ValueMap for a virtual register. 1762 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1763 // If we already have an SDValue for this value, use it. 1764 SDValue &N = NodeMap[V]; 1765 if (N.getNode()) { 1766 if (isIntOrFPConstant(N)) { 1767 // Remove the debug location from the node as the node is about to be used 1768 // in a location which may differ from the original debug location. This 1769 // is relevant to Constant and ConstantFP nodes because they can appear 1770 // as constant expressions inside PHI nodes. 1771 N->setDebugLoc(DebugLoc()); 1772 } 1773 return N; 1774 } 1775 1776 // Otherwise create a new SDValue and remember it. 1777 SDValue Val = getValueImpl(V); 1778 NodeMap[V] = Val; 1779 resolveDanglingDebugInfo(V, Val); 1780 return Val; 1781 } 1782 1783 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1784 /// Create an SDValue for the given value. 1785 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1786 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1787 1788 if (const Constant *C = dyn_cast<Constant>(V)) { 1789 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1790 1791 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1792 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1793 1794 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1795 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1796 1797 if (isa<ConstantPointerNull>(C)) { 1798 unsigned AS = V->getType()->getPointerAddressSpace(); 1799 return DAG.getConstant(0, getCurSDLoc(), 1800 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1801 } 1802 1803 if (match(C, m_VScale())) 1804 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1805 1806 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1807 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1808 1809 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1810 return DAG.getUNDEF(VT); 1811 1812 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1813 visit(CE->getOpcode(), *CE); 1814 SDValue N1 = NodeMap[V]; 1815 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1816 return N1; 1817 } 1818 1819 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1820 SmallVector<SDValue, 4> Constants; 1821 for (const Use &U : C->operands()) { 1822 SDNode *Val = getValue(U).getNode(); 1823 // If the operand is an empty aggregate, there are no values. 1824 if (!Val) continue; 1825 // Add each leaf value from the operand to the Constants list 1826 // to form a flattened list of all the values. 1827 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1828 Constants.push_back(SDValue(Val, i)); 1829 } 1830 1831 return DAG.getMergeValues(Constants, getCurSDLoc()); 1832 } 1833 1834 if (const ConstantDataSequential *CDS = 1835 dyn_cast<ConstantDataSequential>(C)) { 1836 SmallVector<SDValue, 4> Ops; 1837 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1838 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1839 // Add each leaf value from the operand to the Constants list 1840 // to form a flattened list of all the values. 1841 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1842 Ops.push_back(SDValue(Val, i)); 1843 } 1844 1845 if (isa<ArrayType>(CDS->getType())) 1846 return DAG.getMergeValues(Ops, getCurSDLoc()); 1847 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1848 } 1849 1850 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1851 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1852 "Unknown struct or array constant!"); 1853 1854 SmallVector<EVT, 4> ValueVTs; 1855 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1856 unsigned NumElts = ValueVTs.size(); 1857 if (NumElts == 0) 1858 return SDValue(); // empty struct 1859 SmallVector<SDValue, 4> Constants(NumElts); 1860 for (unsigned i = 0; i != NumElts; ++i) { 1861 EVT EltVT = ValueVTs[i]; 1862 if (isa<UndefValue>(C)) 1863 Constants[i] = DAG.getUNDEF(EltVT); 1864 else if (EltVT.isFloatingPoint()) 1865 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1866 else 1867 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1868 } 1869 1870 return DAG.getMergeValues(Constants, getCurSDLoc()); 1871 } 1872 1873 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1874 return DAG.getBlockAddress(BA, VT); 1875 1876 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1877 return getValue(Equiv->getGlobalValue()); 1878 1879 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1880 return getValue(NC->getGlobalValue()); 1881 1882 if (VT == MVT::aarch64svcount) { 1883 assert(C->isNullValue() && "Can only zero this target type!"); 1884 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1885 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1886 } 1887 1888 VectorType *VecTy = cast<VectorType>(V->getType()); 1889 1890 // Now that we know the number and type of the elements, get that number of 1891 // elements into the Ops array based on what kind of constant it is. 1892 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1893 SmallVector<SDValue, 16> Ops; 1894 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1895 for (unsigned i = 0; i != NumElements; ++i) 1896 Ops.push_back(getValue(CV->getOperand(i))); 1897 1898 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1899 } 1900 1901 if (isa<ConstantAggregateZero>(C)) { 1902 EVT EltVT = 1903 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1904 1905 SDValue Op; 1906 if (EltVT.isFloatingPoint()) 1907 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1908 else 1909 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1910 1911 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1912 } 1913 1914 llvm_unreachable("Unknown vector constant"); 1915 } 1916 1917 // If this is a static alloca, generate it as the frameindex instead of 1918 // computation. 1919 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1920 DenseMap<const AllocaInst*, int>::iterator SI = 1921 FuncInfo.StaticAllocaMap.find(AI); 1922 if (SI != FuncInfo.StaticAllocaMap.end()) 1923 return DAG.getFrameIndex( 1924 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1925 } 1926 1927 // If this is an instruction which fast-isel has deferred, select it now. 1928 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1929 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1930 1931 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1932 Inst->getType(), std::nullopt); 1933 SDValue Chain = DAG.getEntryNode(); 1934 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1935 } 1936 1937 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1938 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1939 1940 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1941 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1942 1943 llvm_unreachable("Can't get register for value!"); 1944 } 1945 1946 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1947 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1948 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1949 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1950 bool IsSEH = isAsynchronousEHPersonality(Pers); 1951 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1952 if (!IsSEH) 1953 CatchPadMBB->setIsEHScopeEntry(); 1954 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1955 if (IsMSVCCXX || IsCoreCLR) 1956 CatchPadMBB->setIsEHFuncletEntry(); 1957 } 1958 1959 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1960 // Update machine-CFG edge. 1961 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1962 FuncInfo.MBB->addSuccessor(TargetMBB); 1963 TargetMBB->setIsEHCatchretTarget(true); 1964 DAG.getMachineFunction().setHasEHCatchret(true); 1965 1966 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1967 bool IsSEH = isAsynchronousEHPersonality(Pers); 1968 if (IsSEH) { 1969 // If this is not a fall-through branch or optimizations are switched off, 1970 // emit the branch. 1971 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1972 TM.getOptLevel() == CodeGenOptLevel::None) 1973 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1974 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1975 return; 1976 } 1977 1978 // Figure out the funclet membership for the catchret's successor. 1979 // This will be used by the FuncletLayout pass to determine how to order the 1980 // BB's. 1981 // A 'catchret' returns to the outer scope's color. 1982 Value *ParentPad = I.getCatchSwitchParentPad(); 1983 const BasicBlock *SuccessorColor; 1984 if (isa<ConstantTokenNone>(ParentPad)) 1985 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1986 else 1987 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1988 assert(SuccessorColor && "No parent funclet for catchret!"); 1989 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1990 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1991 1992 // Create the terminator node. 1993 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1994 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1995 DAG.getBasicBlock(SuccessorColorMBB)); 1996 DAG.setRoot(Ret); 1997 } 1998 1999 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 2000 // Don't emit any special code for the cleanuppad instruction. It just marks 2001 // the start of an EH scope/funclet. 2002 FuncInfo.MBB->setIsEHScopeEntry(); 2003 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2004 if (Pers != EHPersonality::Wasm_CXX) { 2005 FuncInfo.MBB->setIsEHFuncletEntry(); 2006 FuncInfo.MBB->setIsCleanupFuncletEntry(); 2007 } 2008 } 2009 2010 // In wasm EH, even though a catchpad may not catch an exception if a tag does 2011 // not match, it is OK to add only the first unwind destination catchpad to the 2012 // successors, because there will be at least one invoke instruction within the 2013 // catch scope that points to the next unwind destination, if one exists, so 2014 // CFGSort cannot mess up with BB sorting order. 2015 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 2016 // call within them, and catchpads only consisting of 'catch (...)' have a 2017 // '__cxa_end_catch' call within them, both of which generate invokes in case 2018 // the next unwind destination exists, i.e., the next unwind destination is not 2019 // the caller.) 2020 // 2021 // Having at most one EH pad successor is also simpler and helps later 2022 // transformations. 2023 // 2024 // For example, 2025 // current: 2026 // invoke void @foo to ... unwind label %catch.dispatch 2027 // catch.dispatch: 2028 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2029 // catch.start: 2030 // ... 2031 // ... in this BB or some other child BB dominated by this BB there will be an 2032 // invoke that points to 'next' BB as an unwind destination 2033 // 2034 // next: ; We don't need to add this to 'current' BB's successor 2035 // ... 2036 static void findWasmUnwindDestinations( 2037 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2038 BranchProbability Prob, 2039 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2040 &UnwindDests) { 2041 while (EHPadBB) { 2042 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2043 if (isa<CleanupPadInst>(Pad)) { 2044 // Stop on cleanup pads. 2045 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2046 UnwindDests.back().first->setIsEHScopeEntry(); 2047 break; 2048 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2049 // Add the catchpad handlers to the possible destinations. We don't 2050 // continue to the unwind destination of the catchswitch for wasm. 2051 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2052 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2053 UnwindDests.back().first->setIsEHScopeEntry(); 2054 } 2055 break; 2056 } else { 2057 continue; 2058 } 2059 } 2060 } 2061 2062 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2063 /// many places it could ultimately go. In the IR, we have a single unwind 2064 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2065 /// This function skips over imaginary basic blocks that hold catchswitch 2066 /// instructions, and finds all the "real" machine 2067 /// basic block destinations. As those destinations may not be successors of 2068 /// EHPadBB, here we also calculate the edge probability to those destinations. 2069 /// The passed-in Prob is the edge probability to EHPadBB. 2070 static void findUnwindDestinations( 2071 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2072 BranchProbability Prob, 2073 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2074 &UnwindDests) { 2075 EHPersonality Personality = 2076 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2077 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2078 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2079 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2080 bool IsSEH = isAsynchronousEHPersonality(Personality); 2081 2082 if (IsWasmCXX) { 2083 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2084 assert(UnwindDests.size() <= 1 && 2085 "There should be at most one unwind destination for wasm"); 2086 return; 2087 } 2088 2089 while (EHPadBB) { 2090 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2091 BasicBlock *NewEHPadBB = nullptr; 2092 if (isa<LandingPadInst>(Pad)) { 2093 // Stop on landingpads. They are not funclets. 2094 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2095 break; 2096 } else if (isa<CleanupPadInst>(Pad)) { 2097 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2098 // personalities. 2099 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2100 UnwindDests.back().first->setIsEHScopeEntry(); 2101 UnwindDests.back().first->setIsEHFuncletEntry(); 2102 break; 2103 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2104 // Add the catchpad handlers to the possible destinations. 2105 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2106 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2107 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2108 if (IsMSVCCXX || IsCoreCLR) 2109 UnwindDests.back().first->setIsEHFuncletEntry(); 2110 if (!IsSEH) 2111 UnwindDests.back().first->setIsEHScopeEntry(); 2112 } 2113 NewEHPadBB = CatchSwitch->getUnwindDest(); 2114 } else { 2115 continue; 2116 } 2117 2118 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2119 if (BPI && NewEHPadBB) 2120 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2121 EHPadBB = NewEHPadBB; 2122 } 2123 } 2124 2125 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2126 // Update successor info. 2127 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2128 auto UnwindDest = I.getUnwindDest(); 2129 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2130 BranchProbability UnwindDestProb = 2131 (BPI && UnwindDest) 2132 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2133 : BranchProbability::getZero(); 2134 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2135 for (auto &UnwindDest : UnwindDests) { 2136 UnwindDest.first->setIsEHPad(); 2137 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2138 } 2139 FuncInfo.MBB->normalizeSuccProbs(); 2140 2141 // Create the terminator node. 2142 SDValue Ret = 2143 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2144 DAG.setRoot(Ret); 2145 } 2146 2147 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2148 report_fatal_error("visitCatchSwitch not yet implemented!"); 2149 } 2150 2151 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2152 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2153 auto &DL = DAG.getDataLayout(); 2154 SDValue Chain = getControlRoot(); 2155 SmallVector<ISD::OutputArg, 8> Outs; 2156 SmallVector<SDValue, 8> OutVals; 2157 2158 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2159 // lower 2160 // 2161 // %val = call <ty> @llvm.experimental.deoptimize() 2162 // ret <ty> %val 2163 // 2164 // differently. 2165 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2166 LowerDeoptimizingReturn(); 2167 return; 2168 } 2169 2170 if (!FuncInfo.CanLowerReturn) { 2171 unsigned DemoteReg = FuncInfo.DemoteRegister; 2172 const Function *F = I.getParent()->getParent(); 2173 2174 // Emit a store of the return value through the virtual register. 2175 // Leave Outs empty so that LowerReturn won't try to load return 2176 // registers the usual way. 2177 SmallVector<EVT, 1> PtrValueVTs; 2178 ComputeValueVTs(TLI, DL, 2179 PointerType::get(F->getContext(), 2180 DAG.getDataLayout().getAllocaAddrSpace()), 2181 PtrValueVTs); 2182 2183 SDValue RetPtr = 2184 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2185 SDValue RetOp = getValue(I.getOperand(0)); 2186 2187 SmallVector<EVT, 4> ValueVTs, MemVTs; 2188 SmallVector<uint64_t, 4> Offsets; 2189 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2190 &Offsets, 0); 2191 unsigned NumValues = ValueVTs.size(); 2192 2193 SmallVector<SDValue, 4> Chains(NumValues); 2194 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2195 for (unsigned i = 0; i != NumValues; ++i) { 2196 // An aggregate return value cannot wrap around the address space, so 2197 // offsets to its parts don't wrap either. 2198 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2199 TypeSize::getFixed(Offsets[i])); 2200 2201 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2202 if (MemVTs[i] != ValueVTs[i]) 2203 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2204 Chains[i] = DAG.getStore( 2205 Chain, getCurSDLoc(), Val, 2206 // FIXME: better loc info would be nice. 2207 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2208 commonAlignment(BaseAlign, Offsets[i])); 2209 } 2210 2211 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2212 MVT::Other, Chains); 2213 } else if (I.getNumOperands() != 0) { 2214 SmallVector<EVT, 4> ValueVTs; 2215 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2216 unsigned NumValues = ValueVTs.size(); 2217 if (NumValues) { 2218 SDValue RetOp = getValue(I.getOperand(0)); 2219 2220 const Function *F = I.getParent()->getParent(); 2221 2222 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2223 I.getOperand(0)->getType(), F->getCallingConv(), 2224 /*IsVarArg*/ false, DL); 2225 2226 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2227 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2228 ExtendKind = ISD::SIGN_EXTEND; 2229 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2230 ExtendKind = ISD::ZERO_EXTEND; 2231 2232 LLVMContext &Context = F->getContext(); 2233 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2234 2235 for (unsigned j = 0; j != NumValues; ++j) { 2236 EVT VT = ValueVTs[j]; 2237 2238 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2239 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2240 2241 CallingConv::ID CC = F->getCallingConv(); 2242 2243 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2244 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2245 SmallVector<SDValue, 4> Parts(NumParts); 2246 getCopyToParts(DAG, getCurSDLoc(), 2247 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2248 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2249 2250 // 'inreg' on function refers to return value 2251 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2252 if (RetInReg) 2253 Flags.setInReg(); 2254 2255 if (I.getOperand(0)->getType()->isPointerTy()) { 2256 Flags.setPointer(); 2257 Flags.setPointerAddrSpace( 2258 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2259 } 2260 2261 if (NeedsRegBlock) { 2262 Flags.setInConsecutiveRegs(); 2263 if (j == NumValues - 1) 2264 Flags.setInConsecutiveRegsLast(); 2265 } 2266 2267 // Propagate extension type if any 2268 if (ExtendKind == ISD::SIGN_EXTEND) 2269 Flags.setSExt(); 2270 else if (ExtendKind == ISD::ZERO_EXTEND) 2271 Flags.setZExt(); 2272 2273 for (unsigned i = 0; i < NumParts; ++i) { 2274 Outs.push_back(ISD::OutputArg(Flags, 2275 Parts[i].getValueType().getSimpleVT(), 2276 VT, /*isfixed=*/true, 0, 0)); 2277 OutVals.push_back(Parts[i]); 2278 } 2279 } 2280 } 2281 } 2282 2283 // Push in swifterror virtual register as the last element of Outs. This makes 2284 // sure swifterror virtual register will be returned in the swifterror 2285 // physical register. 2286 const Function *F = I.getParent()->getParent(); 2287 if (TLI.supportSwiftError() && 2288 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2289 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2290 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2291 Flags.setSwiftError(); 2292 Outs.push_back(ISD::OutputArg( 2293 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2294 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2295 // Create SDNode for the swifterror virtual register. 2296 OutVals.push_back( 2297 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2298 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2299 EVT(TLI.getPointerTy(DL)))); 2300 } 2301 2302 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2303 CallingConv::ID CallConv = 2304 DAG.getMachineFunction().getFunction().getCallingConv(); 2305 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2306 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2307 2308 // Verify that the target's LowerReturn behaved as expected. 2309 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2310 "LowerReturn didn't return a valid chain!"); 2311 2312 // Update the DAG with the new chain value resulting from return lowering. 2313 DAG.setRoot(Chain); 2314 } 2315 2316 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2317 /// created for it, emit nodes to copy the value into the virtual 2318 /// registers. 2319 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2320 // Skip empty types 2321 if (V->getType()->isEmptyTy()) 2322 return; 2323 2324 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2325 if (VMI != FuncInfo.ValueMap.end()) { 2326 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2327 "Unused value assigned virtual registers!"); 2328 CopyValueToVirtualRegister(V, VMI->second); 2329 } 2330 } 2331 2332 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2333 /// the current basic block, add it to ValueMap now so that we'll get a 2334 /// CopyTo/FromReg. 2335 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2336 // No need to export constants. 2337 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2338 2339 // Already exported? 2340 if (FuncInfo.isExportedInst(V)) return; 2341 2342 Register Reg = FuncInfo.InitializeRegForValue(V); 2343 CopyValueToVirtualRegister(V, Reg); 2344 } 2345 2346 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2347 const BasicBlock *FromBB) { 2348 // The operands of the setcc have to be in this block. We don't know 2349 // how to export them from some other block. 2350 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2351 // Can export from current BB. 2352 if (VI->getParent() == FromBB) 2353 return true; 2354 2355 // Is already exported, noop. 2356 return FuncInfo.isExportedInst(V); 2357 } 2358 2359 // If this is an argument, we can export it if the BB is the entry block or 2360 // if it is already exported. 2361 if (isa<Argument>(V)) { 2362 if (FromBB->isEntryBlock()) 2363 return true; 2364 2365 // Otherwise, can only export this if it is already exported. 2366 return FuncInfo.isExportedInst(V); 2367 } 2368 2369 // Otherwise, constants can always be exported. 2370 return true; 2371 } 2372 2373 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2374 BranchProbability 2375 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2376 const MachineBasicBlock *Dst) const { 2377 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2378 const BasicBlock *SrcBB = Src->getBasicBlock(); 2379 const BasicBlock *DstBB = Dst->getBasicBlock(); 2380 if (!BPI) { 2381 // If BPI is not available, set the default probability as 1 / N, where N is 2382 // the number of successors. 2383 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2384 return BranchProbability(1, SuccSize); 2385 } 2386 return BPI->getEdgeProbability(SrcBB, DstBB); 2387 } 2388 2389 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2390 MachineBasicBlock *Dst, 2391 BranchProbability Prob) { 2392 if (!FuncInfo.BPI) 2393 Src->addSuccessorWithoutProb(Dst); 2394 else { 2395 if (Prob.isUnknown()) 2396 Prob = getEdgeProbability(Src, Dst); 2397 Src->addSuccessor(Dst, Prob); 2398 } 2399 } 2400 2401 static bool InBlock(const Value *V, const BasicBlock *BB) { 2402 if (const Instruction *I = dyn_cast<Instruction>(V)) 2403 return I->getParent() == BB; 2404 return true; 2405 } 2406 2407 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2408 /// This function emits a branch and is used at the leaves of an OR or an 2409 /// AND operator tree. 2410 void 2411 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2412 MachineBasicBlock *TBB, 2413 MachineBasicBlock *FBB, 2414 MachineBasicBlock *CurBB, 2415 MachineBasicBlock *SwitchBB, 2416 BranchProbability TProb, 2417 BranchProbability FProb, 2418 bool InvertCond) { 2419 const BasicBlock *BB = CurBB->getBasicBlock(); 2420 2421 // If the leaf of the tree is a comparison, merge the condition into 2422 // the caseblock. 2423 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2424 // The operands of the cmp have to be in this block. We don't know 2425 // how to export them from some other block. If this is the first block 2426 // of the sequence, no exporting is needed. 2427 if (CurBB == SwitchBB || 2428 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2429 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2430 ISD::CondCode Condition; 2431 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2432 ICmpInst::Predicate Pred = 2433 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2434 Condition = getICmpCondCode(Pred); 2435 } else { 2436 const FCmpInst *FC = cast<FCmpInst>(Cond); 2437 FCmpInst::Predicate Pred = 2438 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2439 Condition = getFCmpCondCode(Pred); 2440 if (TM.Options.NoNaNsFPMath) 2441 Condition = getFCmpCodeWithoutNaN(Condition); 2442 } 2443 2444 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2445 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2446 SL->SwitchCases.push_back(CB); 2447 return; 2448 } 2449 } 2450 2451 // Create a CaseBlock record representing this branch. 2452 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2453 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2454 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2455 SL->SwitchCases.push_back(CB); 2456 } 2457 2458 // Collect dependencies on V recursively. This is used for the cost analysis in 2459 // `shouldKeepJumpConditionsTogether`. 2460 static bool collectInstructionDeps( 2461 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V, 2462 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr, 2463 unsigned Depth = 0) { 2464 // Return false if we have an incomplete count. 2465 if (Depth >= SelectionDAG::MaxRecursionDepth) 2466 return false; 2467 2468 auto *I = dyn_cast<Instruction>(V); 2469 if (I == nullptr) 2470 return true; 2471 2472 if (Necessary != nullptr) { 2473 // This instruction is necessary for the other side of the condition so 2474 // don't count it. 2475 if (Necessary->contains(I)) 2476 return true; 2477 } 2478 2479 // Already added this dep. 2480 if (!Deps->try_emplace(I, false).second) 2481 return true; 2482 2483 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx) 2484 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary, 2485 Depth + 1)) 2486 return false; 2487 return true; 2488 } 2489 2490 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether( 2491 const FunctionLoweringInfo &FuncInfo, const BranchInst &I, 2492 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, 2493 TargetLoweringBase::CondMergingParams Params) const { 2494 if (I.getNumSuccessors() != 2) 2495 return false; 2496 2497 if (!I.isConditional()) 2498 return false; 2499 2500 if (Params.BaseCost < 0) 2501 return false; 2502 2503 // Baseline cost. 2504 InstructionCost CostThresh = Params.BaseCost; 2505 2506 BranchProbabilityInfo *BPI = nullptr; 2507 if (Params.LikelyBias || Params.UnlikelyBias) 2508 BPI = FuncInfo.BPI; 2509 if (BPI != nullptr) { 2510 // See if we are either likely to get an early out or compute both lhs/rhs 2511 // of the condition. 2512 BasicBlock *IfFalse = I.getSuccessor(0); 2513 BasicBlock *IfTrue = I.getSuccessor(1); 2514 2515 std::optional<bool> Likely; 2516 if (BPI->isEdgeHot(I.getParent(), IfTrue)) 2517 Likely = true; 2518 else if (BPI->isEdgeHot(I.getParent(), IfFalse)) 2519 Likely = false; 2520 2521 if (Likely) { 2522 if (Opc == (*Likely ? Instruction::And : Instruction::Or)) 2523 // Its likely we will have to compute both lhs and rhs of condition 2524 CostThresh += Params.LikelyBias; 2525 else { 2526 if (Params.UnlikelyBias < 0) 2527 return false; 2528 // Its likely we will get an early out. 2529 CostThresh -= Params.UnlikelyBias; 2530 } 2531 } 2532 } 2533 2534 if (CostThresh <= 0) 2535 return false; 2536 2537 // Collect "all" instructions that lhs condition is dependent on. 2538 // Use map for stable iteration (to avoid non-determanism of iteration of 2539 // SmallPtrSet). The `bool` value is just a dummy. 2540 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps; 2541 collectInstructionDeps(&LhsDeps, Lhs); 2542 // Collect "all" instructions that rhs condition is dependent on AND are 2543 // dependencies of lhs. This gives us an estimate on which instructions we 2544 // stand to save by splitting the condition. 2545 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps)) 2546 return false; 2547 // Add the compare instruction itself unless its a dependency on the LHS. 2548 if (const auto *RhsI = dyn_cast<Instruction>(Rhs)) 2549 if (!LhsDeps.contains(RhsI)) 2550 RhsDeps.try_emplace(RhsI, false); 2551 2552 const auto &TLI = DAG.getTargetLoweringInfo(); 2553 const auto &TTI = 2554 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 2555 2556 InstructionCost CostOfIncluding = 0; 2557 // See if this instruction will need to computed independently of whether RHS 2558 // is. 2559 Value *BrCond = I.getCondition(); 2560 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) { 2561 for (const auto *U : Ins->users()) { 2562 // If user is independent of RHS calculation we don't need to count it. 2563 if (auto *UIns = dyn_cast<Instruction>(U)) 2564 if (UIns != BrCond && !RhsDeps.contains(UIns)) 2565 return false; 2566 } 2567 return true; 2568 }; 2569 2570 // Prune instructions from RHS Deps that are dependencies of unrelated 2571 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly 2572 // arbitrary and just meant to cap the how much time we spend in the pruning 2573 // loop. Its highly unlikely to come into affect. 2574 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth; 2575 // Stop after a certain point. No incorrectness from including too many 2576 // instructions. 2577 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) { 2578 const Instruction *ToDrop = nullptr; 2579 for (const auto &InsPair : RhsDeps) { 2580 if (!ShouldCountInsn(InsPair.first)) { 2581 ToDrop = InsPair.first; 2582 break; 2583 } 2584 } 2585 if (ToDrop == nullptr) 2586 break; 2587 RhsDeps.erase(ToDrop); 2588 } 2589 2590 for (const auto &InsPair : RhsDeps) { 2591 // Finally accumulate latency that we can only attribute to computing the 2592 // RHS condition. Use latency because we are essentially trying to calculate 2593 // the cost of the dependency chain. 2594 // Possible TODO: We could try to estimate ILP and make this more precise. 2595 CostOfIncluding += 2596 TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency); 2597 2598 if (CostOfIncluding > CostThresh) 2599 return false; 2600 } 2601 return true; 2602 } 2603 2604 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2605 MachineBasicBlock *TBB, 2606 MachineBasicBlock *FBB, 2607 MachineBasicBlock *CurBB, 2608 MachineBasicBlock *SwitchBB, 2609 Instruction::BinaryOps Opc, 2610 BranchProbability TProb, 2611 BranchProbability FProb, 2612 bool InvertCond) { 2613 // Skip over not part of the tree and remember to invert op and operands at 2614 // next level. 2615 Value *NotCond; 2616 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2617 InBlock(NotCond, CurBB->getBasicBlock())) { 2618 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2619 !InvertCond); 2620 return; 2621 } 2622 2623 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2624 const Value *BOpOp0, *BOpOp1; 2625 // Compute the effective opcode for Cond, taking into account whether it needs 2626 // to be inverted, e.g. 2627 // and (not (or A, B)), C 2628 // gets lowered as 2629 // and (and (not A, not B), C) 2630 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2631 if (BOp) { 2632 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2633 ? Instruction::And 2634 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2635 ? Instruction::Or 2636 : (Instruction::BinaryOps)0); 2637 if (InvertCond) { 2638 if (BOpc == Instruction::And) 2639 BOpc = Instruction::Or; 2640 else if (BOpc == Instruction::Or) 2641 BOpc = Instruction::And; 2642 } 2643 } 2644 2645 // If this node is not part of the or/and tree, emit it as a branch. 2646 // Note that all nodes in the tree should have same opcode. 2647 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2648 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2649 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2650 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2651 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2652 TProb, FProb, InvertCond); 2653 return; 2654 } 2655 2656 // Create TmpBB after CurBB. 2657 MachineFunction::iterator BBI(CurBB); 2658 MachineFunction &MF = DAG.getMachineFunction(); 2659 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2660 CurBB->getParent()->insert(++BBI, TmpBB); 2661 2662 if (Opc == Instruction::Or) { 2663 // Codegen X | Y as: 2664 // BB1: 2665 // jmp_if_X TBB 2666 // jmp TmpBB 2667 // TmpBB: 2668 // jmp_if_Y TBB 2669 // jmp FBB 2670 // 2671 2672 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2673 // The requirement is that 2674 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2675 // = TrueProb for original BB. 2676 // Assuming the original probabilities are A and B, one choice is to set 2677 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2678 // A/(1+B) and 2B/(1+B). This choice assumes that 2679 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2680 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2681 // TmpBB, but the math is more complicated. 2682 2683 auto NewTrueProb = TProb / 2; 2684 auto NewFalseProb = TProb / 2 + FProb; 2685 // Emit the LHS condition. 2686 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2687 NewFalseProb, InvertCond); 2688 2689 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2690 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2691 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2692 // Emit the RHS condition into TmpBB. 2693 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2694 Probs[1], InvertCond); 2695 } else { 2696 assert(Opc == Instruction::And && "Unknown merge op!"); 2697 // Codegen X & Y as: 2698 // BB1: 2699 // jmp_if_X TmpBB 2700 // jmp FBB 2701 // TmpBB: 2702 // jmp_if_Y TBB 2703 // jmp FBB 2704 // 2705 // This requires creation of TmpBB after CurBB. 2706 2707 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2708 // The requirement is that 2709 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2710 // = FalseProb for original BB. 2711 // Assuming the original probabilities are A and B, one choice is to set 2712 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2713 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2714 // TrueProb for BB1 * FalseProb for TmpBB. 2715 2716 auto NewTrueProb = TProb + FProb / 2; 2717 auto NewFalseProb = FProb / 2; 2718 // Emit the LHS condition. 2719 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2720 NewFalseProb, InvertCond); 2721 2722 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2723 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2724 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2725 // Emit the RHS condition into TmpBB. 2726 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2727 Probs[1], InvertCond); 2728 } 2729 } 2730 2731 /// If the set of cases should be emitted as a series of branches, return true. 2732 /// If we should emit this as a bunch of and/or'd together conditions, return 2733 /// false. 2734 bool 2735 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2736 if (Cases.size() != 2) return true; 2737 2738 // If this is two comparisons of the same values or'd or and'd together, they 2739 // will get folded into a single comparison, so don't emit two blocks. 2740 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2741 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2742 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2743 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2744 return false; 2745 } 2746 2747 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2748 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2749 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2750 Cases[0].CC == Cases[1].CC && 2751 isa<Constant>(Cases[0].CmpRHS) && 2752 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2753 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2754 return false; 2755 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2756 return false; 2757 } 2758 2759 return true; 2760 } 2761 2762 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2763 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2764 2765 // Update machine-CFG edges. 2766 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2767 2768 if (I.isUnconditional()) { 2769 // Update machine-CFG edges. 2770 BrMBB->addSuccessor(Succ0MBB); 2771 2772 // If this is not a fall-through branch or optimizations are switched off, 2773 // emit the branch. 2774 if (Succ0MBB != NextBlock(BrMBB) || 2775 TM.getOptLevel() == CodeGenOptLevel::None) { 2776 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2777 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2778 setValue(&I, Br); 2779 DAG.setRoot(Br); 2780 } 2781 2782 return; 2783 } 2784 2785 // If this condition is one of the special cases we handle, do special stuff 2786 // now. 2787 const Value *CondVal = I.getCondition(); 2788 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2789 2790 // If this is a series of conditions that are or'd or and'd together, emit 2791 // this as a sequence of branches instead of setcc's with and/or operations. 2792 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2793 // unpredictable branches, and vector extracts because those jumps are likely 2794 // expensive for any target), this should improve performance. 2795 // For example, instead of something like: 2796 // cmp A, B 2797 // C = seteq 2798 // cmp D, E 2799 // F = setle 2800 // or C, F 2801 // jnz foo 2802 // Emit: 2803 // cmp A, B 2804 // je foo 2805 // cmp D, E 2806 // jle foo 2807 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2808 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2809 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2810 Value *Vec; 2811 const Value *BOp0, *BOp1; 2812 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2813 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2814 Opcode = Instruction::And; 2815 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2816 Opcode = Instruction::Or; 2817 2818 if (Opcode && 2819 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2820 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) && 2821 !shouldKeepJumpConditionsTogether( 2822 FuncInfo, I, Opcode, BOp0, BOp1, 2823 DAG.getTargetLoweringInfo().getJumpConditionMergingParams( 2824 Opcode, BOp0, BOp1))) { 2825 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2826 getEdgeProbability(BrMBB, Succ0MBB), 2827 getEdgeProbability(BrMBB, Succ1MBB), 2828 /*InvertCond=*/false); 2829 // If the compares in later blocks need to use values not currently 2830 // exported from this block, export them now. This block should always 2831 // be the first entry. 2832 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2833 2834 // Allow some cases to be rejected. 2835 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2836 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2837 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2838 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2839 } 2840 2841 // Emit the branch for this block. 2842 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2843 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2844 return; 2845 } 2846 2847 // Okay, we decided not to do this, remove any inserted MBB's and clear 2848 // SwitchCases. 2849 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2850 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2851 2852 SL->SwitchCases.clear(); 2853 } 2854 } 2855 2856 // Create a CaseBlock record representing this branch. 2857 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2858 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2859 2860 // Use visitSwitchCase to actually insert the fast branch sequence for this 2861 // cond branch. 2862 visitSwitchCase(CB, BrMBB); 2863 } 2864 2865 /// visitSwitchCase - Emits the necessary code to represent a single node in 2866 /// the binary search tree resulting from lowering a switch instruction. 2867 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2868 MachineBasicBlock *SwitchBB) { 2869 SDValue Cond; 2870 SDValue CondLHS = getValue(CB.CmpLHS); 2871 SDLoc dl = CB.DL; 2872 2873 if (CB.CC == ISD::SETTRUE) { 2874 // Branch or fall through to TrueBB. 2875 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2876 SwitchBB->normalizeSuccProbs(); 2877 if (CB.TrueBB != NextBlock(SwitchBB)) { 2878 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2879 DAG.getBasicBlock(CB.TrueBB))); 2880 } 2881 return; 2882 } 2883 2884 auto &TLI = DAG.getTargetLoweringInfo(); 2885 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2886 2887 // Build the setcc now. 2888 if (!CB.CmpMHS) { 2889 // Fold "(X == true)" to X and "(X == false)" to !X to 2890 // handle common cases produced by branch lowering. 2891 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2892 CB.CC == ISD::SETEQ) 2893 Cond = CondLHS; 2894 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2895 CB.CC == ISD::SETEQ) { 2896 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2897 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2898 } else { 2899 SDValue CondRHS = getValue(CB.CmpRHS); 2900 2901 // If a pointer's DAG type is larger than its memory type then the DAG 2902 // values are zero-extended. This breaks signed comparisons so truncate 2903 // back to the underlying type before doing the compare. 2904 if (CondLHS.getValueType() != MemVT) { 2905 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2906 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2907 } 2908 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2909 } 2910 } else { 2911 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2912 2913 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2914 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2915 2916 SDValue CmpOp = getValue(CB.CmpMHS); 2917 EVT VT = CmpOp.getValueType(); 2918 2919 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2920 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2921 ISD::SETLE); 2922 } else { 2923 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2924 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2925 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2926 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2927 } 2928 } 2929 2930 // Update successor info 2931 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2932 // TrueBB and FalseBB are always different unless the incoming IR is 2933 // degenerate. This only happens when running llc on weird IR. 2934 if (CB.TrueBB != CB.FalseBB) 2935 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2936 SwitchBB->normalizeSuccProbs(); 2937 2938 // If the lhs block is the next block, invert the condition so that we can 2939 // fall through to the lhs instead of the rhs block. 2940 if (CB.TrueBB == NextBlock(SwitchBB)) { 2941 std::swap(CB.TrueBB, CB.FalseBB); 2942 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2943 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2944 } 2945 2946 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2947 MVT::Other, getControlRoot(), Cond, 2948 DAG.getBasicBlock(CB.TrueBB)); 2949 2950 setValue(CurInst, BrCond); 2951 2952 // Insert the false branch. Do this even if it's a fall through branch, 2953 // this makes it easier to do DAG optimizations which require inverting 2954 // the branch condition. 2955 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2956 DAG.getBasicBlock(CB.FalseBB)); 2957 2958 DAG.setRoot(BrCond); 2959 } 2960 2961 /// visitJumpTable - Emit JumpTable node in the current MBB 2962 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2963 // Emit the code for the jump table 2964 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2965 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2966 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2967 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2968 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2969 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2970 Index.getValue(1), Table, Index); 2971 DAG.setRoot(BrJumpTable); 2972 } 2973 2974 /// visitJumpTableHeader - This function emits necessary code to produce index 2975 /// in the JumpTable from switch case. 2976 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2977 JumpTableHeader &JTH, 2978 MachineBasicBlock *SwitchBB) { 2979 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2980 const SDLoc &dl = *JT.SL; 2981 2982 // Subtract the lowest switch case value from the value being switched on. 2983 SDValue SwitchOp = getValue(JTH.SValue); 2984 EVT VT = SwitchOp.getValueType(); 2985 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2986 DAG.getConstant(JTH.First, dl, VT)); 2987 2988 // The SDNode we just created, which holds the value being switched on minus 2989 // the smallest case value, needs to be copied to a virtual register so it 2990 // can be used as an index into the jump table in a subsequent basic block. 2991 // This value may be smaller or larger than the target's pointer type, and 2992 // therefore require extension or truncating. 2993 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2994 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2995 2996 unsigned JumpTableReg = 2997 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2998 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2999 JumpTableReg, SwitchOp); 3000 JT.Reg = JumpTableReg; 3001 3002 if (!JTH.FallthroughUnreachable) { 3003 // Emit the range check for the jump table, and branch to the default block 3004 // for the switch statement if the value being switched on exceeds the 3005 // largest case in the switch. 3006 SDValue CMP = DAG.getSetCC( 3007 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3008 Sub.getValueType()), 3009 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 3010 3011 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3012 MVT::Other, CopyTo, CMP, 3013 DAG.getBasicBlock(JT.Default)); 3014 3015 // Avoid emitting unnecessary branches to the next block. 3016 if (JT.MBB != NextBlock(SwitchBB)) 3017 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 3018 DAG.getBasicBlock(JT.MBB)); 3019 3020 DAG.setRoot(BrCond); 3021 } else { 3022 // Avoid emitting unnecessary branches to the next block. 3023 if (JT.MBB != NextBlock(SwitchBB)) 3024 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 3025 DAG.getBasicBlock(JT.MBB))); 3026 else 3027 DAG.setRoot(CopyTo); 3028 } 3029 } 3030 3031 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 3032 /// variable if there exists one. 3033 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 3034 SDValue &Chain) { 3035 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3036 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3037 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3038 MachineFunction &MF = DAG.getMachineFunction(); 3039 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 3040 MachineSDNode *Node = 3041 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 3042 if (Global) { 3043 MachinePointerInfo MPInfo(Global); 3044 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 3045 MachineMemOperand::MODereferenceable; 3046 MachineMemOperand *MemRef = MF.getMachineMemOperand( 3047 MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8), 3048 DAG.getEVTAlign(PtrTy)); 3049 DAG.setNodeMemRefs(Node, {MemRef}); 3050 } 3051 if (PtrTy != PtrMemTy) 3052 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 3053 return SDValue(Node, 0); 3054 } 3055 3056 /// Codegen a new tail for a stack protector check ParentMBB which has had its 3057 /// tail spliced into a stack protector check success bb. 3058 /// 3059 /// For a high level explanation of how this fits into the stack protector 3060 /// generation see the comment on the declaration of class 3061 /// StackProtectorDescriptor. 3062 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 3063 MachineBasicBlock *ParentBB) { 3064 3065 // First create the loads to the guard/stack slot for the comparison. 3066 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3067 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3068 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3069 3070 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 3071 int FI = MFI.getStackProtectorIndex(); 3072 3073 SDValue Guard; 3074 SDLoc dl = getCurSDLoc(); 3075 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 3076 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 3077 Align Align = 3078 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 3079 3080 // Generate code to load the content of the guard slot. 3081 SDValue GuardVal = DAG.getLoad( 3082 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 3083 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 3084 MachineMemOperand::MOVolatile); 3085 3086 if (TLI.useStackGuardXorFP()) 3087 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 3088 3089 // Retrieve guard check function, nullptr if instrumentation is inlined. 3090 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 3091 // The target provides a guard check function to validate the guard value. 3092 // Generate a call to that function with the content of the guard slot as 3093 // argument. 3094 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 3095 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 3096 3097 TargetLowering::ArgListTy Args; 3098 TargetLowering::ArgListEntry Entry; 3099 Entry.Node = GuardVal; 3100 Entry.Ty = FnTy->getParamType(0); 3101 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 3102 Entry.IsInReg = true; 3103 Args.push_back(Entry); 3104 3105 TargetLowering::CallLoweringInfo CLI(DAG); 3106 CLI.setDebugLoc(getCurSDLoc()) 3107 .setChain(DAG.getEntryNode()) 3108 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 3109 getValue(GuardCheckFn), std::move(Args)); 3110 3111 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 3112 DAG.setRoot(Result.second); 3113 return; 3114 } 3115 3116 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 3117 // Otherwise, emit a volatile load to retrieve the stack guard value. 3118 SDValue Chain = DAG.getEntryNode(); 3119 if (TLI.useLoadStackGuardNode()) { 3120 Guard = getLoadStackGuard(DAG, dl, Chain); 3121 } else { 3122 const Value *IRGuard = TLI.getSDagStackGuard(M); 3123 SDValue GuardPtr = getValue(IRGuard); 3124 3125 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 3126 MachinePointerInfo(IRGuard, 0), Align, 3127 MachineMemOperand::MOVolatile); 3128 } 3129 3130 // Perform the comparison via a getsetcc. 3131 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 3132 *DAG.getContext(), 3133 Guard.getValueType()), 3134 Guard, GuardVal, ISD::SETNE); 3135 3136 // If the guard/stackslot do not equal, branch to failure MBB. 3137 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3138 MVT::Other, GuardVal.getOperand(0), 3139 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 3140 // Otherwise branch to success MBB. 3141 SDValue Br = DAG.getNode(ISD::BR, dl, 3142 MVT::Other, BrCond, 3143 DAG.getBasicBlock(SPD.getSuccessMBB())); 3144 3145 DAG.setRoot(Br); 3146 } 3147 3148 /// Codegen the failure basic block for a stack protector check. 3149 /// 3150 /// A failure stack protector machine basic block consists simply of a call to 3151 /// __stack_chk_fail(). 3152 /// 3153 /// For a high level explanation of how this fits into the stack protector 3154 /// generation see the comment on the declaration of class 3155 /// StackProtectorDescriptor. 3156 void 3157 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 3158 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3159 TargetLowering::MakeLibCallOptions CallOptions; 3160 CallOptions.setDiscardResult(true); 3161 SDValue Chain = 3162 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 3163 std::nullopt, CallOptions, getCurSDLoc()) 3164 .second; 3165 // On PS4/PS5, the "return address" must still be within the calling 3166 // function, even if it's at the very end, so emit an explicit TRAP here. 3167 // Passing 'true' for doesNotReturn above won't generate the trap for us. 3168 if (TM.getTargetTriple().isPS()) 3169 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3170 // WebAssembly needs an unreachable instruction after a non-returning call, 3171 // because the function return type can be different from __stack_chk_fail's 3172 // return type (void). 3173 if (TM.getTargetTriple().isWasm()) 3174 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3175 3176 DAG.setRoot(Chain); 3177 } 3178 3179 /// visitBitTestHeader - This function emits necessary code to produce value 3180 /// suitable for "bit tests" 3181 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3182 MachineBasicBlock *SwitchBB) { 3183 SDLoc dl = getCurSDLoc(); 3184 3185 // Subtract the minimum value. 3186 SDValue SwitchOp = getValue(B.SValue); 3187 EVT VT = SwitchOp.getValueType(); 3188 SDValue RangeSub = 3189 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3190 3191 // Determine the type of the test operands. 3192 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3193 bool UsePtrType = false; 3194 if (!TLI.isTypeLegal(VT)) { 3195 UsePtrType = true; 3196 } else { 3197 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3198 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3199 // Switch table case range are encoded into series of masks. 3200 // Just use pointer type, it's guaranteed to fit. 3201 UsePtrType = true; 3202 break; 3203 } 3204 } 3205 SDValue Sub = RangeSub; 3206 if (UsePtrType) { 3207 VT = TLI.getPointerTy(DAG.getDataLayout()); 3208 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3209 } 3210 3211 B.RegVT = VT.getSimpleVT(); 3212 B.Reg = FuncInfo.CreateReg(B.RegVT); 3213 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3214 3215 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3216 3217 if (!B.FallthroughUnreachable) 3218 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3219 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3220 SwitchBB->normalizeSuccProbs(); 3221 3222 SDValue Root = CopyTo; 3223 if (!B.FallthroughUnreachable) { 3224 // Conditional branch to the default block. 3225 SDValue RangeCmp = DAG.getSetCC(dl, 3226 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3227 RangeSub.getValueType()), 3228 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3229 ISD::SETUGT); 3230 3231 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3232 DAG.getBasicBlock(B.Default)); 3233 } 3234 3235 // Avoid emitting unnecessary branches to the next block. 3236 if (MBB != NextBlock(SwitchBB)) 3237 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3238 3239 DAG.setRoot(Root); 3240 } 3241 3242 /// visitBitTestCase - this function produces one "bit test" 3243 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3244 MachineBasicBlock* NextMBB, 3245 BranchProbability BranchProbToNext, 3246 unsigned Reg, 3247 BitTestCase &B, 3248 MachineBasicBlock *SwitchBB) { 3249 SDLoc dl = getCurSDLoc(); 3250 MVT VT = BB.RegVT; 3251 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3252 SDValue Cmp; 3253 unsigned PopCount = llvm::popcount(B.Mask); 3254 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3255 if (PopCount == 1) { 3256 // Testing for a single bit; just compare the shift count with what it 3257 // would need to be to shift a 1 bit in that position. 3258 Cmp = DAG.getSetCC( 3259 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3260 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3261 ISD::SETEQ); 3262 } else if (PopCount == BB.Range) { 3263 // There is only one zero bit in the range, test for it directly. 3264 Cmp = DAG.getSetCC( 3265 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3266 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3267 } else { 3268 // Make desired shift 3269 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3270 DAG.getConstant(1, dl, VT), ShiftOp); 3271 3272 // Emit bit tests and jumps 3273 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3274 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3275 Cmp = DAG.getSetCC( 3276 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3277 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3278 } 3279 3280 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3281 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3282 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3283 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3284 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3285 // one as they are relative probabilities (and thus work more like weights), 3286 // and hence we need to normalize them to let the sum of them become one. 3287 SwitchBB->normalizeSuccProbs(); 3288 3289 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3290 MVT::Other, getControlRoot(), 3291 Cmp, DAG.getBasicBlock(B.TargetBB)); 3292 3293 // Avoid emitting unnecessary branches to the next block. 3294 if (NextMBB != NextBlock(SwitchBB)) 3295 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3296 DAG.getBasicBlock(NextMBB)); 3297 3298 DAG.setRoot(BrAnd); 3299 } 3300 3301 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3302 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3303 3304 // Retrieve successors. Look through artificial IR level blocks like 3305 // catchswitch for successors. 3306 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3307 const BasicBlock *EHPadBB = I.getSuccessor(1); 3308 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3309 3310 // Deopt and ptrauth bundles are lowered in helper functions, and we don't 3311 // have to do anything here to lower funclet bundles. 3312 assert(!I.hasOperandBundlesOtherThan( 3313 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3314 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3315 LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth, 3316 LLVMContext::OB_clang_arc_attachedcall}) && 3317 "Cannot lower invokes with arbitrary operand bundles yet!"); 3318 3319 const Value *Callee(I.getCalledOperand()); 3320 const Function *Fn = dyn_cast<Function>(Callee); 3321 if (isa<InlineAsm>(Callee)) 3322 visitInlineAsm(I, EHPadBB); 3323 else if (Fn && Fn->isIntrinsic()) { 3324 switch (Fn->getIntrinsicID()) { 3325 default: 3326 llvm_unreachable("Cannot invoke this intrinsic"); 3327 case Intrinsic::donothing: 3328 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3329 case Intrinsic::seh_try_begin: 3330 case Intrinsic::seh_scope_begin: 3331 case Intrinsic::seh_try_end: 3332 case Intrinsic::seh_scope_end: 3333 if (EHPadMBB) 3334 // a block referenced by EH table 3335 // so dtor-funclet not removed by opts 3336 EHPadMBB->setMachineBlockAddressTaken(); 3337 break; 3338 case Intrinsic::experimental_patchpoint_void: 3339 case Intrinsic::experimental_patchpoint: 3340 visitPatchpoint(I, EHPadBB); 3341 break; 3342 case Intrinsic::experimental_gc_statepoint: 3343 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3344 break; 3345 case Intrinsic::wasm_rethrow: { 3346 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3347 // special because it can be invoked, so we manually lower it to a DAG 3348 // node here. 3349 SmallVector<SDValue, 8> Ops; 3350 Ops.push_back(getRoot()); // inchain 3351 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3352 Ops.push_back( 3353 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3354 TLI.getPointerTy(DAG.getDataLayout()))); 3355 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3356 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3357 break; 3358 } 3359 } 3360 } else if (I.hasDeoptState()) { 3361 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3362 // Eventually we will support lowering the @llvm.experimental.deoptimize 3363 // intrinsic, and right now there are no plans to support other intrinsics 3364 // with deopt state. 3365 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3366 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 3367 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB); 3368 } else { 3369 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3370 } 3371 3372 // If the value of the invoke is used outside of its defining block, make it 3373 // available as a virtual register. 3374 // We already took care of the exported value for the statepoint instruction 3375 // during call to the LowerStatepoint. 3376 if (!isa<GCStatepointInst>(I)) { 3377 CopyToExportRegsIfNeeded(&I); 3378 } 3379 3380 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3381 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3382 BranchProbability EHPadBBProb = 3383 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3384 : BranchProbability::getZero(); 3385 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3386 3387 // Update successor info. 3388 addSuccessorWithProb(InvokeMBB, Return); 3389 for (auto &UnwindDest : UnwindDests) { 3390 UnwindDest.first->setIsEHPad(); 3391 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3392 } 3393 InvokeMBB->normalizeSuccProbs(); 3394 3395 // Drop into normal successor. 3396 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3397 DAG.getBasicBlock(Return))); 3398 } 3399 3400 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3401 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3402 3403 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3404 // have to do anything here to lower funclet bundles. 3405 assert(!I.hasOperandBundlesOtherThan( 3406 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3407 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3408 3409 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3410 visitInlineAsm(I); 3411 CopyToExportRegsIfNeeded(&I); 3412 3413 // Retrieve successors. 3414 SmallPtrSet<BasicBlock *, 8> Dests; 3415 Dests.insert(I.getDefaultDest()); 3416 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3417 3418 // Update successor info. 3419 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3420 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3421 BasicBlock *Dest = I.getIndirectDest(i); 3422 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3423 Target->setIsInlineAsmBrIndirectTarget(); 3424 Target->setMachineBlockAddressTaken(); 3425 Target->setLabelMustBeEmitted(); 3426 // Don't add duplicate machine successors. 3427 if (Dests.insert(Dest).second) 3428 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3429 } 3430 CallBrMBB->normalizeSuccProbs(); 3431 3432 // Drop into default successor. 3433 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3434 MVT::Other, getControlRoot(), 3435 DAG.getBasicBlock(Return))); 3436 } 3437 3438 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3439 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3440 } 3441 3442 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3443 assert(FuncInfo.MBB->isEHPad() && 3444 "Call to landingpad not in landing pad!"); 3445 3446 // If there aren't registers to copy the values into (e.g., during SjLj 3447 // exceptions), then don't bother to create these DAG nodes. 3448 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3449 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3450 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3451 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3452 return; 3453 3454 // If landingpad's return type is token type, we don't create DAG nodes 3455 // for its exception pointer and selector value. The extraction of exception 3456 // pointer or selector value from token type landingpads is not currently 3457 // supported. 3458 if (LP.getType()->isTokenTy()) 3459 return; 3460 3461 SmallVector<EVT, 2> ValueVTs; 3462 SDLoc dl = getCurSDLoc(); 3463 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3464 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3465 3466 // Get the two live-in registers as SDValues. The physregs have already been 3467 // copied into virtual registers. 3468 SDValue Ops[2]; 3469 if (FuncInfo.ExceptionPointerVirtReg) { 3470 Ops[0] = DAG.getZExtOrTrunc( 3471 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3472 FuncInfo.ExceptionPointerVirtReg, 3473 TLI.getPointerTy(DAG.getDataLayout())), 3474 dl, ValueVTs[0]); 3475 } else { 3476 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3477 } 3478 Ops[1] = DAG.getZExtOrTrunc( 3479 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3480 FuncInfo.ExceptionSelectorVirtReg, 3481 TLI.getPointerTy(DAG.getDataLayout())), 3482 dl, ValueVTs[1]); 3483 3484 // Merge into one. 3485 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3486 DAG.getVTList(ValueVTs), Ops); 3487 setValue(&LP, Res); 3488 } 3489 3490 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3491 MachineBasicBlock *Last) { 3492 // Update JTCases. 3493 for (JumpTableBlock &JTB : SL->JTCases) 3494 if (JTB.first.HeaderBB == First) 3495 JTB.first.HeaderBB = Last; 3496 3497 // Update BitTestCases. 3498 for (BitTestBlock &BTB : SL->BitTestCases) 3499 if (BTB.Parent == First) 3500 BTB.Parent = Last; 3501 } 3502 3503 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3504 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3505 3506 // Update machine-CFG edges with unique successors. 3507 SmallSet<BasicBlock*, 32> Done; 3508 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3509 BasicBlock *BB = I.getSuccessor(i); 3510 bool Inserted = Done.insert(BB).second; 3511 if (!Inserted) 3512 continue; 3513 3514 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3515 addSuccessorWithProb(IndirectBrMBB, Succ); 3516 } 3517 IndirectBrMBB->normalizeSuccProbs(); 3518 3519 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3520 MVT::Other, getControlRoot(), 3521 getValue(I.getAddress()))); 3522 } 3523 3524 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3525 if (!DAG.getTarget().Options.TrapUnreachable) 3526 return; 3527 3528 // We may be able to ignore unreachable behind a noreturn call. 3529 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3530 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) { 3531 if (Call->doesNotReturn()) 3532 return; 3533 } 3534 } 3535 3536 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3537 } 3538 3539 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3540 SDNodeFlags Flags; 3541 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3542 Flags.copyFMF(*FPOp); 3543 3544 SDValue Op = getValue(I.getOperand(0)); 3545 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3546 Op, Flags); 3547 setValue(&I, UnNodeValue); 3548 } 3549 3550 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3551 SDNodeFlags Flags; 3552 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3553 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3554 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3555 } 3556 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3557 Flags.setExact(ExactOp->isExact()); 3558 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3559 Flags.setDisjoint(DisjointOp->isDisjoint()); 3560 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3561 Flags.copyFMF(*FPOp); 3562 3563 SDValue Op1 = getValue(I.getOperand(0)); 3564 SDValue Op2 = getValue(I.getOperand(1)); 3565 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3566 Op1, Op2, Flags); 3567 setValue(&I, BinNodeValue); 3568 } 3569 3570 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3571 SDValue Op1 = getValue(I.getOperand(0)); 3572 SDValue Op2 = getValue(I.getOperand(1)); 3573 3574 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3575 Op1.getValueType(), DAG.getDataLayout()); 3576 3577 // Coerce the shift amount to the right type if we can. This exposes the 3578 // truncate or zext to optimization early. 3579 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3580 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3581 "Unexpected shift type"); 3582 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3583 } 3584 3585 bool nuw = false; 3586 bool nsw = false; 3587 bool exact = false; 3588 3589 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3590 3591 if (const OverflowingBinaryOperator *OFBinOp = 3592 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3593 nuw = OFBinOp->hasNoUnsignedWrap(); 3594 nsw = OFBinOp->hasNoSignedWrap(); 3595 } 3596 if (const PossiblyExactOperator *ExactOp = 3597 dyn_cast<const PossiblyExactOperator>(&I)) 3598 exact = ExactOp->isExact(); 3599 } 3600 SDNodeFlags Flags; 3601 Flags.setExact(exact); 3602 Flags.setNoSignedWrap(nsw); 3603 Flags.setNoUnsignedWrap(nuw); 3604 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3605 Flags); 3606 setValue(&I, Res); 3607 } 3608 3609 void SelectionDAGBuilder::visitSDiv(const User &I) { 3610 SDValue Op1 = getValue(I.getOperand(0)); 3611 SDValue Op2 = getValue(I.getOperand(1)); 3612 3613 SDNodeFlags Flags; 3614 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3615 cast<PossiblyExactOperator>(&I)->isExact()); 3616 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3617 Op2, Flags)); 3618 } 3619 3620 void SelectionDAGBuilder::visitICmp(const User &I) { 3621 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3622 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3623 predicate = IC->getPredicate(); 3624 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3625 predicate = ICmpInst::Predicate(IC->getPredicate()); 3626 SDValue Op1 = getValue(I.getOperand(0)); 3627 SDValue Op2 = getValue(I.getOperand(1)); 3628 ISD::CondCode Opcode = getICmpCondCode(predicate); 3629 3630 auto &TLI = DAG.getTargetLoweringInfo(); 3631 EVT MemVT = 3632 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3633 3634 // If a pointer's DAG type is larger than its memory type then the DAG values 3635 // are zero-extended. This breaks signed comparisons so truncate back to the 3636 // underlying type before doing the compare. 3637 if (Op1.getValueType() != MemVT) { 3638 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3639 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3640 } 3641 3642 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3643 I.getType()); 3644 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3645 } 3646 3647 void SelectionDAGBuilder::visitFCmp(const User &I) { 3648 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3649 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3650 predicate = FC->getPredicate(); 3651 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3652 predicate = FCmpInst::Predicate(FC->getPredicate()); 3653 SDValue Op1 = getValue(I.getOperand(0)); 3654 SDValue Op2 = getValue(I.getOperand(1)); 3655 3656 ISD::CondCode Condition = getFCmpCondCode(predicate); 3657 auto *FPMO = cast<FPMathOperator>(&I); 3658 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3659 Condition = getFCmpCodeWithoutNaN(Condition); 3660 3661 SDNodeFlags Flags; 3662 Flags.copyFMF(*FPMO); 3663 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3664 3665 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3666 I.getType()); 3667 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3668 } 3669 3670 // Check if the condition of the select has one use or two users that are both 3671 // selects with the same condition. 3672 static bool hasOnlySelectUsers(const Value *Cond) { 3673 return llvm::all_of(Cond->users(), [](const Value *V) { 3674 return isa<SelectInst>(V); 3675 }); 3676 } 3677 3678 void SelectionDAGBuilder::visitSelect(const User &I) { 3679 SmallVector<EVT, 4> ValueVTs; 3680 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3681 ValueVTs); 3682 unsigned NumValues = ValueVTs.size(); 3683 if (NumValues == 0) return; 3684 3685 SmallVector<SDValue, 4> Values(NumValues); 3686 SDValue Cond = getValue(I.getOperand(0)); 3687 SDValue LHSVal = getValue(I.getOperand(1)); 3688 SDValue RHSVal = getValue(I.getOperand(2)); 3689 SmallVector<SDValue, 1> BaseOps(1, Cond); 3690 ISD::NodeType OpCode = 3691 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3692 3693 bool IsUnaryAbs = false; 3694 bool Negate = false; 3695 3696 SDNodeFlags Flags; 3697 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3698 Flags.copyFMF(*FPOp); 3699 3700 Flags.setUnpredictable( 3701 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3702 3703 // Min/max matching is only viable if all output VTs are the same. 3704 if (all_equal(ValueVTs)) { 3705 EVT VT = ValueVTs[0]; 3706 LLVMContext &Ctx = *DAG.getContext(); 3707 auto &TLI = DAG.getTargetLoweringInfo(); 3708 3709 // We care about the legality of the operation after it has been type 3710 // legalized. 3711 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3712 VT = TLI.getTypeToTransformTo(Ctx, VT); 3713 3714 // If the vselect is legal, assume we want to leave this as a vector setcc + 3715 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3716 // min/max is legal on the scalar type. 3717 bool UseScalarMinMax = VT.isVector() && 3718 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3719 3720 // ValueTracking's select pattern matching does not account for -0.0, 3721 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3722 // -0.0 is less than +0.0. 3723 Value *LHS, *RHS; 3724 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3725 ISD::NodeType Opc = ISD::DELETED_NODE; 3726 switch (SPR.Flavor) { 3727 case SPF_UMAX: Opc = ISD::UMAX; break; 3728 case SPF_UMIN: Opc = ISD::UMIN; break; 3729 case SPF_SMAX: Opc = ISD::SMAX; break; 3730 case SPF_SMIN: Opc = ISD::SMIN; break; 3731 case SPF_FMINNUM: 3732 switch (SPR.NaNBehavior) { 3733 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3734 case SPNB_RETURNS_NAN: break; 3735 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3736 case SPNB_RETURNS_ANY: 3737 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3738 (UseScalarMinMax && 3739 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3740 Opc = ISD::FMINNUM; 3741 break; 3742 } 3743 break; 3744 case SPF_FMAXNUM: 3745 switch (SPR.NaNBehavior) { 3746 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3747 case SPNB_RETURNS_NAN: break; 3748 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3749 case SPNB_RETURNS_ANY: 3750 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3751 (UseScalarMinMax && 3752 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3753 Opc = ISD::FMAXNUM; 3754 break; 3755 } 3756 break; 3757 case SPF_NABS: 3758 Negate = true; 3759 [[fallthrough]]; 3760 case SPF_ABS: 3761 IsUnaryAbs = true; 3762 Opc = ISD::ABS; 3763 break; 3764 default: break; 3765 } 3766 3767 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3768 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3769 (UseScalarMinMax && 3770 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3771 // If the underlying comparison instruction is used by any other 3772 // instruction, the consumed instructions won't be destroyed, so it is 3773 // not profitable to convert to a min/max. 3774 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3775 OpCode = Opc; 3776 LHSVal = getValue(LHS); 3777 RHSVal = getValue(RHS); 3778 BaseOps.clear(); 3779 } 3780 3781 if (IsUnaryAbs) { 3782 OpCode = Opc; 3783 LHSVal = getValue(LHS); 3784 BaseOps.clear(); 3785 } 3786 } 3787 3788 if (IsUnaryAbs) { 3789 for (unsigned i = 0; i != NumValues; ++i) { 3790 SDLoc dl = getCurSDLoc(); 3791 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3792 Values[i] = 3793 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3794 if (Negate) 3795 Values[i] = DAG.getNegative(Values[i], dl, VT); 3796 } 3797 } else { 3798 for (unsigned i = 0; i != NumValues; ++i) { 3799 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3800 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3801 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3802 Values[i] = DAG.getNode( 3803 OpCode, getCurSDLoc(), 3804 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3805 } 3806 } 3807 3808 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3809 DAG.getVTList(ValueVTs), Values)); 3810 } 3811 3812 void SelectionDAGBuilder::visitTrunc(const User &I) { 3813 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3814 SDValue N = getValue(I.getOperand(0)); 3815 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3816 I.getType()); 3817 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3818 } 3819 3820 void SelectionDAGBuilder::visitZExt(const User &I) { 3821 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3822 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3823 SDValue N = getValue(I.getOperand(0)); 3824 auto &TLI = DAG.getTargetLoweringInfo(); 3825 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3826 3827 SDNodeFlags Flags; 3828 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3829 Flags.setNonNeg(PNI->hasNonNeg()); 3830 3831 // Eagerly use nonneg information to canonicalize towards sign_extend if 3832 // that is the target's preference. 3833 // TODO: Let the target do this later. 3834 if (Flags.hasNonNeg() && 3835 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3836 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3837 return; 3838 } 3839 3840 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3841 } 3842 3843 void SelectionDAGBuilder::visitSExt(const User &I) { 3844 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3845 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3846 SDValue N = getValue(I.getOperand(0)); 3847 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3848 I.getType()); 3849 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3850 } 3851 3852 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3853 // FPTrunc is never a no-op cast, no need to check 3854 SDValue N = getValue(I.getOperand(0)); 3855 SDLoc dl = getCurSDLoc(); 3856 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3857 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3858 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3859 DAG.getTargetConstant( 3860 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3861 } 3862 3863 void SelectionDAGBuilder::visitFPExt(const User &I) { 3864 // FPExt is never a no-op cast, no need to check 3865 SDValue N = getValue(I.getOperand(0)); 3866 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3867 I.getType()); 3868 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3869 } 3870 3871 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3872 // FPToUI is never a no-op cast, no need to check 3873 SDValue N = getValue(I.getOperand(0)); 3874 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3875 I.getType()); 3876 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3877 } 3878 3879 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3880 // FPToSI is never a no-op cast, no need to check 3881 SDValue N = getValue(I.getOperand(0)); 3882 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3883 I.getType()); 3884 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3885 } 3886 3887 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3888 // UIToFP is never a no-op cast, no need to check 3889 SDValue N = getValue(I.getOperand(0)); 3890 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3891 I.getType()); 3892 SDNodeFlags Flags; 3893 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3894 Flags.setNonNeg(PNI->hasNonNeg()); 3895 3896 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags)); 3897 } 3898 3899 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3900 // SIToFP is never a no-op cast, no need to check 3901 SDValue N = getValue(I.getOperand(0)); 3902 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3903 I.getType()); 3904 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3905 } 3906 3907 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3908 // What to do depends on the size of the integer and the size of the pointer. 3909 // We can either truncate, zero extend, or no-op, accordingly. 3910 SDValue N = getValue(I.getOperand(0)); 3911 auto &TLI = DAG.getTargetLoweringInfo(); 3912 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3913 I.getType()); 3914 EVT PtrMemVT = 3915 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3916 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3917 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3918 setValue(&I, N); 3919 } 3920 3921 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3922 // What to do depends on the size of the integer and the size of the pointer. 3923 // We can either truncate, zero extend, or no-op, accordingly. 3924 SDValue N = getValue(I.getOperand(0)); 3925 auto &TLI = DAG.getTargetLoweringInfo(); 3926 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3927 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3928 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3929 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3930 setValue(&I, N); 3931 } 3932 3933 void SelectionDAGBuilder::visitBitCast(const User &I) { 3934 SDValue N = getValue(I.getOperand(0)); 3935 SDLoc dl = getCurSDLoc(); 3936 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3937 I.getType()); 3938 3939 // BitCast assures us that source and destination are the same size so this is 3940 // either a BITCAST or a no-op. 3941 if (DestVT != N.getValueType()) 3942 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3943 DestVT, N)); // convert types. 3944 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3945 // might fold any kind of constant expression to an integer constant and that 3946 // is not what we are looking for. Only recognize a bitcast of a genuine 3947 // constant integer as an opaque constant. 3948 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3949 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3950 /*isOpaque*/true)); 3951 else 3952 setValue(&I, N); // noop cast. 3953 } 3954 3955 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3956 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3957 const Value *SV = I.getOperand(0); 3958 SDValue N = getValue(SV); 3959 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3960 3961 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3962 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3963 3964 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3965 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3966 3967 setValue(&I, N); 3968 } 3969 3970 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3971 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3972 SDValue InVec = getValue(I.getOperand(0)); 3973 SDValue InVal = getValue(I.getOperand(1)); 3974 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3975 TLI.getVectorIdxTy(DAG.getDataLayout())); 3976 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3977 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3978 InVec, InVal, InIdx)); 3979 } 3980 3981 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3982 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3983 SDValue InVec = getValue(I.getOperand(0)); 3984 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3985 TLI.getVectorIdxTy(DAG.getDataLayout())); 3986 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3987 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3988 InVec, InIdx)); 3989 } 3990 3991 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3992 SDValue Src1 = getValue(I.getOperand(0)); 3993 SDValue Src2 = getValue(I.getOperand(1)); 3994 ArrayRef<int> Mask; 3995 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3996 Mask = SVI->getShuffleMask(); 3997 else 3998 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3999 SDLoc DL = getCurSDLoc(); 4000 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4001 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4002 EVT SrcVT = Src1.getValueType(); 4003 4004 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 4005 VT.isScalableVector()) { 4006 // Canonical splat form of first element of first input vector. 4007 SDValue FirstElt = 4008 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 4009 DAG.getVectorIdxConstant(0, DL)); 4010 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 4011 return; 4012 } 4013 4014 // For now, we only handle splats for scalable vectors. 4015 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 4016 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 4017 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 4018 4019 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 4020 unsigned MaskNumElts = Mask.size(); 4021 4022 if (SrcNumElts == MaskNumElts) { 4023 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 4024 return; 4025 } 4026 4027 // Normalize the shuffle vector since mask and vector length don't match. 4028 if (SrcNumElts < MaskNumElts) { 4029 // Mask is longer than the source vectors. We can use concatenate vector to 4030 // make the mask and vectors lengths match. 4031 4032 if (MaskNumElts % SrcNumElts == 0) { 4033 // Mask length is a multiple of the source vector length. 4034 // Check if the shuffle is some kind of concatenation of the input 4035 // vectors. 4036 unsigned NumConcat = MaskNumElts / SrcNumElts; 4037 bool IsConcat = true; 4038 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 4039 for (unsigned i = 0; i != MaskNumElts; ++i) { 4040 int Idx = Mask[i]; 4041 if (Idx < 0) 4042 continue; 4043 // Ensure the indices in each SrcVT sized piece are sequential and that 4044 // the same source is used for the whole piece. 4045 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 4046 (ConcatSrcs[i / SrcNumElts] >= 0 && 4047 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 4048 IsConcat = false; 4049 break; 4050 } 4051 // Remember which source this index came from. 4052 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 4053 } 4054 4055 // The shuffle is concatenating multiple vectors together. Just emit 4056 // a CONCAT_VECTORS operation. 4057 if (IsConcat) { 4058 SmallVector<SDValue, 8> ConcatOps; 4059 for (auto Src : ConcatSrcs) { 4060 if (Src < 0) 4061 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 4062 else if (Src == 0) 4063 ConcatOps.push_back(Src1); 4064 else 4065 ConcatOps.push_back(Src2); 4066 } 4067 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 4068 return; 4069 } 4070 } 4071 4072 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 4073 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 4074 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 4075 PaddedMaskNumElts); 4076 4077 // Pad both vectors with undefs to make them the same length as the mask. 4078 SDValue UndefVal = DAG.getUNDEF(SrcVT); 4079 4080 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 4081 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 4082 MOps1[0] = Src1; 4083 MOps2[0] = Src2; 4084 4085 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 4086 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 4087 4088 // Readjust mask for new input vector length. 4089 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 4090 for (unsigned i = 0; i != MaskNumElts; ++i) { 4091 int Idx = Mask[i]; 4092 if (Idx >= (int)SrcNumElts) 4093 Idx -= SrcNumElts - PaddedMaskNumElts; 4094 MappedOps[i] = Idx; 4095 } 4096 4097 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 4098 4099 // If the concatenated vector was padded, extract a subvector with the 4100 // correct number of elements. 4101 if (MaskNumElts != PaddedMaskNumElts) 4102 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 4103 DAG.getVectorIdxConstant(0, DL)); 4104 4105 setValue(&I, Result); 4106 return; 4107 } 4108 4109 if (SrcNumElts > MaskNumElts) { 4110 // Analyze the access pattern of the vector to see if we can extract 4111 // two subvectors and do the shuffle. 4112 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 4113 bool CanExtract = true; 4114 for (int Idx : Mask) { 4115 unsigned Input = 0; 4116 if (Idx < 0) 4117 continue; 4118 4119 if (Idx >= (int)SrcNumElts) { 4120 Input = 1; 4121 Idx -= SrcNumElts; 4122 } 4123 4124 // If all the indices come from the same MaskNumElts sized portion of 4125 // the sources we can use extract. Also make sure the extract wouldn't 4126 // extract past the end of the source. 4127 int NewStartIdx = alignDown(Idx, MaskNumElts); 4128 if (NewStartIdx + MaskNumElts > SrcNumElts || 4129 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 4130 CanExtract = false; 4131 // Make sure we always update StartIdx as we use it to track if all 4132 // elements are undef. 4133 StartIdx[Input] = NewStartIdx; 4134 } 4135 4136 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 4137 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 4138 return; 4139 } 4140 if (CanExtract) { 4141 // Extract appropriate subvector and generate a vector shuffle 4142 for (unsigned Input = 0; Input < 2; ++Input) { 4143 SDValue &Src = Input == 0 ? Src1 : Src2; 4144 if (StartIdx[Input] < 0) 4145 Src = DAG.getUNDEF(VT); 4146 else { 4147 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 4148 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 4149 } 4150 } 4151 4152 // Calculate new mask. 4153 SmallVector<int, 8> MappedOps(Mask); 4154 for (int &Idx : MappedOps) { 4155 if (Idx >= (int)SrcNumElts) 4156 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 4157 else if (Idx >= 0) 4158 Idx -= StartIdx[0]; 4159 } 4160 4161 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 4162 return; 4163 } 4164 } 4165 4166 // We can't use either concat vectors or extract subvectors so fall back to 4167 // replacing the shuffle with extract and build vector. 4168 // to insert and build vector. 4169 EVT EltVT = VT.getVectorElementType(); 4170 SmallVector<SDValue,8> Ops; 4171 for (int Idx : Mask) { 4172 SDValue Res; 4173 4174 if (Idx < 0) { 4175 Res = DAG.getUNDEF(EltVT); 4176 } else { 4177 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 4178 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 4179 4180 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4181 DAG.getVectorIdxConstant(Idx, DL)); 4182 } 4183 4184 Ops.push_back(Res); 4185 } 4186 4187 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4188 } 4189 4190 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4191 ArrayRef<unsigned> Indices = I.getIndices(); 4192 const Value *Op0 = I.getOperand(0); 4193 const Value *Op1 = I.getOperand(1); 4194 Type *AggTy = I.getType(); 4195 Type *ValTy = Op1->getType(); 4196 bool IntoUndef = isa<UndefValue>(Op0); 4197 bool FromUndef = isa<UndefValue>(Op1); 4198 4199 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4200 4201 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4202 SmallVector<EVT, 4> AggValueVTs; 4203 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4204 SmallVector<EVT, 4> ValValueVTs; 4205 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4206 4207 unsigned NumAggValues = AggValueVTs.size(); 4208 unsigned NumValValues = ValValueVTs.size(); 4209 SmallVector<SDValue, 4> Values(NumAggValues); 4210 4211 // Ignore an insertvalue that produces an empty object 4212 if (!NumAggValues) { 4213 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4214 return; 4215 } 4216 4217 SDValue Agg = getValue(Op0); 4218 unsigned i = 0; 4219 // Copy the beginning value(s) from the original aggregate. 4220 for (; i != LinearIndex; ++i) 4221 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4222 SDValue(Agg.getNode(), Agg.getResNo() + i); 4223 // Copy values from the inserted value(s). 4224 if (NumValValues) { 4225 SDValue Val = getValue(Op1); 4226 for (; i != LinearIndex + NumValValues; ++i) 4227 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4228 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4229 } 4230 // Copy remaining value(s) from the original aggregate. 4231 for (; i != NumAggValues; ++i) 4232 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4233 SDValue(Agg.getNode(), Agg.getResNo() + i); 4234 4235 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4236 DAG.getVTList(AggValueVTs), Values)); 4237 } 4238 4239 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4240 ArrayRef<unsigned> Indices = I.getIndices(); 4241 const Value *Op0 = I.getOperand(0); 4242 Type *AggTy = Op0->getType(); 4243 Type *ValTy = I.getType(); 4244 bool OutOfUndef = isa<UndefValue>(Op0); 4245 4246 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4247 4248 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4249 SmallVector<EVT, 4> ValValueVTs; 4250 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4251 4252 unsigned NumValValues = ValValueVTs.size(); 4253 4254 // Ignore a extractvalue that produces an empty object 4255 if (!NumValValues) { 4256 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4257 return; 4258 } 4259 4260 SmallVector<SDValue, 4> Values(NumValValues); 4261 4262 SDValue Agg = getValue(Op0); 4263 // Copy out the selected value(s). 4264 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4265 Values[i - LinearIndex] = 4266 OutOfUndef ? 4267 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4268 SDValue(Agg.getNode(), Agg.getResNo() + i); 4269 4270 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4271 DAG.getVTList(ValValueVTs), Values)); 4272 } 4273 4274 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4275 Value *Op0 = I.getOperand(0); 4276 // Note that the pointer operand may be a vector of pointers. Take the scalar 4277 // element which holds a pointer. 4278 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4279 SDValue N = getValue(Op0); 4280 SDLoc dl = getCurSDLoc(); 4281 auto &TLI = DAG.getTargetLoweringInfo(); 4282 4283 // Normalize Vector GEP - all scalar operands should be converted to the 4284 // splat vector. 4285 bool IsVectorGEP = I.getType()->isVectorTy(); 4286 ElementCount VectorElementCount = 4287 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4288 : ElementCount::getFixed(0); 4289 4290 if (IsVectorGEP && !N.getValueType().isVector()) { 4291 LLVMContext &Context = *DAG.getContext(); 4292 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4293 N = DAG.getSplat(VT, dl, N); 4294 } 4295 4296 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4297 GTI != E; ++GTI) { 4298 const Value *Idx = GTI.getOperand(); 4299 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4300 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4301 if (Field) { 4302 // N = N + Offset 4303 uint64_t Offset = 4304 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4305 4306 // In an inbounds GEP with an offset that is nonnegative even when 4307 // interpreted as signed, assume there is no unsigned overflow. 4308 SDNodeFlags Flags; 4309 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 4310 Flags.setNoUnsignedWrap(true); 4311 4312 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4313 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4314 } 4315 } else { 4316 // IdxSize is the width of the arithmetic according to IR semantics. 4317 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4318 // (and fix up the result later). 4319 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4320 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4321 TypeSize ElementSize = 4322 GTI.getSequentialElementStride(DAG.getDataLayout()); 4323 // We intentionally mask away the high bits here; ElementSize may not 4324 // fit in IdxTy. 4325 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4326 bool ElementScalable = ElementSize.isScalable(); 4327 4328 // If this is a scalar constant or a splat vector of constants, 4329 // handle it quickly. 4330 const auto *C = dyn_cast<Constant>(Idx); 4331 if (C && isa<VectorType>(C->getType())) 4332 C = C->getSplatValue(); 4333 4334 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4335 if (CI && CI->isZero()) 4336 continue; 4337 if (CI && !ElementScalable) { 4338 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4339 LLVMContext &Context = *DAG.getContext(); 4340 SDValue OffsVal; 4341 if (IsVectorGEP) 4342 OffsVal = DAG.getConstant( 4343 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4344 else 4345 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4346 4347 // In an inbounds GEP with an offset that is nonnegative even when 4348 // interpreted as signed, assume there is no unsigned overflow. 4349 SDNodeFlags Flags; 4350 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4351 Flags.setNoUnsignedWrap(true); 4352 4353 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4354 4355 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4356 continue; 4357 } 4358 4359 // N = N + Idx * ElementMul; 4360 SDValue IdxN = getValue(Idx); 4361 4362 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4363 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4364 VectorElementCount); 4365 IdxN = DAG.getSplat(VT, dl, IdxN); 4366 } 4367 4368 // If the index is smaller or larger than intptr_t, truncate or extend 4369 // it. 4370 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4371 4372 if (ElementScalable) { 4373 EVT VScaleTy = N.getValueType().getScalarType(); 4374 SDValue VScale = DAG.getNode( 4375 ISD::VSCALE, dl, VScaleTy, 4376 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4377 if (IsVectorGEP) 4378 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4379 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4380 } else { 4381 // If this is a multiply by a power of two, turn it into a shl 4382 // immediately. This is a very common case. 4383 if (ElementMul != 1) { 4384 if (ElementMul.isPowerOf2()) { 4385 unsigned Amt = ElementMul.logBase2(); 4386 IdxN = DAG.getNode(ISD::SHL, dl, 4387 N.getValueType(), IdxN, 4388 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4389 } else { 4390 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4391 IdxN.getValueType()); 4392 IdxN = DAG.getNode(ISD::MUL, dl, 4393 N.getValueType(), IdxN, Scale); 4394 } 4395 } 4396 } 4397 4398 N = DAG.getNode(ISD::ADD, dl, 4399 N.getValueType(), N, IdxN); 4400 } 4401 } 4402 4403 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4404 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4405 if (IsVectorGEP) { 4406 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4407 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4408 } 4409 4410 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4411 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4412 4413 setValue(&I, N); 4414 } 4415 4416 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4417 // If this is a fixed sized alloca in the entry block of the function, 4418 // allocate it statically on the stack. 4419 if (FuncInfo.StaticAllocaMap.count(&I)) 4420 return; // getValue will auto-populate this. 4421 4422 SDLoc dl = getCurSDLoc(); 4423 Type *Ty = I.getAllocatedType(); 4424 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4425 auto &DL = DAG.getDataLayout(); 4426 TypeSize TySize = DL.getTypeAllocSize(Ty); 4427 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4428 4429 SDValue AllocSize = getValue(I.getArraySize()); 4430 4431 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4432 if (AllocSize.getValueType() != IntPtr) 4433 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4434 4435 if (TySize.isScalable()) 4436 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4437 DAG.getVScale(dl, IntPtr, 4438 APInt(IntPtr.getScalarSizeInBits(), 4439 TySize.getKnownMinValue()))); 4440 else { 4441 SDValue TySizeValue = 4442 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4443 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4444 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4445 } 4446 4447 // Handle alignment. If the requested alignment is less than or equal to 4448 // the stack alignment, ignore it. If the size is greater than or equal to 4449 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4450 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4451 if (*Alignment <= StackAlign) 4452 Alignment = std::nullopt; 4453 4454 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4455 // Round the size of the allocation up to the stack alignment size 4456 // by add SA-1 to the size. This doesn't overflow because we're computing 4457 // an address inside an alloca. 4458 SDNodeFlags Flags; 4459 Flags.setNoUnsignedWrap(true); 4460 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4461 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4462 4463 // Mask out the low bits for alignment purposes. 4464 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4465 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4466 4467 SDValue Ops[] = { 4468 getRoot(), AllocSize, 4469 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4470 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4471 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4472 setValue(&I, DSA); 4473 DAG.setRoot(DSA.getValue(1)); 4474 4475 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4476 } 4477 4478 static const MDNode *getRangeMetadata(const Instruction &I) { 4479 // If !noundef is not present, then !range violation results in a poison 4480 // value rather than immediate undefined behavior. In theory, transferring 4481 // these annotations to SDAG is fine, but in practice there are key SDAG 4482 // transforms that are known not to be poison-safe, such as folding logical 4483 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4484 // also present. 4485 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4486 return nullptr; 4487 return I.getMetadata(LLVMContext::MD_range); 4488 } 4489 4490 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4491 if (I.isAtomic()) 4492 return visitAtomicLoad(I); 4493 4494 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4495 const Value *SV = I.getOperand(0); 4496 if (TLI.supportSwiftError()) { 4497 // Swifterror values can come from either a function parameter with 4498 // swifterror attribute or an alloca with swifterror attribute. 4499 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4500 if (Arg->hasSwiftErrorAttr()) 4501 return visitLoadFromSwiftError(I); 4502 } 4503 4504 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4505 if (Alloca->isSwiftError()) 4506 return visitLoadFromSwiftError(I); 4507 } 4508 } 4509 4510 SDValue Ptr = getValue(SV); 4511 4512 Type *Ty = I.getType(); 4513 SmallVector<EVT, 4> ValueVTs, MemVTs; 4514 SmallVector<TypeSize, 4> Offsets; 4515 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4516 unsigned NumValues = ValueVTs.size(); 4517 if (NumValues == 0) 4518 return; 4519 4520 Align Alignment = I.getAlign(); 4521 AAMDNodes AAInfo = I.getAAMetadata(); 4522 const MDNode *Ranges = getRangeMetadata(I); 4523 bool isVolatile = I.isVolatile(); 4524 MachineMemOperand::Flags MMOFlags = 4525 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4526 4527 SDValue Root; 4528 bool ConstantMemory = false; 4529 if (isVolatile) 4530 // Serialize volatile loads with other side effects. 4531 Root = getRoot(); 4532 else if (NumValues > MaxParallelChains) 4533 Root = getMemoryRoot(); 4534 else if (AA && 4535 AA->pointsToConstantMemory(MemoryLocation( 4536 SV, 4537 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4538 AAInfo))) { 4539 // Do not serialize (non-volatile) loads of constant memory with anything. 4540 Root = DAG.getEntryNode(); 4541 ConstantMemory = true; 4542 MMOFlags |= MachineMemOperand::MOInvariant; 4543 } else { 4544 // Do not serialize non-volatile loads against each other. 4545 Root = DAG.getRoot(); 4546 } 4547 4548 SDLoc dl = getCurSDLoc(); 4549 4550 if (isVolatile) 4551 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4552 4553 SmallVector<SDValue, 4> Values(NumValues); 4554 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4555 4556 unsigned ChainI = 0; 4557 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4558 // Serializing loads here may result in excessive register pressure, and 4559 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4560 // could recover a bit by hoisting nodes upward in the chain by recognizing 4561 // they are side-effect free or do not alias. The optimizer should really 4562 // avoid this case by converting large object/array copies to llvm.memcpy 4563 // (MaxParallelChains should always remain as failsafe). 4564 if (ChainI == MaxParallelChains) { 4565 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4566 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4567 ArrayRef(Chains.data(), ChainI)); 4568 Root = Chain; 4569 ChainI = 0; 4570 } 4571 4572 // TODO: MachinePointerInfo only supports a fixed length offset. 4573 MachinePointerInfo PtrInfo = 4574 !Offsets[i].isScalable() || Offsets[i].isZero() 4575 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4576 : MachinePointerInfo(); 4577 4578 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4579 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4580 MMOFlags, AAInfo, Ranges); 4581 Chains[ChainI] = L.getValue(1); 4582 4583 if (MemVTs[i] != ValueVTs[i]) 4584 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4585 4586 Values[i] = L; 4587 } 4588 4589 if (!ConstantMemory) { 4590 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4591 ArrayRef(Chains.data(), ChainI)); 4592 if (isVolatile) 4593 DAG.setRoot(Chain); 4594 else 4595 PendingLoads.push_back(Chain); 4596 } 4597 4598 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4599 DAG.getVTList(ValueVTs), Values)); 4600 } 4601 4602 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4603 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4604 "call visitStoreToSwiftError when backend supports swifterror"); 4605 4606 SmallVector<EVT, 4> ValueVTs; 4607 SmallVector<uint64_t, 4> Offsets; 4608 const Value *SrcV = I.getOperand(0); 4609 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4610 SrcV->getType(), ValueVTs, &Offsets, 0); 4611 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4612 "expect a single EVT for swifterror"); 4613 4614 SDValue Src = getValue(SrcV); 4615 // Create a virtual register, then update the virtual register. 4616 Register VReg = 4617 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4618 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4619 // Chain can be getRoot or getControlRoot. 4620 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4621 SDValue(Src.getNode(), Src.getResNo())); 4622 DAG.setRoot(CopyNode); 4623 } 4624 4625 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4626 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4627 "call visitLoadFromSwiftError when backend supports swifterror"); 4628 4629 assert(!I.isVolatile() && 4630 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4631 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4632 "Support volatile, non temporal, invariant for load_from_swift_error"); 4633 4634 const Value *SV = I.getOperand(0); 4635 Type *Ty = I.getType(); 4636 assert( 4637 (!AA || 4638 !AA->pointsToConstantMemory(MemoryLocation( 4639 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4640 I.getAAMetadata()))) && 4641 "load_from_swift_error should not be constant memory"); 4642 4643 SmallVector<EVT, 4> ValueVTs; 4644 SmallVector<uint64_t, 4> Offsets; 4645 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4646 ValueVTs, &Offsets, 0); 4647 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4648 "expect a single EVT for swifterror"); 4649 4650 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4651 SDValue L = DAG.getCopyFromReg( 4652 getRoot(), getCurSDLoc(), 4653 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4654 4655 setValue(&I, L); 4656 } 4657 4658 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4659 if (I.isAtomic()) 4660 return visitAtomicStore(I); 4661 4662 const Value *SrcV = I.getOperand(0); 4663 const Value *PtrV = I.getOperand(1); 4664 4665 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4666 if (TLI.supportSwiftError()) { 4667 // Swifterror values can come from either a function parameter with 4668 // swifterror attribute or an alloca with swifterror attribute. 4669 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4670 if (Arg->hasSwiftErrorAttr()) 4671 return visitStoreToSwiftError(I); 4672 } 4673 4674 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4675 if (Alloca->isSwiftError()) 4676 return visitStoreToSwiftError(I); 4677 } 4678 } 4679 4680 SmallVector<EVT, 4> ValueVTs, MemVTs; 4681 SmallVector<TypeSize, 4> Offsets; 4682 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4683 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4684 unsigned NumValues = ValueVTs.size(); 4685 if (NumValues == 0) 4686 return; 4687 4688 // Get the lowered operands. Note that we do this after 4689 // checking if NumResults is zero, because with zero results 4690 // the operands won't have values in the map. 4691 SDValue Src = getValue(SrcV); 4692 SDValue Ptr = getValue(PtrV); 4693 4694 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4695 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4696 SDLoc dl = getCurSDLoc(); 4697 Align Alignment = I.getAlign(); 4698 AAMDNodes AAInfo = I.getAAMetadata(); 4699 4700 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4701 4702 unsigned ChainI = 0; 4703 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4704 // See visitLoad comments. 4705 if (ChainI == MaxParallelChains) { 4706 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4707 ArrayRef(Chains.data(), ChainI)); 4708 Root = Chain; 4709 ChainI = 0; 4710 } 4711 4712 // TODO: MachinePointerInfo only supports a fixed length offset. 4713 MachinePointerInfo PtrInfo = 4714 !Offsets[i].isScalable() || Offsets[i].isZero() 4715 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4716 : MachinePointerInfo(); 4717 4718 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4719 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4720 if (MemVTs[i] != ValueVTs[i]) 4721 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4722 SDValue St = 4723 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4724 Chains[ChainI] = St; 4725 } 4726 4727 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4728 ArrayRef(Chains.data(), ChainI)); 4729 setValue(&I, StoreNode); 4730 DAG.setRoot(StoreNode); 4731 } 4732 4733 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4734 bool IsCompressing) { 4735 SDLoc sdl = getCurSDLoc(); 4736 4737 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4738 Align &Alignment) { 4739 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4740 Src0 = I.getArgOperand(0); 4741 Ptr = I.getArgOperand(1); 4742 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue(); 4743 Mask = I.getArgOperand(3); 4744 }; 4745 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4746 Align &Alignment) { 4747 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4748 Src0 = I.getArgOperand(0); 4749 Ptr = I.getArgOperand(1); 4750 Mask = I.getArgOperand(2); 4751 Alignment = I.getParamAlign(1).valueOrOne(); 4752 }; 4753 4754 Value *PtrOperand, *MaskOperand, *Src0Operand; 4755 Align Alignment; 4756 if (IsCompressing) 4757 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4758 else 4759 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4760 4761 SDValue Ptr = getValue(PtrOperand); 4762 SDValue Src0 = getValue(Src0Operand); 4763 SDValue Mask = getValue(MaskOperand); 4764 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4765 4766 EVT VT = Src0.getValueType(); 4767 4768 auto MMOFlags = MachineMemOperand::MOStore; 4769 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4770 MMOFlags |= MachineMemOperand::MONonTemporal; 4771 4772 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4773 MachinePointerInfo(PtrOperand), MMOFlags, 4774 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4775 SDValue StoreNode = 4776 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4777 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4778 DAG.setRoot(StoreNode); 4779 setValue(&I, StoreNode); 4780 } 4781 4782 // Get a uniform base for the Gather/Scatter intrinsic. 4783 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4784 // We try to represent it as a base pointer + vector of indices. 4785 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4786 // The first operand of the GEP may be a single pointer or a vector of pointers 4787 // Example: 4788 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4789 // or 4790 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4791 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4792 // 4793 // When the first GEP operand is a single pointer - it is the uniform base we 4794 // are looking for. If first operand of the GEP is a splat vector - we 4795 // extract the splat value and use it as a uniform base. 4796 // In all other cases the function returns 'false'. 4797 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4798 ISD::MemIndexType &IndexType, SDValue &Scale, 4799 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4800 uint64_t ElemSize) { 4801 SelectionDAG& DAG = SDB->DAG; 4802 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4803 const DataLayout &DL = DAG.getDataLayout(); 4804 4805 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4806 4807 // Handle splat constant pointer. 4808 if (auto *C = dyn_cast<Constant>(Ptr)) { 4809 C = C->getSplatValue(); 4810 if (!C) 4811 return false; 4812 4813 Base = SDB->getValue(C); 4814 4815 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4816 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4817 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4818 IndexType = ISD::SIGNED_SCALED; 4819 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4820 return true; 4821 } 4822 4823 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4824 if (!GEP || GEP->getParent() != CurBB) 4825 return false; 4826 4827 if (GEP->getNumOperands() != 2) 4828 return false; 4829 4830 const Value *BasePtr = GEP->getPointerOperand(); 4831 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4832 4833 // Make sure the base is scalar and the index is a vector. 4834 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4835 return false; 4836 4837 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4838 if (ScaleVal.isScalable()) 4839 return false; 4840 4841 // Target may not support the required addressing mode. 4842 if (ScaleVal != 1 && 4843 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4844 return false; 4845 4846 Base = SDB->getValue(BasePtr); 4847 Index = SDB->getValue(IndexVal); 4848 IndexType = ISD::SIGNED_SCALED; 4849 4850 Scale = 4851 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4852 return true; 4853 } 4854 4855 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4856 SDLoc sdl = getCurSDLoc(); 4857 4858 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4859 const Value *Ptr = I.getArgOperand(1); 4860 SDValue Src0 = getValue(I.getArgOperand(0)); 4861 SDValue Mask = getValue(I.getArgOperand(3)); 4862 EVT VT = Src0.getValueType(); 4863 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4864 ->getMaybeAlignValue() 4865 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4866 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4867 4868 SDValue Base; 4869 SDValue Index; 4870 ISD::MemIndexType IndexType; 4871 SDValue Scale; 4872 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4873 I.getParent(), VT.getScalarStoreSize()); 4874 4875 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4876 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4877 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4878 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4879 if (!UniformBase) { 4880 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4881 Index = getValue(Ptr); 4882 IndexType = ISD::SIGNED_SCALED; 4883 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4884 } 4885 4886 EVT IdxVT = Index.getValueType(); 4887 EVT EltTy = IdxVT.getVectorElementType(); 4888 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4889 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4890 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4891 } 4892 4893 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4894 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4895 Ops, MMO, IndexType, false); 4896 DAG.setRoot(Scatter); 4897 setValue(&I, Scatter); 4898 } 4899 4900 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4901 SDLoc sdl = getCurSDLoc(); 4902 4903 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4904 Align &Alignment) { 4905 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4906 Ptr = I.getArgOperand(0); 4907 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue(); 4908 Mask = I.getArgOperand(2); 4909 Src0 = I.getArgOperand(3); 4910 }; 4911 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4912 Align &Alignment) { 4913 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4914 Ptr = I.getArgOperand(0); 4915 Alignment = I.getParamAlign(0).valueOrOne(); 4916 Mask = I.getArgOperand(1); 4917 Src0 = I.getArgOperand(2); 4918 }; 4919 4920 Value *PtrOperand, *MaskOperand, *Src0Operand; 4921 Align Alignment; 4922 if (IsExpanding) 4923 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4924 else 4925 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4926 4927 SDValue Ptr = getValue(PtrOperand); 4928 SDValue Src0 = getValue(Src0Operand); 4929 SDValue Mask = getValue(MaskOperand); 4930 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4931 4932 EVT VT = Src0.getValueType(); 4933 AAMDNodes AAInfo = I.getAAMetadata(); 4934 const MDNode *Ranges = getRangeMetadata(I); 4935 4936 // Do not serialize masked loads of constant memory with anything. 4937 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4938 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4939 4940 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4941 4942 auto MMOFlags = MachineMemOperand::MOLoad; 4943 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4944 MMOFlags |= MachineMemOperand::MONonTemporal; 4945 4946 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4947 MachinePointerInfo(PtrOperand), MMOFlags, 4948 LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges); 4949 4950 SDValue Load = 4951 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4952 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4953 if (AddToChain) 4954 PendingLoads.push_back(Load.getValue(1)); 4955 setValue(&I, Load); 4956 } 4957 4958 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4959 SDLoc sdl = getCurSDLoc(); 4960 4961 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4962 const Value *Ptr = I.getArgOperand(0); 4963 SDValue Src0 = getValue(I.getArgOperand(3)); 4964 SDValue Mask = getValue(I.getArgOperand(2)); 4965 4966 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4967 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4968 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4969 ->getMaybeAlignValue() 4970 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4971 4972 const MDNode *Ranges = getRangeMetadata(I); 4973 4974 SDValue Root = DAG.getRoot(); 4975 SDValue Base; 4976 SDValue Index; 4977 ISD::MemIndexType IndexType; 4978 SDValue Scale; 4979 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4980 I.getParent(), VT.getScalarStoreSize()); 4981 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4982 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4983 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4984 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(), 4985 Ranges); 4986 4987 if (!UniformBase) { 4988 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4989 Index = getValue(Ptr); 4990 IndexType = ISD::SIGNED_SCALED; 4991 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4992 } 4993 4994 EVT IdxVT = Index.getValueType(); 4995 EVT EltTy = IdxVT.getVectorElementType(); 4996 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4997 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4998 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4999 } 5000 5001 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 5002 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 5003 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 5004 5005 PendingLoads.push_back(Gather.getValue(1)); 5006 setValue(&I, Gather); 5007 } 5008 5009 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 5010 SDLoc dl = getCurSDLoc(); 5011 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 5012 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 5013 SyncScope::ID SSID = I.getSyncScopeID(); 5014 5015 SDValue InChain = getRoot(); 5016 5017 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 5018 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 5019 5020 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5021 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5022 5023 MachineFunction &MF = DAG.getMachineFunction(); 5024 MachineMemOperand *MMO = MF.getMachineMemOperand( 5025 MachinePointerInfo(I.getPointerOperand()), Flags, 5026 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5027 AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering); 5028 5029 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 5030 dl, MemVT, VTs, InChain, 5031 getValue(I.getPointerOperand()), 5032 getValue(I.getCompareOperand()), 5033 getValue(I.getNewValOperand()), MMO); 5034 5035 SDValue OutChain = L.getValue(2); 5036 5037 setValue(&I, L); 5038 DAG.setRoot(OutChain); 5039 } 5040 5041 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 5042 SDLoc dl = getCurSDLoc(); 5043 ISD::NodeType NT; 5044 switch (I.getOperation()) { 5045 default: llvm_unreachable("Unknown atomicrmw operation"); 5046 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 5047 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 5048 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 5049 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 5050 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 5051 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 5052 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 5053 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 5054 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 5055 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 5056 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 5057 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 5058 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 5059 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 5060 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 5061 case AtomicRMWInst::UIncWrap: 5062 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 5063 break; 5064 case AtomicRMWInst::UDecWrap: 5065 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 5066 break; 5067 } 5068 AtomicOrdering Ordering = I.getOrdering(); 5069 SyncScope::ID SSID = I.getSyncScopeID(); 5070 5071 SDValue InChain = getRoot(); 5072 5073 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 5074 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5075 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5076 5077 MachineFunction &MF = DAG.getMachineFunction(); 5078 MachineMemOperand *MMO = MF.getMachineMemOperand( 5079 MachinePointerInfo(I.getPointerOperand()), Flags, 5080 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5081 AAMDNodes(), nullptr, SSID, Ordering); 5082 5083 SDValue L = 5084 DAG.getAtomic(NT, dl, MemVT, InChain, 5085 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 5086 MMO); 5087 5088 SDValue OutChain = L.getValue(1); 5089 5090 setValue(&I, L); 5091 DAG.setRoot(OutChain); 5092 } 5093 5094 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 5095 SDLoc dl = getCurSDLoc(); 5096 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5097 SDValue Ops[3]; 5098 Ops[0] = getRoot(); 5099 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 5100 TLI.getFenceOperandTy(DAG.getDataLayout())); 5101 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 5102 TLI.getFenceOperandTy(DAG.getDataLayout())); 5103 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 5104 setValue(&I, N); 5105 DAG.setRoot(N); 5106 } 5107 5108 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 5109 SDLoc dl = getCurSDLoc(); 5110 AtomicOrdering Order = I.getOrdering(); 5111 SyncScope::ID SSID = I.getSyncScopeID(); 5112 5113 SDValue InChain = getRoot(); 5114 5115 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5116 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5117 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 5118 5119 if (!TLI.supportsUnalignedAtomics() && 5120 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5121 report_fatal_error("Cannot generate unaligned atomic load"); 5122 5123 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 5124 5125 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5126 MachinePointerInfo(I.getPointerOperand()), Flags, 5127 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5128 nullptr, SSID, Order); 5129 5130 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 5131 5132 SDValue Ptr = getValue(I.getPointerOperand()); 5133 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 5134 Ptr, MMO); 5135 5136 SDValue OutChain = L.getValue(1); 5137 if (MemVT != VT) 5138 L = DAG.getPtrExtOrTrunc(L, dl, VT); 5139 5140 setValue(&I, L); 5141 DAG.setRoot(OutChain); 5142 } 5143 5144 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 5145 SDLoc dl = getCurSDLoc(); 5146 5147 AtomicOrdering Ordering = I.getOrdering(); 5148 SyncScope::ID SSID = I.getSyncScopeID(); 5149 5150 SDValue InChain = getRoot(); 5151 5152 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5153 EVT MemVT = 5154 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 5155 5156 if (!TLI.supportsUnalignedAtomics() && 5157 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5158 report_fatal_error("Cannot generate unaligned atomic store"); 5159 5160 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 5161 5162 MachineFunction &MF = DAG.getMachineFunction(); 5163 MachineMemOperand *MMO = MF.getMachineMemOperand( 5164 MachinePointerInfo(I.getPointerOperand()), Flags, 5165 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5166 nullptr, SSID, Ordering); 5167 5168 SDValue Val = getValue(I.getValueOperand()); 5169 if (Val.getValueType() != MemVT) 5170 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 5171 SDValue Ptr = getValue(I.getPointerOperand()); 5172 5173 SDValue OutChain = 5174 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 5175 5176 setValue(&I, OutChain); 5177 DAG.setRoot(OutChain); 5178 } 5179 5180 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 5181 /// node. 5182 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5183 unsigned Intrinsic) { 5184 // Ignore the callsite's attributes. A specific call site may be marked with 5185 // readnone, but the lowering code will expect the chain based on the 5186 // definition. 5187 const Function *F = I.getCalledFunction(); 5188 bool HasChain = !F->doesNotAccessMemory(); 5189 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 5190 5191 // Build the operand list. 5192 SmallVector<SDValue, 8> Ops; 5193 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5194 if (OnlyLoad) { 5195 // We don't need to serialize loads against other loads. 5196 Ops.push_back(DAG.getRoot()); 5197 } else { 5198 Ops.push_back(getRoot()); 5199 } 5200 } 5201 5202 // Info is set by getTgtMemIntrinsic 5203 TargetLowering::IntrinsicInfo Info; 5204 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5205 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5206 DAG.getMachineFunction(), 5207 Intrinsic); 5208 5209 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5210 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5211 Info.opc == ISD::INTRINSIC_W_CHAIN) 5212 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5213 TLI.getPointerTy(DAG.getDataLayout()))); 5214 5215 // Add all operands of the call to the operand list. 5216 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5217 const Value *Arg = I.getArgOperand(i); 5218 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5219 Ops.push_back(getValue(Arg)); 5220 continue; 5221 } 5222 5223 // Use TargetConstant instead of a regular constant for immarg. 5224 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5225 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5226 assert(CI->getBitWidth() <= 64 && 5227 "large intrinsic immediates not handled"); 5228 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5229 } else { 5230 Ops.push_back( 5231 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5232 } 5233 } 5234 5235 SmallVector<EVT, 4> ValueVTs; 5236 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5237 5238 if (HasChain) 5239 ValueVTs.push_back(MVT::Other); 5240 5241 SDVTList VTs = DAG.getVTList(ValueVTs); 5242 5243 // Propagate fast-math-flags from IR to node(s). 5244 SDNodeFlags Flags; 5245 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5246 Flags.copyFMF(*FPMO); 5247 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5248 5249 // Create the node. 5250 SDValue Result; 5251 5252 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) { 5253 auto *Token = Bundle->Inputs[0].get(); 5254 SDValue ConvControlToken = getValue(Token); 5255 assert(Ops.back().getValueType() != MVT::Glue && 5256 "Did not expected another glue node here."); 5257 ConvControlToken = 5258 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken); 5259 Ops.push_back(ConvControlToken); 5260 } 5261 5262 // In some cases, custom collection of operands from CallInst I may be needed. 5263 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5264 if (IsTgtIntrinsic) { 5265 // This is target intrinsic that touches memory 5266 // 5267 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5268 // didn't yield anything useful. 5269 MachinePointerInfo MPI; 5270 if (Info.ptrVal) 5271 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5272 else if (Info.fallbackAddressSpace) 5273 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5274 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5275 Info.memVT, MPI, Info.align, Info.flags, 5276 Info.size, I.getAAMetadata()); 5277 } else if (!HasChain) { 5278 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5279 } else if (!I.getType()->isVoidTy()) { 5280 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5281 } else { 5282 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5283 } 5284 5285 if (HasChain) { 5286 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5287 if (OnlyLoad) 5288 PendingLoads.push_back(Chain); 5289 else 5290 DAG.setRoot(Chain); 5291 } 5292 5293 if (!I.getType()->isVoidTy()) { 5294 if (!isa<VectorType>(I.getType())) 5295 Result = lowerRangeToAssertZExt(DAG, I, Result); 5296 5297 MaybeAlign Alignment = I.getRetAlign(); 5298 5299 // Insert `assertalign` node if there's an alignment. 5300 if (InsertAssertAlign && Alignment) { 5301 Result = 5302 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5303 } 5304 } 5305 5306 setValue(&I, Result); 5307 } 5308 5309 /// GetSignificand - Get the significand and build it into a floating-point 5310 /// number with exponent of 1: 5311 /// 5312 /// Op = (Op & 0x007fffff) | 0x3f800000; 5313 /// 5314 /// where Op is the hexadecimal representation of floating point value. 5315 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5316 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5317 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5318 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5319 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5320 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5321 } 5322 5323 /// GetExponent - Get the exponent: 5324 /// 5325 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5326 /// 5327 /// where Op is the hexadecimal representation of floating point value. 5328 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5329 const TargetLowering &TLI, const SDLoc &dl) { 5330 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5331 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5332 SDValue t1 = DAG.getNode( 5333 ISD::SRL, dl, MVT::i32, t0, 5334 DAG.getConstant(23, dl, 5335 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5336 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5337 DAG.getConstant(127, dl, MVT::i32)); 5338 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5339 } 5340 5341 /// getF32Constant - Get 32-bit floating point constant. 5342 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5343 const SDLoc &dl) { 5344 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5345 MVT::f32); 5346 } 5347 5348 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5349 SelectionDAG &DAG) { 5350 // TODO: What fast-math-flags should be set on the floating-point nodes? 5351 5352 // IntegerPartOfX = ((int32_t)(t0); 5353 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5354 5355 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5356 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5357 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5358 5359 // IntegerPartOfX <<= 23; 5360 IntegerPartOfX = 5361 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5362 DAG.getConstant(23, dl, 5363 DAG.getTargetLoweringInfo().getShiftAmountTy( 5364 MVT::i32, DAG.getDataLayout()))); 5365 5366 SDValue TwoToFractionalPartOfX; 5367 if (LimitFloatPrecision <= 6) { 5368 // For floating-point precision of 6: 5369 // 5370 // TwoToFractionalPartOfX = 5371 // 0.997535578f + 5372 // (0.735607626f + 0.252464424f * x) * x; 5373 // 5374 // error 0.0144103317, which is 6 bits 5375 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5376 getF32Constant(DAG, 0x3e814304, dl)); 5377 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5378 getF32Constant(DAG, 0x3f3c50c8, dl)); 5379 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5380 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5381 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5382 } else if (LimitFloatPrecision <= 12) { 5383 // For floating-point precision of 12: 5384 // 5385 // TwoToFractionalPartOfX = 5386 // 0.999892986f + 5387 // (0.696457318f + 5388 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5389 // 5390 // error 0.000107046256, which is 13 to 14 bits 5391 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5392 getF32Constant(DAG, 0x3da235e3, dl)); 5393 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5394 getF32Constant(DAG, 0x3e65b8f3, dl)); 5395 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5396 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5397 getF32Constant(DAG, 0x3f324b07, dl)); 5398 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5399 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5400 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5401 } else { // LimitFloatPrecision <= 18 5402 // For floating-point precision of 18: 5403 // 5404 // TwoToFractionalPartOfX = 5405 // 0.999999982f + 5406 // (0.693148872f + 5407 // (0.240227044f + 5408 // (0.554906021e-1f + 5409 // (0.961591928e-2f + 5410 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5411 // error 2.47208000*10^(-7), which is better than 18 bits 5412 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5413 getF32Constant(DAG, 0x3924b03e, dl)); 5414 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5415 getF32Constant(DAG, 0x3ab24b87, dl)); 5416 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5417 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5418 getF32Constant(DAG, 0x3c1d8c17, dl)); 5419 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5420 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5421 getF32Constant(DAG, 0x3d634a1d, dl)); 5422 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5423 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5424 getF32Constant(DAG, 0x3e75fe14, dl)); 5425 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5426 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5427 getF32Constant(DAG, 0x3f317234, dl)); 5428 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5429 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5430 getF32Constant(DAG, 0x3f800000, dl)); 5431 } 5432 5433 // Add the exponent into the result in integer domain. 5434 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5435 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5436 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5437 } 5438 5439 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5440 /// limited-precision mode. 5441 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5442 const TargetLowering &TLI, SDNodeFlags Flags) { 5443 if (Op.getValueType() == MVT::f32 && 5444 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5445 5446 // Put the exponent in the right bit position for later addition to the 5447 // final result: 5448 // 5449 // t0 = Op * log2(e) 5450 5451 // TODO: What fast-math-flags should be set here? 5452 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5453 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5454 return getLimitedPrecisionExp2(t0, dl, DAG); 5455 } 5456 5457 // No special expansion. 5458 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5459 } 5460 5461 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5462 /// limited-precision mode. 5463 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5464 const TargetLowering &TLI, SDNodeFlags Flags) { 5465 // TODO: What fast-math-flags should be set on the floating-point nodes? 5466 5467 if (Op.getValueType() == MVT::f32 && 5468 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5469 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5470 5471 // Scale the exponent by log(2). 5472 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5473 SDValue LogOfExponent = 5474 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5475 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5476 5477 // Get the significand and build it into a floating-point number with 5478 // exponent of 1. 5479 SDValue X = GetSignificand(DAG, Op1, dl); 5480 5481 SDValue LogOfMantissa; 5482 if (LimitFloatPrecision <= 6) { 5483 // For floating-point precision of 6: 5484 // 5485 // LogofMantissa = 5486 // -1.1609546f + 5487 // (1.4034025f - 0.23903021f * x) * x; 5488 // 5489 // error 0.0034276066, which is better than 8 bits 5490 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5491 getF32Constant(DAG, 0xbe74c456, dl)); 5492 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5493 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5494 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5495 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5496 getF32Constant(DAG, 0x3f949a29, dl)); 5497 } else if (LimitFloatPrecision <= 12) { 5498 // For floating-point precision of 12: 5499 // 5500 // LogOfMantissa = 5501 // -1.7417939f + 5502 // (2.8212026f + 5503 // (-1.4699568f + 5504 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5505 // 5506 // error 0.000061011436, which is 14 bits 5507 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5508 getF32Constant(DAG, 0xbd67b6d6, dl)); 5509 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5510 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5511 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5512 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5513 getF32Constant(DAG, 0x3fbc278b, dl)); 5514 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5515 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5516 getF32Constant(DAG, 0x40348e95, dl)); 5517 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5518 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5519 getF32Constant(DAG, 0x3fdef31a, dl)); 5520 } else { // LimitFloatPrecision <= 18 5521 // For floating-point precision of 18: 5522 // 5523 // LogOfMantissa = 5524 // -2.1072184f + 5525 // (4.2372794f + 5526 // (-3.7029485f + 5527 // (2.2781945f + 5528 // (-0.87823314f + 5529 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5530 // 5531 // error 0.0000023660568, which is better than 18 bits 5532 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5533 getF32Constant(DAG, 0xbc91e5ac, dl)); 5534 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5535 getF32Constant(DAG, 0x3e4350aa, dl)); 5536 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5537 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5538 getF32Constant(DAG, 0x3f60d3e3, dl)); 5539 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5540 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5541 getF32Constant(DAG, 0x4011cdf0, dl)); 5542 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5543 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5544 getF32Constant(DAG, 0x406cfd1c, dl)); 5545 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5546 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5547 getF32Constant(DAG, 0x408797cb, dl)); 5548 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5549 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5550 getF32Constant(DAG, 0x4006dcab, dl)); 5551 } 5552 5553 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5554 } 5555 5556 // No special expansion. 5557 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5558 } 5559 5560 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5561 /// limited-precision mode. 5562 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5563 const TargetLowering &TLI, SDNodeFlags Flags) { 5564 // TODO: What fast-math-flags should be set on the floating-point nodes? 5565 5566 if (Op.getValueType() == MVT::f32 && 5567 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5568 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5569 5570 // Get the exponent. 5571 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5572 5573 // Get the significand and build it into a floating-point number with 5574 // exponent of 1. 5575 SDValue X = GetSignificand(DAG, Op1, dl); 5576 5577 // Different possible minimax approximations of significand in 5578 // floating-point for various degrees of accuracy over [1,2]. 5579 SDValue Log2ofMantissa; 5580 if (LimitFloatPrecision <= 6) { 5581 // For floating-point precision of 6: 5582 // 5583 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5584 // 5585 // error 0.0049451742, which is more than 7 bits 5586 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5587 getF32Constant(DAG, 0xbeb08fe0, dl)); 5588 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5589 getF32Constant(DAG, 0x40019463, dl)); 5590 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5591 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5592 getF32Constant(DAG, 0x3fd6633d, dl)); 5593 } else if (LimitFloatPrecision <= 12) { 5594 // For floating-point precision of 12: 5595 // 5596 // Log2ofMantissa = 5597 // -2.51285454f + 5598 // (4.07009056f + 5599 // (-2.12067489f + 5600 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5601 // 5602 // error 0.0000876136000, which is better than 13 bits 5603 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5604 getF32Constant(DAG, 0xbda7262e, dl)); 5605 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5606 getF32Constant(DAG, 0x3f25280b, dl)); 5607 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5608 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5609 getF32Constant(DAG, 0x4007b923, dl)); 5610 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5611 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5612 getF32Constant(DAG, 0x40823e2f, dl)); 5613 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5614 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5615 getF32Constant(DAG, 0x4020d29c, dl)); 5616 } else { // LimitFloatPrecision <= 18 5617 // For floating-point precision of 18: 5618 // 5619 // Log2ofMantissa = 5620 // -3.0400495f + 5621 // (6.1129976f + 5622 // (-5.3420409f + 5623 // (3.2865683f + 5624 // (-1.2669343f + 5625 // (0.27515199f - 5626 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5627 // 5628 // error 0.0000018516, which is better than 18 bits 5629 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5630 getF32Constant(DAG, 0xbcd2769e, dl)); 5631 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5632 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5633 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5634 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5635 getF32Constant(DAG, 0x3fa22ae7, dl)); 5636 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5637 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5638 getF32Constant(DAG, 0x40525723, dl)); 5639 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5640 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5641 getF32Constant(DAG, 0x40aaf200, dl)); 5642 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5643 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5644 getF32Constant(DAG, 0x40c39dad, dl)); 5645 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5646 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5647 getF32Constant(DAG, 0x4042902c, dl)); 5648 } 5649 5650 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5651 } 5652 5653 // No special expansion. 5654 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5655 } 5656 5657 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5658 /// limited-precision mode. 5659 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5660 const TargetLowering &TLI, SDNodeFlags Flags) { 5661 // TODO: What fast-math-flags should be set on the floating-point nodes? 5662 5663 if (Op.getValueType() == MVT::f32 && 5664 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5665 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5666 5667 // Scale the exponent by log10(2) [0.30102999f]. 5668 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5669 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5670 getF32Constant(DAG, 0x3e9a209a, dl)); 5671 5672 // Get the significand and build it into a floating-point number with 5673 // exponent of 1. 5674 SDValue X = GetSignificand(DAG, Op1, dl); 5675 5676 SDValue Log10ofMantissa; 5677 if (LimitFloatPrecision <= 6) { 5678 // For floating-point precision of 6: 5679 // 5680 // Log10ofMantissa = 5681 // -0.50419619f + 5682 // (0.60948995f - 0.10380950f * x) * x; 5683 // 5684 // error 0.0014886165, which is 6 bits 5685 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5686 getF32Constant(DAG, 0xbdd49a13, dl)); 5687 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5688 getF32Constant(DAG, 0x3f1c0789, dl)); 5689 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5690 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5691 getF32Constant(DAG, 0x3f011300, dl)); 5692 } else if (LimitFloatPrecision <= 12) { 5693 // For floating-point precision of 12: 5694 // 5695 // Log10ofMantissa = 5696 // -0.64831180f + 5697 // (0.91751397f + 5698 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5699 // 5700 // error 0.00019228036, which is better than 12 bits 5701 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5702 getF32Constant(DAG, 0x3d431f31, dl)); 5703 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5704 getF32Constant(DAG, 0x3ea21fb2, dl)); 5705 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5706 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5707 getF32Constant(DAG, 0x3f6ae232, dl)); 5708 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5709 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5710 getF32Constant(DAG, 0x3f25f7c3, dl)); 5711 } else { // LimitFloatPrecision <= 18 5712 // For floating-point precision of 18: 5713 // 5714 // Log10ofMantissa = 5715 // -0.84299375f + 5716 // (1.5327582f + 5717 // (-1.0688956f + 5718 // (0.49102474f + 5719 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5720 // 5721 // error 0.0000037995730, which is better than 18 bits 5722 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5723 getF32Constant(DAG, 0x3c5d51ce, dl)); 5724 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5725 getF32Constant(DAG, 0x3e00685a, dl)); 5726 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5727 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5728 getF32Constant(DAG, 0x3efb6798, dl)); 5729 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5730 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5731 getF32Constant(DAG, 0x3f88d192, dl)); 5732 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5733 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5734 getF32Constant(DAG, 0x3fc4316c, dl)); 5735 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5736 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5737 getF32Constant(DAG, 0x3f57ce70, dl)); 5738 } 5739 5740 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5741 } 5742 5743 // No special expansion. 5744 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5745 } 5746 5747 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5748 /// limited-precision mode. 5749 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5750 const TargetLowering &TLI, SDNodeFlags Flags) { 5751 if (Op.getValueType() == MVT::f32 && 5752 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5753 return getLimitedPrecisionExp2(Op, dl, DAG); 5754 5755 // No special expansion. 5756 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5757 } 5758 5759 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5760 /// limited-precision mode with x == 10.0f. 5761 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5762 SelectionDAG &DAG, const TargetLowering &TLI, 5763 SDNodeFlags Flags) { 5764 bool IsExp10 = false; 5765 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5766 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5767 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5768 APFloat Ten(10.0f); 5769 IsExp10 = LHSC->isExactlyValue(Ten); 5770 } 5771 } 5772 5773 // TODO: What fast-math-flags should be set on the FMUL node? 5774 if (IsExp10) { 5775 // Put the exponent in the right bit position for later addition to the 5776 // final result: 5777 // 5778 // #define LOG2OF10 3.3219281f 5779 // t0 = Op * LOG2OF10; 5780 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5781 getF32Constant(DAG, 0x40549a78, dl)); 5782 return getLimitedPrecisionExp2(t0, dl, DAG); 5783 } 5784 5785 // No special expansion. 5786 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5787 } 5788 5789 /// ExpandPowI - Expand a llvm.powi intrinsic. 5790 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5791 SelectionDAG &DAG) { 5792 // If RHS is a constant, we can expand this out to a multiplication tree if 5793 // it's beneficial on the target, otherwise we end up lowering to a call to 5794 // __powidf2 (for example). 5795 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5796 unsigned Val = RHSC->getSExtValue(); 5797 5798 // powi(x, 0) -> 1.0 5799 if (Val == 0) 5800 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5801 5802 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5803 Val, DAG.shouldOptForSize())) { 5804 // Get the exponent as a positive value. 5805 if ((int)Val < 0) 5806 Val = -Val; 5807 // We use the simple binary decomposition method to generate the multiply 5808 // sequence. There are more optimal ways to do this (for example, 5809 // powi(x,15) generates one more multiply than it should), but this has 5810 // the benefit of being both really simple and much better than a libcall. 5811 SDValue Res; // Logically starts equal to 1.0 5812 SDValue CurSquare = LHS; 5813 // TODO: Intrinsics should have fast-math-flags that propagate to these 5814 // nodes. 5815 while (Val) { 5816 if (Val & 1) { 5817 if (Res.getNode()) 5818 Res = 5819 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5820 else 5821 Res = CurSquare; // 1.0*CurSquare. 5822 } 5823 5824 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5825 CurSquare, CurSquare); 5826 Val >>= 1; 5827 } 5828 5829 // If the original was negative, invert the result, producing 1/(x*x*x). 5830 if (RHSC->getSExtValue() < 0) 5831 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5832 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5833 return Res; 5834 } 5835 } 5836 5837 // Otherwise, expand to a libcall. 5838 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5839 } 5840 5841 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5842 SDValue LHS, SDValue RHS, SDValue Scale, 5843 SelectionDAG &DAG, const TargetLowering &TLI) { 5844 EVT VT = LHS.getValueType(); 5845 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5846 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5847 LLVMContext &Ctx = *DAG.getContext(); 5848 5849 // If the type is legal but the operation isn't, this node might survive all 5850 // the way to operation legalization. If we end up there and we do not have 5851 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5852 // node. 5853 5854 // Coax the legalizer into expanding the node during type legalization instead 5855 // by bumping the size by one bit. This will force it to Promote, enabling the 5856 // early expansion and avoiding the need to expand later. 5857 5858 // We don't have to do this if Scale is 0; that can always be expanded, unless 5859 // it's a saturating signed operation. Those can experience true integer 5860 // division overflow, a case which we must avoid. 5861 5862 // FIXME: We wouldn't have to do this (or any of the early 5863 // expansion/promotion) if it was possible to expand a libcall of an 5864 // illegal type during operation legalization. But it's not, so things 5865 // get a bit hacky. 5866 unsigned ScaleInt = Scale->getAsZExtVal(); 5867 if ((ScaleInt > 0 || (Saturating && Signed)) && 5868 (TLI.isTypeLegal(VT) || 5869 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5870 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5871 Opcode, VT, ScaleInt); 5872 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5873 EVT PromVT; 5874 if (VT.isScalarInteger()) 5875 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5876 else if (VT.isVector()) { 5877 PromVT = VT.getVectorElementType(); 5878 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5879 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5880 } else 5881 llvm_unreachable("Wrong VT for DIVFIX?"); 5882 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5883 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5884 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5885 // For saturating operations, we need to shift up the LHS to get the 5886 // proper saturation width, and then shift down again afterwards. 5887 if (Saturating) 5888 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5889 DAG.getConstant(1, DL, ShiftTy)); 5890 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5891 if (Saturating) 5892 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5893 DAG.getConstant(1, DL, ShiftTy)); 5894 return DAG.getZExtOrTrunc(Res, DL, VT); 5895 } 5896 } 5897 5898 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5899 } 5900 5901 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5902 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5903 static void 5904 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5905 const SDValue &N) { 5906 switch (N.getOpcode()) { 5907 case ISD::CopyFromReg: { 5908 SDValue Op = N.getOperand(1); 5909 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5910 Op.getValueType().getSizeInBits()); 5911 return; 5912 } 5913 case ISD::BITCAST: 5914 case ISD::AssertZext: 5915 case ISD::AssertSext: 5916 case ISD::TRUNCATE: 5917 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5918 return; 5919 case ISD::BUILD_PAIR: 5920 case ISD::BUILD_VECTOR: 5921 case ISD::CONCAT_VECTORS: 5922 for (SDValue Op : N->op_values()) 5923 getUnderlyingArgRegs(Regs, Op); 5924 return; 5925 default: 5926 return; 5927 } 5928 } 5929 5930 /// If the DbgValueInst is a dbg_value of a function argument, create the 5931 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5932 /// instruction selection, they will be inserted to the entry BB. 5933 /// We don't currently support this for variadic dbg_values, as they shouldn't 5934 /// appear for function arguments or in the prologue. 5935 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5936 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5937 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5938 const Argument *Arg = dyn_cast<Argument>(V); 5939 if (!Arg) 5940 return false; 5941 5942 MachineFunction &MF = DAG.getMachineFunction(); 5943 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5944 5945 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5946 // we've been asked to pursue. 5947 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5948 bool Indirect) { 5949 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5950 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5951 // pointing at the VReg, which will be patched up later. 5952 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5953 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5954 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5955 /* isKill */ false, /* isDead */ false, 5956 /* isUndef */ false, /* isEarlyClobber */ false, 5957 /* SubReg */ 0, /* isDebug */ true)}); 5958 5959 auto *NewDIExpr = FragExpr; 5960 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5961 // the DIExpression. 5962 if (Indirect) 5963 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5964 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5965 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5966 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5967 } else { 5968 // Create a completely standard DBG_VALUE. 5969 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5970 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5971 } 5972 }; 5973 5974 if (Kind == FuncArgumentDbgValueKind::Value) { 5975 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5976 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5977 // the entry block. 5978 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5979 if (!IsInEntryBlock) 5980 return false; 5981 5982 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5983 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5984 // variable that also is a param. 5985 // 5986 // Although, if we are at the top of the entry block already, we can still 5987 // emit using ArgDbgValue. This might catch some situations when the 5988 // dbg.value refers to an argument that isn't used in the entry block, so 5989 // any CopyToReg node would be optimized out and the only way to express 5990 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5991 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5992 // we should only emit as ArgDbgValue if the Variable is an argument to the 5993 // current function, and the dbg.value intrinsic is found in the entry 5994 // block. 5995 bool VariableIsFunctionInputArg = Variable->isParameter() && 5996 !DL->getInlinedAt(); 5997 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5998 if (!IsInPrologue && !VariableIsFunctionInputArg) 5999 return false; 6000 6001 // Here we assume that a function argument on IR level only can be used to 6002 // describe one input parameter on source level. If we for example have 6003 // source code like this 6004 // 6005 // struct A { long x, y; }; 6006 // void foo(struct A a, long b) { 6007 // ... 6008 // b = a.x; 6009 // ... 6010 // } 6011 // 6012 // and IR like this 6013 // 6014 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 6015 // entry: 6016 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 6017 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 6018 // call void @llvm.dbg.value(metadata i32 %b, "b", 6019 // ... 6020 // call void @llvm.dbg.value(metadata i32 %a1, "b" 6021 // ... 6022 // 6023 // then the last dbg.value is describing a parameter "b" using a value that 6024 // is an argument. But since we already has used %a1 to describe a parameter 6025 // we should not handle that last dbg.value here (that would result in an 6026 // incorrect hoisting of the DBG_VALUE to the function entry). 6027 // Notice that we allow one dbg.value per IR level argument, to accommodate 6028 // for the situation with fragments above. 6029 // If there is no node for the value being handled, we return true to skip 6030 // the normal generation of debug info, as it would kill existing debug 6031 // info for the parameter in case of duplicates. 6032 if (VariableIsFunctionInputArg) { 6033 unsigned ArgNo = Arg->getArgNo(); 6034 if (ArgNo >= FuncInfo.DescribedArgs.size()) 6035 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 6036 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 6037 return !NodeMap[V].getNode(); 6038 FuncInfo.DescribedArgs.set(ArgNo); 6039 } 6040 } 6041 6042 bool IsIndirect = false; 6043 std::optional<MachineOperand> Op; 6044 // Some arguments' frame index is recorded during argument lowering. 6045 int FI = FuncInfo.getArgumentFrameIndex(Arg); 6046 if (FI != std::numeric_limits<int>::max()) 6047 Op = MachineOperand::CreateFI(FI); 6048 6049 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 6050 if (!Op && N.getNode()) { 6051 getUnderlyingArgRegs(ArgRegsAndSizes, N); 6052 Register Reg; 6053 if (ArgRegsAndSizes.size() == 1) 6054 Reg = ArgRegsAndSizes.front().first; 6055 6056 if (Reg && Reg.isVirtual()) { 6057 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6058 Register PR = RegInfo.getLiveInPhysReg(Reg); 6059 if (PR) 6060 Reg = PR; 6061 } 6062 if (Reg) { 6063 Op = MachineOperand::CreateReg(Reg, false); 6064 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6065 } 6066 } 6067 6068 if (!Op && N.getNode()) { 6069 // Check if frame index is available. 6070 SDValue LCandidate = peekThroughBitcasts(N); 6071 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 6072 if (FrameIndexSDNode *FINode = 6073 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 6074 Op = MachineOperand::CreateFI(FINode->getIndex()); 6075 } 6076 6077 if (!Op) { 6078 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 6079 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 6080 SplitRegs) { 6081 unsigned Offset = 0; 6082 for (const auto &RegAndSize : SplitRegs) { 6083 // If the expression is already a fragment, the current register 6084 // offset+size might extend beyond the fragment. In this case, only 6085 // the register bits that are inside the fragment are relevant. 6086 int RegFragmentSizeInBits = RegAndSize.second; 6087 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 6088 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 6089 // The register is entirely outside the expression fragment, 6090 // so is irrelevant for debug info. 6091 if (Offset >= ExprFragmentSizeInBits) 6092 break; 6093 // The register is partially outside the expression fragment, only 6094 // the low bits within the fragment are relevant for debug info. 6095 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 6096 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 6097 } 6098 } 6099 6100 auto FragmentExpr = DIExpression::createFragmentExpression( 6101 Expr, Offset, RegFragmentSizeInBits); 6102 Offset += RegAndSize.second; 6103 // If a valid fragment expression cannot be created, the variable's 6104 // correct value cannot be determined and so it is set as Undef. 6105 if (!FragmentExpr) { 6106 SDDbgValue *SDV = DAG.getConstantDbgValue( 6107 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 6108 DAG.AddDbgValue(SDV, false); 6109 continue; 6110 } 6111 MachineInstr *NewMI = 6112 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 6113 Kind != FuncArgumentDbgValueKind::Value); 6114 FuncInfo.ArgDbgValues.push_back(NewMI); 6115 } 6116 }; 6117 6118 // Check if ValueMap has reg number. 6119 DenseMap<const Value *, Register>::const_iterator 6120 VMI = FuncInfo.ValueMap.find(V); 6121 if (VMI != FuncInfo.ValueMap.end()) { 6122 const auto &TLI = DAG.getTargetLoweringInfo(); 6123 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 6124 V->getType(), std::nullopt); 6125 if (RFV.occupiesMultipleRegs()) { 6126 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 6127 return true; 6128 } 6129 6130 Op = MachineOperand::CreateReg(VMI->second, false); 6131 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6132 } else if (ArgRegsAndSizes.size() > 1) { 6133 // This was split due to the calling convention, and no virtual register 6134 // mapping exists for the value. 6135 splitMultiRegDbgValue(ArgRegsAndSizes); 6136 return true; 6137 } 6138 } 6139 6140 if (!Op) 6141 return false; 6142 6143 assert(Variable->isValidLocationForIntrinsic(DL) && 6144 "Expected inlined-at fields to agree"); 6145 MachineInstr *NewMI = nullptr; 6146 6147 if (Op->isReg()) 6148 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 6149 else 6150 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 6151 Variable, Expr); 6152 6153 // Otherwise, use ArgDbgValues. 6154 FuncInfo.ArgDbgValues.push_back(NewMI); 6155 return true; 6156 } 6157 6158 /// Return the appropriate SDDbgValue based on N. 6159 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 6160 DILocalVariable *Variable, 6161 DIExpression *Expr, 6162 const DebugLoc &dl, 6163 unsigned DbgSDNodeOrder) { 6164 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 6165 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 6166 // stack slot locations. 6167 // 6168 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 6169 // debug values here after optimization: 6170 // 6171 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 6172 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 6173 // 6174 // Both describe the direct values of their associated variables. 6175 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 6176 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6177 } 6178 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 6179 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6180 } 6181 6182 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 6183 switch (Intrinsic) { 6184 case Intrinsic::smul_fix: 6185 return ISD::SMULFIX; 6186 case Intrinsic::umul_fix: 6187 return ISD::UMULFIX; 6188 case Intrinsic::smul_fix_sat: 6189 return ISD::SMULFIXSAT; 6190 case Intrinsic::umul_fix_sat: 6191 return ISD::UMULFIXSAT; 6192 case Intrinsic::sdiv_fix: 6193 return ISD::SDIVFIX; 6194 case Intrinsic::udiv_fix: 6195 return ISD::UDIVFIX; 6196 case Intrinsic::sdiv_fix_sat: 6197 return ISD::SDIVFIXSAT; 6198 case Intrinsic::udiv_fix_sat: 6199 return ISD::UDIVFIXSAT; 6200 default: 6201 llvm_unreachable("Unhandled fixed point intrinsic"); 6202 } 6203 } 6204 6205 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6206 const char *FunctionName) { 6207 assert(FunctionName && "FunctionName must not be nullptr"); 6208 SDValue Callee = DAG.getExternalSymbol( 6209 FunctionName, 6210 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6211 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6212 } 6213 6214 /// Given a @llvm.call.preallocated.setup, return the corresponding 6215 /// preallocated call. 6216 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6217 assert(cast<CallBase>(PreallocatedSetup) 6218 ->getCalledFunction() 6219 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6220 "expected call_preallocated_setup Value"); 6221 for (const auto *U : PreallocatedSetup->users()) { 6222 auto *UseCall = cast<CallBase>(U); 6223 const Function *Fn = UseCall->getCalledFunction(); 6224 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6225 return UseCall; 6226 } 6227 } 6228 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6229 } 6230 6231 /// If DI is a debug value with an EntryValue expression, lower it using the 6232 /// corresponding physical register of the associated Argument value 6233 /// (guaranteed to exist by the verifier). 6234 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6235 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6236 DIExpression *Expr, DebugLoc DbgLoc) { 6237 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6238 return false; 6239 6240 // These properties are guaranteed by the verifier. 6241 const Argument *Arg = cast<Argument>(Values[0]); 6242 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6243 6244 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6245 if (ArgIt == FuncInfo.ValueMap.end()) { 6246 LLVM_DEBUG( 6247 dbgs() << "Dropping dbg.value: expression is entry_value but " 6248 "couldn't find an associated register for the Argument\n"); 6249 return true; 6250 } 6251 Register ArgVReg = ArgIt->getSecond(); 6252 6253 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6254 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6255 SDDbgValue *SDV = DAG.getVRegDbgValue( 6256 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6257 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6258 return true; 6259 } 6260 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6261 "couldn't find a physical register\n"); 6262 return true; 6263 } 6264 6265 /// Lower the call to the specified intrinsic function. 6266 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I, 6267 unsigned Intrinsic) { 6268 SDLoc sdl = getCurSDLoc(); 6269 switch (Intrinsic) { 6270 case Intrinsic::experimental_convergence_anchor: 6271 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped)); 6272 break; 6273 case Intrinsic::experimental_convergence_entry: 6274 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped)); 6275 break; 6276 case Intrinsic::experimental_convergence_loop: { 6277 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl); 6278 auto *Token = Bundle->Inputs[0].get(); 6279 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped, 6280 getValue(Token))); 6281 break; 6282 } 6283 } 6284 } 6285 6286 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I, 6287 unsigned IntrinsicID) { 6288 // For now, we're only lowering an 'add' histogram. 6289 // We can add others later, e.g. saturating adds, min/max. 6290 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add && 6291 "Tried to lower unsupported histogram type"); 6292 SDLoc sdl = getCurSDLoc(); 6293 Value *Ptr = I.getOperand(0); 6294 SDValue Inc = getValue(I.getOperand(1)); 6295 SDValue Mask = getValue(I.getOperand(2)); 6296 6297 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6298 DataLayout TargetDL = DAG.getDataLayout(); 6299 EVT VT = Inc.getValueType(); 6300 Align Alignment = DAG.getEVTAlign(VT); 6301 6302 const MDNode *Ranges = getRangeMetadata(I); 6303 6304 SDValue Root = DAG.getRoot(); 6305 SDValue Base; 6306 SDValue Index; 6307 ISD::MemIndexType IndexType; 6308 SDValue Scale; 6309 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 6310 I.getParent(), VT.getScalarStoreSize()); 6311 6312 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 6313 6314 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6315 MachinePointerInfo(AS), 6316 MachineMemOperand::MOLoad | MachineMemOperand::MOStore, 6317 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 6318 6319 if (!UniformBase) { 6320 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6321 Index = getValue(Ptr); 6322 IndexType = ISD::SIGNED_SCALED; 6323 Scale = 6324 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6325 } 6326 6327 EVT IdxVT = Index.getValueType(); 6328 EVT EltTy = IdxVT.getVectorElementType(); 6329 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 6330 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 6331 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 6332 } 6333 6334 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32); 6335 6336 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID}; 6337 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl, 6338 Ops, MMO, IndexType); 6339 6340 setValue(&I, Histogram); 6341 DAG.setRoot(Histogram); 6342 } 6343 6344 /// Lower the call to the specified intrinsic function. 6345 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6346 unsigned Intrinsic) { 6347 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6348 SDLoc sdl = getCurSDLoc(); 6349 DebugLoc dl = getCurDebugLoc(); 6350 SDValue Res; 6351 6352 SDNodeFlags Flags; 6353 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6354 Flags.copyFMF(*FPOp); 6355 6356 switch (Intrinsic) { 6357 default: 6358 // By default, turn this into a target intrinsic node. 6359 visitTargetIntrinsic(I, Intrinsic); 6360 return; 6361 case Intrinsic::vscale: { 6362 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6363 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6364 return; 6365 } 6366 case Intrinsic::vastart: visitVAStart(I); return; 6367 case Intrinsic::vaend: visitVAEnd(I); return; 6368 case Intrinsic::vacopy: visitVACopy(I); return; 6369 case Intrinsic::returnaddress: 6370 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6371 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6372 getValue(I.getArgOperand(0)))); 6373 return; 6374 case Intrinsic::addressofreturnaddress: 6375 setValue(&I, 6376 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6377 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6378 return; 6379 case Intrinsic::sponentry: 6380 setValue(&I, 6381 DAG.getNode(ISD::SPONENTRY, sdl, 6382 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6383 return; 6384 case Intrinsic::frameaddress: 6385 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6386 TLI.getFrameIndexTy(DAG.getDataLayout()), 6387 getValue(I.getArgOperand(0)))); 6388 return; 6389 case Intrinsic::read_volatile_register: 6390 case Intrinsic::read_register: { 6391 Value *Reg = I.getArgOperand(0); 6392 SDValue Chain = getRoot(); 6393 SDValue RegName = 6394 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6395 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6396 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6397 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6398 setValue(&I, Res); 6399 DAG.setRoot(Res.getValue(1)); 6400 return; 6401 } 6402 case Intrinsic::write_register: { 6403 Value *Reg = I.getArgOperand(0); 6404 Value *RegValue = I.getArgOperand(1); 6405 SDValue Chain = getRoot(); 6406 SDValue RegName = 6407 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6408 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6409 RegName, getValue(RegValue))); 6410 return; 6411 } 6412 case Intrinsic::memcpy: { 6413 const auto &MCI = cast<MemCpyInst>(I); 6414 SDValue Op1 = getValue(I.getArgOperand(0)); 6415 SDValue Op2 = getValue(I.getArgOperand(1)); 6416 SDValue Op3 = getValue(I.getArgOperand(2)); 6417 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6418 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6419 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6420 Align Alignment = std::min(DstAlign, SrcAlign); 6421 bool isVol = MCI.isVolatile(); 6422 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6423 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6424 // node. 6425 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6426 SDValue MC = DAG.getMemcpy( 6427 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6428 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6429 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6430 updateDAGForMaybeTailCall(MC); 6431 return; 6432 } 6433 case Intrinsic::memcpy_inline: { 6434 const auto &MCI = cast<MemCpyInlineInst>(I); 6435 SDValue Dst = getValue(I.getArgOperand(0)); 6436 SDValue Src = getValue(I.getArgOperand(1)); 6437 SDValue Size = getValue(I.getArgOperand(2)); 6438 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6439 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6440 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6441 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6442 Align Alignment = std::min(DstAlign, SrcAlign); 6443 bool isVol = MCI.isVolatile(); 6444 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6445 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6446 // node. 6447 SDValue MC = DAG.getMemcpy( 6448 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6449 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6450 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6451 updateDAGForMaybeTailCall(MC); 6452 return; 6453 } 6454 case Intrinsic::memset: { 6455 const auto &MSI = cast<MemSetInst>(I); 6456 SDValue Op1 = getValue(I.getArgOperand(0)); 6457 SDValue Op2 = getValue(I.getArgOperand(1)); 6458 SDValue Op3 = getValue(I.getArgOperand(2)); 6459 // @llvm.memset defines 0 and 1 to both mean no alignment. 6460 Align Alignment = MSI.getDestAlign().valueOrOne(); 6461 bool isVol = MSI.isVolatile(); 6462 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6463 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6464 SDValue MS = DAG.getMemset( 6465 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6466 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6467 updateDAGForMaybeTailCall(MS); 6468 return; 6469 } 6470 case Intrinsic::memset_inline: { 6471 const auto &MSII = cast<MemSetInlineInst>(I); 6472 SDValue Dst = getValue(I.getArgOperand(0)); 6473 SDValue Value = getValue(I.getArgOperand(1)); 6474 SDValue Size = getValue(I.getArgOperand(2)); 6475 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6476 // @llvm.memset defines 0 and 1 to both mean no alignment. 6477 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6478 bool isVol = MSII.isVolatile(); 6479 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6480 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6481 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6482 /* AlwaysInline */ true, isTC, 6483 MachinePointerInfo(I.getArgOperand(0)), 6484 I.getAAMetadata()); 6485 updateDAGForMaybeTailCall(MC); 6486 return; 6487 } 6488 case Intrinsic::memmove: { 6489 const auto &MMI = cast<MemMoveInst>(I); 6490 SDValue Op1 = getValue(I.getArgOperand(0)); 6491 SDValue Op2 = getValue(I.getArgOperand(1)); 6492 SDValue Op3 = getValue(I.getArgOperand(2)); 6493 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6494 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6495 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6496 Align Alignment = std::min(DstAlign, SrcAlign); 6497 bool isVol = MMI.isVolatile(); 6498 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6499 // FIXME: Support passing different dest/src alignments to the memmove DAG 6500 // node. 6501 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6502 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6503 isTC, MachinePointerInfo(I.getArgOperand(0)), 6504 MachinePointerInfo(I.getArgOperand(1)), 6505 I.getAAMetadata(), AA); 6506 updateDAGForMaybeTailCall(MM); 6507 return; 6508 } 6509 case Intrinsic::memcpy_element_unordered_atomic: { 6510 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6511 SDValue Dst = getValue(MI.getRawDest()); 6512 SDValue Src = getValue(MI.getRawSource()); 6513 SDValue Length = getValue(MI.getLength()); 6514 6515 Type *LengthTy = MI.getLength()->getType(); 6516 unsigned ElemSz = MI.getElementSizeInBytes(); 6517 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6518 SDValue MC = 6519 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6520 isTC, MachinePointerInfo(MI.getRawDest()), 6521 MachinePointerInfo(MI.getRawSource())); 6522 updateDAGForMaybeTailCall(MC); 6523 return; 6524 } 6525 case Intrinsic::memmove_element_unordered_atomic: { 6526 auto &MI = cast<AtomicMemMoveInst>(I); 6527 SDValue Dst = getValue(MI.getRawDest()); 6528 SDValue Src = getValue(MI.getRawSource()); 6529 SDValue Length = getValue(MI.getLength()); 6530 6531 Type *LengthTy = MI.getLength()->getType(); 6532 unsigned ElemSz = MI.getElementSizeInBytes(); 6533 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6534 SDValue MC = 6535 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6536 isTC, MachinePointerInfo(MI.getRawDest()), 6537 MachinePointerInfo(MI.getRawSource())); 6538 updateDAGForMaybeTailCall(MC); 6539 return; 6540 } 6541 case Intrinsic::memset_element_unordered_atomic: { 6542 auto &MI = cast<AtomicMemSetInst>(I); 6543 SDValue Dst = getValue(MI.getRawDest()); 6544 SDValue Val = getValue(MI.getValue()); 6545 SDValue Length = getValue(MI.getLength()); 6546 6547 Type *LengthTy = MI.getLength()->getType(); 6548 unsigned ElemSz = MI.getElementSizeInBytes(); 6549 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6550 SDValue MC = 6551 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6552 isTC, MachinePointerInfo(MI.getRawDest())); 6553 updateDAGForMaybeTailCall(MC); 6554 return; 6555 } 6556 case Intrinsic::call_preallocated_setup: { 6557 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6558 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6559 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6560 getRoot(), SrcValue); 6561 setValue(&I, Res); 6562 DAG.setRoot(Res); 6563 return; 6564 } 6565 case Intrinsic::call_preallocated_arg: { 6566 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6567 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6568 SDValue Ops[3]; 6569 Ops[0] = getRoot(); 6570 Ops[1] = SrcValue; 6571 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6572 MVT::i32); // arg index 6573 SDValue Res = DAG.getNode( 6574 ISD::PREALLOCATED_ARG, sdl, 6575 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6576 setValue(&I, Res); 6577 DAG.setRoot(Res.getValue(1)); 6578 return; 6579 } 6580 case Intrinsic::dbg_declare: { 6581 const auto &DI = cast<DbgDeclareInst>(I); 6582 // Debug intrinsics are handled separately in assignment tracking mode. 6583 // Some intrinsics are handled right after Argument lowering. 6584 if (AssignmentTrackingEnabled || 6585 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6586 return; 6587 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6588 DILocalVariable *Variable = DI.getVariable(); 6589 DIExpression *Expression = DI.getExpression(); 6590 dropDanglingDebugInfo(Variable, Expression); 6591 // Assume dbg.declare can not currently use DIArgList, i.e. 6592 // it is non-variadic. 6593 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6594 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6595 DI.getDebugLoc()); 6596 return; 6597 } 6598 case Intrinsic::dbg_label: { 6599 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6600 DILabel *Label = DI.getLabel(); 6601 assert(Label && "Missing label"); 6602 6603 SDDbgLabel *SDV; 6604 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6605 DAG.AddDbgLabel(SDV); 6606 return; 6607 } 6608 case Intrinsic::dbg_assign: { 6609 // Debug intrinsics are handled seperately in assignment tracking mode. 6610 if (AssignmentTrackingEnabled) 6611 return; 6612 // If assignment tracking hasn't been enabled then fall through and treat 6613 // the dbg.assign as a dbg.value. 6614 [[fallthrough]]; 6615 } 6616 case Intrinsic::dbg_value: { 6617 // Debug intrinsics are handled seperately in assignment tracking mode. 6618 if (AssignmentTrackingEnabled) 6619 return; 6620 const DbgValueInst &DI = cast<DbgValueInst>(I); 6621 assert(DI.getVariable() && "Missing variable"); 6622 6623 DILocalVariable *Variable = DI.getVariable(); 6624 DIExpression *Expression = DI.getExpression(); 6625 dropDanglingDebugInfo(Variable, Expression); 6626 6627 if (DI.isKillLocation()) { 6628 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6629 return; 6630 } 6631 6632 SmallVector<Value *, 4> Values(DI.getValues()); 6633 if (Values.empty()) 6634 return; 6635 6636 bool IsVariadic = DI.hasArgList(); 6637 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6638 SDNodeOrder, IsVariadic)) 6639 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6640 DI.getDebugLoc(), SDNodeOrder); 6641 return; 6642 } 6643 6644 case Intrinsic::eh_typeid_for: { 6645 // Find the type id for the given typeinfo. 6646 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6647 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6648 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6649 setValue(&I, Res); 6650 return; 6651 } 6652 6653 case Intrinsic::eh_return_i32: 6654 case Intrinsic::eh_return_i64: 6655 DAG.getMachineFunction().setCallsEHReturn(true); 6656 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6657 MVT::Other, 6658 getControlRoot(), 6659 getValue(I.getArgOperand(0)), 6660 getValue(I.getArgOperand(1)))); 6661 return; 6662 case Intrinsic::eh_unwind_init: 6663 DAG.getMachineFunction().setCallsUnwindInit(true); 6664 return; 6665 case Intrinsic::eh_dwarf_cfa: 6666 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6667 TLI.getPointerTy(DAG.getDataLayout()), 6668 getValue(I.getArgOperand(0)))); 6669 return; 6670 case Intrinsic::eh_sjlj_callsite: { 6671 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6672 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6673 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6674 6675 MMI.setCurrentCallSite(CI->getZExtValue()); 6676 return; 6677 } 6678 case Intrinsic::eh_sjlj_functioncontext: { 6679 // Get and store the index of the function context. 6680 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6681 AllocaInst *FnCtx = 6682 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6683 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6684 MFI.setFunctionContextIndex(FI); 6685 return; 6686 } 6687 case Intrinsic::eh_sjlj_setjmp: { 6688 SDValue Ops[2]; 6689 Ops[0] = getRoot(); 6690 Ops[1] = getValue(I.getArgOperand(0)); 6691 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6692 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6693 setValue(&I, Op.getValue(0)); 6694 DAG.setRoot(Op.getValue(1)); 6695 return; 6696 } 6697 case Intrinsic::eh_sjlj_longjmp: 6698 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6699 getRoot(), getValue(I.getArgOperand(0)))); 6700 return; 6701 case Intrinsic::eh_sjlj_setup_dispatch: 6702 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6703 getRoot())); 6704 return; 6705 case Intrinsic::masked_gather: 6706 visitMaskedGather(I); 6707 return; 6708 case Intrinsic::masked_load: 6709 visitMaskedLoad(I); 6710 return; 6711 case Intrinsic::masked_scatter: 6712 visitMaskedScatter(I); 6713 return; 6714 case Intrinsic::masked_store: 6715 visitMaskedStore(I); 6716 return; 6717 case Intrinsic::masked_expandload: 6718 visitMaskedLoad(I, true /* IsExpanding */); 6719 return; 6720 case Intrinsic::masked_compressstore: 6721 visitMaskedStore(I, true /* IsCompressing */); 6722 return; 6723 case Intrinsic::powi: 6724 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6725 getValue(I.getArgOperand(1)), DAG)); 6726 return; 6727 case Intrinsic::log: 6728 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6729 return; 6730 case Intrinsic::log2: 6731 setValue(&I, 6732 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6733 return; 6734 case Intrinsic::log10: 6735 setValue(&I, 6736 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6737 return; 6738 case Intrinsic::exp: 6739 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6740 return; 6741 case Intrinsic::exp2: 6742 setValue(&I, 6743 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6744 return; 6745 case Intrinsic::pow: 6746 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6747 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6748 return; 6749 case Intrinsic::sqrt: 6750 case Intrinsic::fabs: 6751 case Intrinsic::sin: 6752 case Intrinsic::cos: 6753 case Intrinsic::exp10: 6754 case Intrinsic::floor: 6755 case Intrinsic::ceil: 6756 case Intrinsic::trunc: 6757 case Intrinsic::rint: 6758 case Intrinsic::nearbyint: 6759 case Intrinsic::round: 6760 case Intrinsic::roundeven: 6761 case Intrinsic::canonicalize: { 6762 unsigned Opcode; 6763 // clang-format off 6764 switch (Intrinsic) { 6765 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6766 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6767 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6768 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6769 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6770 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6771 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6772 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6773 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6774 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6775 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6776 case Intrinsic::round: Opcode = ISD::FROUND; break; 6777 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6778 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6779 } 6780 // clang-format on 6781 6782 setValue(&I, DAG.getNode(Opcode, sdl, 6783 getValue(I.getArgOperand(0)).getValueType(), 6784 getValue(I.getArgOperand(0)), Flags)); 6785 return; 6786 } 6787 case Intrinsic::lround: 6788 case Intrinsic::llround: 6789 case Intrinsic::lrint: 6790 case Intrinsic::llrint: { 6791 unsigned Opcode; 6792 // clang-format off 6793 switch (Intrinsic) { 6794 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6795 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6796 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6797 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6798 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6799 } 6800 // clang-format on 6801 6802 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6803 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6804 getValue(I.getArgOperand(0)))); 6805 return; 6806 } 6807 case Intrinsic::minnum: 6808 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6809 getValue(I.getArgOperand(0)).getValueType(), 6810 getValue(I.getArgOperand(0)), 6811 getValue(I.getArgOperand(1)), Flags)); 6812 return; 6813 case Intrinsic::maxnum: 6814 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6815 getValue(I.getArgOperand(0)).getValueType(), 6816 getValue(I.getArgOperand(0)), 6817 getValue(I.getArgOperand(1)), Flags)); 6818 return; 6819 case Intrinsic::minimum: 6820 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6821 getValue(I.getArgOperand(0)).getValueType(), 6822 getValue(I.getArgOperand(0)), 6823 getValue(I.getArgOperand(1)), Flags)); 6824 return; 6825 case Intrinsic::maximum: 6826 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6827 getValue(I.getArgOperand(0)).getValueType(), 6828 getValue(I.getArgOperand(0)), 6829 getValue(I.getArgOperand(1)), Flags)); 6830 return; 6831 case Intrinsic::copysign: 6832 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6833 getValue(I.getArgOperand(0)).getValueType(), 6834 getValue(I.getArgOperand(0)), 6835 getValue(I.getArgOperand(1)), Flags)); 6836 return; 6837 case Intrinsic::ldexp: 6838 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6839 getValue(I.getArgOperand(0)).getValueType(), 6840 getValue(I.getArgOperand(0)), 6841 getValue(I.getArgOperand(1)), Flags)); 6842 return; 6843 case Intrinsic::frexp: { 6844 SmallVector<EVT, 2> ValueVTs; 6845 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6846 SDVTList VTs = DAG.getVTList(ValueVTs); 6847 setValue(&I, 6848 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6849 return; 6850 } 6851 case Intrinsic::arithmetic_fence: { 6852 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6853 getValue(I.getArgOperand(0)).getValueType(), 6854 getValue(I.getArgOperand(0)), Flags)); 6855 return; 6856 } 6857 case Intrinsic::fma: 6858 setValue(&I, DAG.getNode( 6859 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6860 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6861 getValue(I.getArgOperand(2)), Flags)); 6862 return; 6863 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6864 case Intrinsic::INTRINSIC: 6865 #include "llvm/IR/ConstrainedOps.def" 6866 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6867 return; 6868 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6869 #include "llvm/IR/VPIntrinsics.def" 6870 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6871 return; 6872 case Intrinsic::fptrunc_round: { 6873 // Get the last argument, the metadata and convert it to an integer in the 6874 // call 6875 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6876 std::optional<RoundingMode> RoundMode = 6877 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6878 6879 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6880 6881 // Propagate fast-math-flags from IR to node(s). 6882 SDNodeFlags Flags; 6883 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6884 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6885 6886 SDValue Result; 6887 Result = DAG.getNode( 6888 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6889 DAG.getTargetConstant((int)*RoundMode, sdl, 6890 TLI.getPointerTy(DAG.getDataLayout()))); 6891 setValue(&I, Result); 6892 6893 return; 6894 } 6895 case Intrinsic::fmuladd: { 6896 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6897 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6898 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6899 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6900 getValue(I.getArgOperand(0)).getValueType(), 6901 getValue(I.getArgOperand(0)), 6902 getValue(I.getArgOperand(1)), 6903 getValue(I.getArgOperand(2)), Flags)); 6904 } else { 6905 // TODO: Intrinsic calls should have fast-math-flags. 6906 SDValue Mul = DAG.getNode( 6907 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6908 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6909 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6910 getValue(I.getArgOperand(0)).getValueType(), 6911 Mul, getValue(I.getArgOperand(2)), Flags); 6912 setValue(&I, Add); 6913 } 6914 return; 6915 } 6916 case Intrinsic::convert_to_fp16: 6917 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6918 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6919 getValue(I.getArgOperand(0)), 6920 DAG.getTargetConstant(0, sdl, 6921 MVT::i32)))); 6922 return; 6923 case Intrinsic::convert_from_fp16: 6924 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6925 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6926 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6927 getValue(I.getArgOperand(0))))); 6928 return; 6929 case Intrinsic::fptosi_sat: { 6930 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6931 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6932 getValue(I.getArgOperand(0)), 6933 DAG.getValueType(VT.getScalarType()))); 6934 return; 6935 } 6936 case Intrinsic::fptoui_sat: { 6937 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6938 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6939 getValue(I.getArgOperand(0)), 6940 DAG.getValueType(VT.getScalarType()))); 6941 return; 6942 } 6943 case Intrinsic::set_rounding: 6944 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6945 {getRoot(), getValue(I.getArgOperand(0))}); 6946 setValue(&I, Res); 6947 DAG.setRoot(Res.getValue(0)); 6948 return; 6949 case Intrinsic::is_fpclass: { 6950 const DataLayout DLayout = DAG.getDataLayout(); 6951 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6952 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6953 FPClassTest Test = static_cast<FPClassTest>( 6954 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6955 MachineFunction &MF = DAG.getMachineFunction(); 6956 const Function &F = MF.getFunction(); 6957 SDValue Op = getValue(I.getArgOperand(0)); 6958 SDNodeFlags Flags; 6959 Flags.setNoFPExcept( 6960 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6961 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6962 // expansion can use illegal types. Making expansion early allows 6963 // legalizing these types prior to selection. 6964 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6965 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6966 setValue(&I, Result); 6967 return; 6968 } 6969 6970 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6971 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6972 setValue(&I, V); 6973 return; 6974 } 6975 case Intrinsic::get_fpenv: { 6976 const DataLayout DLayout = DAG.getDataLayout(); 6977 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6978 Align TempAlign = DAG.getEVTAlign(EnvVT); 6979 SDValue Chain = getRoot(); 6980 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6981 // and temporary storage in stack. 6982 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6983 Res = DAG.getNode( 6984 ISD::GET_FPENV, sdl, 6985 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6986 MVT::Other), 6987 Chain); 6988 } else { 6989 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6990 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6991 auto MPI = 6992 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6993 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6994 MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(), 6995 TempAlign); 6996 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6997 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6998 } 6999 setValue(&I, Res); 7000 DAG.setRoot(Res.getValue(1)); 7001 return; 7002 } 7003 case Intrinsic::set_fpenv: { 7004 const DataLayout DLayout = DAG.getDataLayout(); 7005 SDValue Env = getValue(I.getArgOperand(0)); 7006 EVT EnvVT = Env.getValueType(); 7007 Align TempAlign = DAG.getEVTAlign(EnvVT); 7008 SDValue Chain = getRoot(); 7009 // If SET_FPENV is custom or legal, use it. Otherwise use loading 7010 // environment from memory. 7011 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 7012 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 7013 } else { 7014 // Allocate space in stack, copy environment bits into it and use this 7015 // memory in SET_FPENV_MEM. 7016 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7017 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7018 auto MPI = 7019 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7020 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 7021 MachineMemOperand::MOStore); 7022 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7023 MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(), 7024 TempAlign); 7025 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7026 } 7027 DAG.setRoot(Chain); 7028 return; 7029 } 7030 case Intrinsic::reset_fpenv: 7031 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 7032 return; 7033 case Intrinsic::get_fpmode: 7034 Res = DAG.getNode( 7035 ISD::GET_FPMODE, sdl, 7036 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7037 MVT::Other), 7038 DAG.getRoot()); 7039 setValue(&I, Res); 7040 DAG.setRoot(Res.getValue(1)); 7041 return; 7042 case Intrinsic::set_fpmode: 7043 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 7044 getValue(I.getArgOperand(0))); 7045 DAG.setRoot(Res); 7046 return; 7047 case Intrinsic::reset_fpmode: { 7048 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 7049 DAG.setRoot(Res); 7050 return; 7051 } 7052 case Intrinsic::pcmarker: { 7053 SDValue Tmp = getValue(I.getArgOperand(0)); 7054 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 7055 return; 7056 } 7057 case Intrinsic::readcyclecounter: { 7058 SDValue Op = getRoot(); 7059 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 7060 DAG.getVTList(MVT::i64, MVT::Other), Op); 7061 setValue(&I, Res); 7062 DAG.setRoot(Res.getValue(1)); 7063 return; 7064 } 7065 case Intrinsic::readsteadycounter: { 7066 SDValue Op = getRoot(); 7067 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 7068 DAG.getVTList(MVT::i64, MVT::Other), Op); 7069 setValue(&I, Res); 7070 DAG.setRoot(Res.getValue(1)); 7071 return; 7072 } 7073 case Intrinsic::bitreverse: 7074 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 7075 getValue(I.getArgOperand(0)).getValueType(), 7076 getValue(I.getArgOperand(0)))); 7077 return; 7078 case Intrinsic::bswap: 7079 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 7080 getValue(I.getArgOperand(0)).getValueType(), 7081 getValue(I.getArgOperand(0)))); 7082 return; 7083 case Intrinsic::cttz: { 7084 SDValue Arg = getValue(I.getArgOperand(0)); 7085 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7086 EVT Ty = Arg.getValueType(); 7087 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 7088 sdl, Ty, Arg)); 7089 return; 7090 } 7091 case Intrinsic::ctlz: { 7092 SDValue Arg = getValue(I.getArgOperand(0)); 7093 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7094 EVT Ty = Arg.getValueType(); 7095 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 7096 sdl, Ty, Arg)); 7097 return; 7098 } 7099 case Intrinsic::ctpop: { 7100 SDValue Arg = getValue(I.getArgOperand(0)); 7101 EVT Ty = Arg.getValueType(); 7102 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 7103 return; 7104 } 7105 case Intrinsic::fshl: 7106 case Intrinsic::fshr: { 7107 bool IsFSHL = Intrinsic == Intrinsic::fshl; 7108 SDValue X = getValue(I.getArgOperand(0)); 7109 SDValue Y = getValue(I.getArgOperand(1)); 7110 SDValue Z = getValue(I.getArgOperand(2)); 7111 EVT VT = X.getValueType(); 7112 7113 if (X == Y) { 7114 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 7115 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 7116 } else { 7117 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 7118 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 7119 } 7120 return; 7121 } 7122 case Intrinsic::sadd_sat: { 7123 SDValue Op1 = getValue(I.getArgOperand(0)); 7124 SDValue Op2 = getValue(I.getArgOperand(1)); 7125 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7126 return; 7127 } 7128 case Intrinsic::uadd_sat: { 7129 SDValue Op1 = getValue(I.getArgOperand(0)); 7130 SDValue Op2 = getValue(I.getArgOperand(1)); 7131 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7132 return; 7133 } 7134 case Intrinsic::ssub_sat: { 7135 SDValue Op1 = getValue(I.getArgOperand(0)); 7136 SDValue Op2 = getValue(I.getArgOperand(1)); 7137 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7138 return; 7139 } 7140 case Intrinsic::usub_sat: { 7141 SDValue Op1 = getValue(I.getArgOperand(0)); 7142 SDValue Op2 = getValue(I.getArgOperand(1)); 7143 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7144 return; 7145 } 7146 case Intrinsic::sshl_sat: { 7147 SDValue Op1 = getValue(I.getArgOperand(0)); 7148 SDValue Op2 = getValue(I.getArgOperand(1)); 7149 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7150 return; 7151 } 7152 case Intrinsic::ushl_sat: { 7153 SDValue Op1 = getValue(I.getArgOperand(0)); 7154 SDValue Op2 = getValue(I.getArgOperand(1)); 7155 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7156 return; 7157 } 7158 case Intrinsic::smul_fix: 7159 case Intrinsic::umul_fix: 7160 case Intrinsic::smul_fix_sat: 7161 case Intrinsic::umul_fix_sat: { 7162 SDValue Op1 = getValue(I.getArgOperand(0)); 7163 SDValue Op2 = getValue(I.getArgOperand(1)); 7164 SDValue Op3 = getValue(I.getArgOperand(2)); 7165 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7166 Op1.getValueType(), Op1, Op2, Op3)); 7167 return; 7168 } 7169 case Intrinsic::sdiv_fix: 7170 case Intrinsic::udiv_fix: 7171 case Intrinsic::sdiv_fix_sat: 7172 case Intrinsic::udiv_fix_sat: { 7173 SDValue Op1 = getValue(I.getArgOperand(0)); 7174 SDValue Op2 = getValue(I.getArgOperand(1)); 7175 SDValue Op3 = getValue(I.getArgOperand(2)); 7176 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7177 Op1, Op2, Op3, DAG, TLI)); 7178 return; 7179 } 7180 case Intrinsic::smax: { 7181 SDValue Op1 = getValue(I.getArgOperand(0)); 7182 SDValue Op2 = getValue(I.getArgOperand(1)); 7183 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 7184 return; 7185 } 7186 case Intrinsic::smin: { 7187 SDValue Op1 = getValue(I.getArgOperand(0)); 7188 SDValue Op2 = getValue(I.getArgOperand(1)); 7189 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 7190 return; 7191 } 7192 case Intrinsic::umax: { 7193 SDValue Op1 = getValue(I.getArgOperand(0)); 7194 SDValue Op2 = getValue(I.getArgOperand(1)); 7195 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 7196 return; 7197 } 7198 case Intrinsic::umin: { 7199 SDValue Op1 = getValue(I.getArgOperand(0)); 7200 SDValue Op2 = getValue(I.getArgOperand(1)); 7201 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 7202 return; 7203 } 7204 case Intrinsic::abs: { 7205 // TODO: Preserve "int min is poison" arg in SDAG? 7206 SDValue Op1 = getValue(I.getArgOperand(0)); 7207 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 7208 return; 7209 } 7210 case Intrinsic::stacksave: { 7211 SDValue Op = getRoot(); 7212 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7213 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 7214 setValue(&I, Res); 7215 DAG.setRoot(Res.getValue(1)); 7216 return; 7217 } 7218 case Intrinsic::stackrestore: 7219 Res = getValue(I.getArgOperand(0)); 7220 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 7221 return; 7222 case Intrinsic::get_dynamic_area_offset: { 7223 SDValue Op = getRoot(); 7224 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7225 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7226 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 7227 // target. 7228 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 7229 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 7230 " intrinsic!"); 7231 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 7232 Op); 7233 DAG.setRoot(Op); 7234 setValue(&I, Res); 7235 return; 7236 } 7237 case Intrinsic::stackguard: { 7238 MachineFunction &MF = DAG.getMachineFunction(); 7239 const Module &M = *MF.getFunction().getParent(); 7240 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7241 SDValue Chain = getRoot(); 7242 if (TLI.useLoadStackGuardNode()) { 7243 Res = getLoadStackGuard(DAG, sdl, Chain); 7244 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 7245 } else { 7246 const Value *Global = TLI.getSDagStackGuard(M); 7247 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7248 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7249 MachinePointerInfo(Global, 0), Align, 7250 MachineMemOperand::MOVolatile); 7251 } 7252 if (TLI.useStackGuardXorFP()) 7253 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7254 DAG.setRoot(Chain); 7255 setValue(&I, Res); 7256 return; 7257 } 7258 case Intrinsic::stackprotector: { 7259 // Emit code into the DAG to store the stack guard onto the stack. 7260 MachineFunction &MF = DAG.getMachineFunction(); 7261 MachineFrameInfo &MFI = MF.getFrameInfo(); 7262 SDValue Src, Chain = getRoot(); 7263 7264 if (TLI.useLoadStackGuardNode()) 7265 Src = getLoadStackGuard(DAG, sdl, Chain); 7266 else 7267 Src = getValue(I.getArgOperand(0)); // The guard's value. 7268 7269 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7270 7271 int FI = FuncInfo.StaticAllocaMap[Slot]; 7272 MFI.setStackProtectorIndex(FI); 7273 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7274 7275 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7276 7277 // Store the stack protector onto the stack. 7278 Res = DAG.getStore( 7279 Chain, sdl, Src, FIN, 7280 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7281 MaybeAlign(), MachineMemOperand::MOVolatile); 7282 setValue(&I, Res); 7283 DAG.setRoot(Res); 7284 return; 7285 } 7286 case Intrinsic::objectsize: 7287 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7288 7289 case Intrinsic::is_constant: 7290 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7291 7292 case Intrinsic::annotation: 7293 case Intrinsic::ptr_annotation: 7294 case Intrinsic::launder_invariant_group: 7295 case Intrinsic::strip_invariant_group: 7296 // Drop the intrinsic, but forward the value 7297 setValue(&I, getValue(I.getOperand(0))); 7298 return; 7299 7300 case Intrinsic::assume: 7301 case Intrinsic::experimental_noalias_scope_decl: 7302 case Intrinsic::var_annotation: 7303 case Intrinsic::sideeffect: 7304 // Discard annotate attributes, noalias scope declarations, assumptions, and 7305 // artificial side-effects. 7306 return; 7307 7308 case Intrinsic::codeview_annotation: { 7309 // Emit a label associated with this metadata. 7310 MachineFunction &MF = DAG.getMachineFunction(); 7311 MCSymbol *Label = 7312 MF.getMMI().getContext().createTempSymbol("annotation", true); 7313 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7314 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7315 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7316 DAG.setRoot(Res); 7317 return; 7318 } 7319 7320 case Intrinsic::init_trampoline: { 7321 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7322 7323 SDValue Ops[6]; 7324 Ops[0] = getRoot(); 7325 Ops[1] = getValue(I.getArgOperand(0)); 7326 Ops[2] = getValue(I.getArgOperand(1)); 7327 Ops[3] = getValue(I.getArgOperand(2)); 7328 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7329 Ops[5] = DAG.getSrcValue(F); 7330 7331 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7332 7333 DAG.setRoot(Res); 7334 return; 7335 } 7336 case Intrinsic::adjust_trampoline: 7337 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7338 TLI.getPointerTy(DAG.getDataLayout()), 7339 getValue(I.getArgOperand(0)))); 7340 return; 7341 case Intrinsic::gcroot: { 7342 assert(DAG.getMachineFunction().getFunction().hasGC() && 7343 "only valid in functions with gc specified, enforced by Verifier"); 7344 assert(GFI && "implied by previous"); 7345 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7346 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7347 7348 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7349 GFI->addStackRoot(FI->getIndex(), TypeMap); 7350 return; 7351 } 7352 case Intrinsic::gcread: 7353 case Intrinsic::gcwrite: 7354 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7355 case Intrinsic::get_rounding: 7356 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7357 setValue(&I, Res); 7358 DAG.setRoot(Res.getValue(1)); 7359 return; 7360 7361 case Intrinsic::expect: 7362 // Just replace __builtin_expect(exp, c) with EXP. 7363 setValue(&I, getValue(I.getArgOperand(0))); 7364 return; 7365 7366 case Intrinsic::ubsantrap: 7367 case Intrinsic::debugtrap: 7368 case Intrinsic::trap: { 7369 StringRef TrapFuncName = 7370 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7371 if (TrapFuncName.empty()) { 7372 switch (Intrinsic) { 7373 case Intrinsic::trap: 7374 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7375 break; 7376 case Intrinsic::debugtrap: 7377 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7378 break; 7379 case Intrinsic::ubsantrap: 7380 DAG.setRoot(DAG.getNode( 7381 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7382 DAG.getTargetConstant( 7383 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7384 MVT::i32))); 7385 break; 7386 default: llvm_unreachable("unknown trap intrinsic"); 7387 } 7388 return; 7389 } 7390 TargetLowering::ArgListTy Args; 7391 if (Intrinsic == Intrinsic::ubsantrap) { 7392 Args.push_back(TargetLoweringBase::ArgListEntry()); 7393 Args[0].Val = I.getArgOperand(0); 7394 Args[0].Node = getValue(Args[0].Val); 7395 Args[0].Ty = Args[0].Val->getType(); 7396 } 7397 7398 TargetLowering::CallLoweringInfo CLI(DAG); 7399 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7400 CallingConv::C, I.getType(), 7401 DAG.getExternalSymbol(TrapFuncName.data(), 7402 TLI.getPointerTy(DAG.getDataLayout())), 7403 std::move(Args)); 7404 7405 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7406 DAG.setRoot(Result.second); 7407 return; 7408 } 7409 7410 case Intrinsic::allow_runtime_check: 7411 case Intrinsic::allow_ubsan_check: 7412 setValue(&I, getValue(ConstantInt::getTrue(I.getType()))); 7413 return; 7414 7415 case Intrinsic::uadd_with_overflow: 7416 case Intrinsic::sadd_with_overflow: 7417 case Intrinsic::usub_with_overflow: 7418 case Intrinsic::ssub_with_overflow: 7419 case Intrinsic::umul_with_overflow: 7420 case Intrinsic::smul_with_overflow: { 7421 ISD::NodeType Op; 7422 switch (Intrinsic) { 7423 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7424 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7425 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7426 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7427 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7428 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7429 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7430 } 7431 SDValue Op1 = getValue(I.getArgOperand(0)); 7432 SDValue Op2 = getValue(I.getArgOperand(1)); 7433 7434 EVT ResultVT = Op1.getValueType(); 7435 EVT OverflowVT = MVT::i1; 7436 if (ResultVT.isVector()) 7437 OverflowVT = EVT::getVectorVT( 7438 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7439 7440 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7441 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7442 return; 7443 } 7444 case Intrinsic::prefetch: { 7445 SDValue Ops[5]; 7446 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7447 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7448 Ops[0] = DAG.getRoot(); 7449 Ops[1] = getValue(I.getArgOperand(0)); 7450 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7451 MVT::i32); 7452 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7453 MVT::i32); 7454 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7455 MVT::i32); 7456 SDValue Result = DAG.getMemIntrinsicNode( 7457 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7458 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7459 /* align */ std::nullopt, Flags); 7460 7461 // Chain the prefetch in parallel with any pending loads, to stay out of 7462 // the way of later optimizations. 7463 PendingLoads.push_back(Result); 7464 Result = getRoot(); 7465 DAG.setRoot(Result); 7466 return; 7467 } 7468 case Intrinsic::lifetime_start: 7469 case Intrinsic::lifetime_end: { 7470 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7471 // Stack coloring is not enabled in O0, discard region information. 7472 if (TM.getOptLevel() == CodeGenOptLevel::None) 7473 return; 7474 7475 const int64_t ObjectSize = 7476 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7477 Value *const ObjectPtr = I.getArgOperand(1); 7478 SmallVector<const Value *, 4> Allocas; 7479 getUnderlyingObjects(ObjectPtr, Allocas); 7480 7481 for (const Value *Alloca : Allocas) { 7482 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7483 7484 // Could not find an Alloca. 7485 if (!LifetimeObject) 7486 continue; 7487 7488 // First check that the Alloca is static, otherwise it won't have a 7489 // valid frame index. 7490 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7491 if (SI == FuncInfo.StaticAllocaMap.end()) 7492 return; 7493 7494 const int FrameIndex = SI->second; 7495 int64_t Offset; 7496 if (GetPointerBaseWithConstantOffset( 7497 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7498 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7499 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7500 Offset); 7501 DAG.setRoot(Res); 7502 } 7503 return; 7504 } 7505 case Intrinsic::pseudoprobe: { 7506 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7507 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7508 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7509 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7510 DAG.setRoot(Res); 7511 return; 7512 } 7513 case Intrinsic::invariant_start: 7514 // Discard region information. 7515 setValue(&I, 7516 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7517 return; 7518 case Intrinsic::invariant_end: 7519 // Discard region information. 7520 return; 7521 case Intrinsic::clear_cache: { 7522 SDValue InputChain = DAG.getRoot(); 7523 SDValue StartVal = getValue(I.getArgOperand(0)); 7524 SDValue EndVal = getValue(I.getArgOperand(1)); 7525 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other), 7526 {InputChain, StartVal, EndVal}); 7527 setValue(&I, Res); 7528 DAG.setRoot(Res); 7529 return; 7530 } 7531 case Intrinsic::donothing: 7532 case Intrinsic::seh_try_begin: 7533 case Intrinsic::seh_scope_begin: 7534 case Intrinsic::seh_try_end: 7535 case Intrinsic::seh_scope_end: 7536 // ignore 7537 return; 7538 case Intrinsic::experimental_stackmap: 7539 visitStackmap(I); 7540 return; 7541 case Intrinsic::experimental_patchpoint_void: 7542 case Intrinsic::experimental_patchpoint: 7543 visitPatchpoint(I); 7544 return; 7545 case Intrinsic::experimental_gc_statepoint: 7546 LowerStatepoint(cast<GCStatepointInst>(I)); 7547 return; 7548 case Intrinsic::experimental_gc_result: 7549 visitGCResult(cast<GCResultInst>(I)); 7550 return; 7551 case Intrinsic::experimental_gc_relocate: 7552 visitGCRelocate(cast<GCRelocateInst>(I)); 7553 return; 7554 case Intrinsic::instrprof_cover: 7555 llvm_unreachable("instrprof failed to lower a cover"); 7556 case Intrinsic::instrprof_increment: 7557 llvm_unreachable("instrprof failed to lower an increment"); 7558 case Intrinsic::instrprof_timestamp: 7559 llvm_unreachable("instrprof failed to lower a timestamp"); 7560 case Intrinsic::instrprof_value_profile: 7561 llvm_unreachable("instrprof failed to lower a value profiling call"); 7562 case Intrinsic::instrprof_mcdc_parameters: 7563 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7564 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7565 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7566 case Intrinsic::instrprof_mcdc_condbitmap_update: 7567 llvm_unreachable("instrprof failed to lower an mcdc condbitmap update"); 7568 case Intrinsic::localescape: { 7569 MachineFunction &MF = DAG.getMachineFunction(); 7570 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7571 7572 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7573 // is the same on all targets. 7574 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7575 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7576 if (isa<ConstantPointerNull>(Arg)) 7577 continue; // Skip null pointers. They represent a hole in index space. 7578 AllocaInst *Slot = cast<AllocaInst>(Arg); 7579 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7580 "can only escape static allocas"); 7581 int FI = FuncInfo.StaticAllocaMap[Slot]; 7582 MCSymbol *FrameAllocSym = 7583 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7584 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7585 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7586 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7587 .addSym(FrameAllocSym) 7588 .addFrameIndex(FI); 7589 } 7590 7591 return; 7592 } 7593 7594 case Intrinsic::localrecover: { 7595 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7596 MachineFunction &MF = DAG.getMachineFunction(); 7597 7598 // Get the symbol that defines the frame offset. 7599 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7600 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7601 unsigned IdxVal = 7602 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7603 MCSymbol *FrameAllocSym = 7604 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7605 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7606 7607 Value *FP = I.getArgOperand(1); 7608 SDValue FPVal = getValue(FP); 7609 EVT PtrVT = FPVal.getValueType(); 7610 7611 // Create a MCSymbol for the label to avoid any target lowering 7612 // that would make this PC relative. 7613 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7614 SDValue OffsetVal = 7615 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7616 7617 // Add the offset to the FP. 7618 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7619 setValue(&I, Add); 7620 7621 return; 7622 } 7623 7624 case Intrinsic::eh_exceptionpointer: 7625 case Intrinsic::eh_exceptioncode: { 7626 // Get the exception pointer vreg, copy from it, and resize it to fit. 7627 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7628 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7629 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7630 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7631 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7632 if (Intrinsic == Intrinsic::eh_exceptioncode) 7633 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7634 setValue(&I, N); 7635 return; 7636 } 7637 case Intrinsic::xray_customevent: { 7638 // Here we want to make sure that the intrinsic behaves as if it has a 7639 // specific calling convention. 7640 const auto &Triple = DAG.getTarget().getTargetTriple(); 7641 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7642 return; 7643 7644 SmallVector<SDValue, 8> Ops; 7645 7646 // We want to say that we always want the arguments in registers. 7647 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7648 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7649 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7650 SDValue Chain = getRoot(); 7651 Ops.push_back(LogEntryVal); 7652 Ops.push_back(StrSizeVal); 7653 Ops.push_back(Chain); 7654 7655 // We need to enforce the calling convention for the callsite, so that 7656 // argument ordering is enforced correctly, and that register allocation can 7657 // see that some registers may be assumed clobbered and have to preserve 7658 // them across calls to the intrinsic. 7659 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7660 sdl, NodeTys, Ops); 7661 SDValue patchableNode = SDValue(MN, 0); 7662 DAG.setRoot(patchableNode); 7663 setValue(&I, patchableNode); 7664 return; 7665 } 7666 case Intrinsic::xray_typedevent: { 7667 // Here we want to make sure that the intrinsic behaves as if it has a 7668 // specific calling convention. 7669 const auto &Triple = DAG.getTarget().getTargetTriple(); 7670 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7671 return; 7672 7673 SmallVector<SDValue, 8> Ops; 7674 7675 // We want to say that we always want the arguments in registers. 7676 // It's unclear to me how manipulating the selection DAG here forces callers 7677 // to provide arguments in registers instead of on the stack. 7678 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7679 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7680 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7681 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7682 SDValue Chain = getRoot(); 7683 Ops.push_back(LogTypeId); 7684 Ops.push_back(LogEntryVal); 7685 Ops.push_back(StrSizeVal); 7686 Ops.push_back(Chain); 7687 7688 // We need to enforce the calling convention for the callsite, so that 7689 // argument ordering is enforced correctly, and that register allocation can 7690 // see that some registers may be assumed clobbered and have to preserve 7691 // them across calls to the intrinsic. 7692 MachineSDNode *MN = DAG.getMachineNode( 7693 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7694 SDValue patchableNode = SDValue(MN, 0); 7695 DAG.setRoot(patchableNode); 7696 setValue(&I, patchableNode); 7697 return; 7698 } 7699 case Intrinsic::experimental_deoptimize: 7700 LowerDeoptimizeCall(&I); 7701 return; 7702 case Intrinsic::experimental_stepvector: 7703 visitStepVector(I); 7704 return; 7705 case Intrinsic::vector_reduce_fadd: 7706 case Intrinsic::vector_reduce_fmul: 7707 case Intrinsic::vector_reduce_add: 7708 case Intrinsic::vector_reduce_mul: 7709 case Intrinsic::vector_reduce_and: 7710 case Intrinsic::vector_reduce_or: 7711 case Intrinsic::vector_reduce_xor: 7712 case Intrinsic::vector_reduce_smax: 7713 case Intrinsic::vector_reduce_smin: 7714 case Intrinsic::vector_reduce_umax: 7715 case Intrinsic::vector_reduce_umin: 7716 case Intrinsic::vector_reduce_fmax: 7717 case Intrinsic::vector_reduce_fmin: 7718 case Intrinsic::vector_reduce_fmaximum: 7719 case Intrinsic::vector_reduce_fminimum: 7720 visitVectorReduce(I, Intrinsic); 7721 return; 7722 7723 case Intrinsic::icall_branch_funnel: { 7724 SmallVector<SDValue, 16> Ops; 7725 Ops.push_back(getValue(I.getArgOperand(0))); 7726 7727 int64_t Offset; 7728 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7729 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7730 if (!Base) 7731 report_fatal_error( 7732 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7733 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7734 7735 struct BranchFunnelTarget { 7736 int64_t Offset; 7737 SDValue Target; 7738 }; 7739 SmallVector<BranchFunnelTarget, 8> Targets; 7740 7741 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7742 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7743 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7744 if (ElemBase != Base) 7745 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7746 "to the same GlobalValue"); 7747 7748 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7749 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7750 if (!GA) 7751 report_fatal_error( 7752 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7753 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7754 GA->getGlobal(), sdl, Val.getValueType(), 7755 GA->getOffset())}); 7756 } 7757 llvm::sort(Targets, 7758 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7759 return T1.Offset < T2.Offset; 7760 }); 7761 7762 for (auto &T : Targets) { 7763 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7764 Ops.push_back(T.Target); 7765 } 7766 7767 Ops.push_back(DAG.getRoot()); // Chain 7768 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7769 MVT::Other, Ops), 7770 0); 7771 DAG.setRoot(N); 7772 setValue(&I, N); 7773 HasTailCall = true; 7774 return; 7775 } 7776 7777 case Intrinsic::wasm_landingpad_index: 7778 // Information this intrinsic contained has been transferred to 7779 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7780 // delete it now. 7781 return; 7782 7783 case Intrinsic::aarch64_settag: 7784 case Intrinsic::aarch64_settag_zero: { 7785 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7786 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7787 SDValue Val = TSI.EmitTargetCodeForSetTag( 7788 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7789 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7790 ZeroMemory); 7791 DAG.setRoot(Val); 7792 setValue(&I, Val); 7793 return; 7794 } 7795 case Intrinsic::amdgcn_cs_chain: { 7796 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7797 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7798 "Non-zero flags not supported yet"); 7799 7800 // At this point we don't care if it's amdgpu_cs_chain or 7801 // amdgpu_cs_chain_preserve. 7802 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7803 7804 Type *RetTy = I.getType(); 7805 assert(RetTy->isVoidTy() && "Should not return"); 7806 7807 SDValue Callee = getValue(I.getOperand(0)); 7808 7809 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7810 // We'll also tack the value of the EXEC mask at the end. 7811 TargetLowering::ArgListTy Args; 7812 Args.reserve(3); 7813 7814 for (unsigned Idx : {2, 3, 1}) { 7815 TargetLowering::ArgListEntry Arg; 7816 Arg.Node = getValue(I.getOperand(Idx)); 7817 Arg.Ty = I.getOperand(Idx)->getType(); 7818 Arg.setAttributes(&I, Idx); 7819 Args.push_back(Arg); 7820 } 7821 7822 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7823 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7824 Args[2].IsInReg = true; // EXEC should be inreg 7825 7826 TargetLowering::CallLoweringInfo CLI(DAG); 7827 CLI.setDebugLoc(getCurSDLoc()) 7828 .setChain(getRoot()) 7829 .setCallee(CC, RetTy, Callee, std::move(Args)) 7830 .setNoReturn(true) 7831 .setTailCall(true) 7832 .setConvergent(I.isConvergent()); 7833 CLI.CB = &I; 7834 std::pair<SDValue, SDValue> Result = 7835 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7836 (void)Result; 7837 assert(!Result.first.getNode() && !Result.second.getNode() && 7838 "Should've lowered as tail call"); 7839 7840 HasTailCall = true; 7841 return; 7842 } 7843 case Intrinsic::ptrmask: { 7844 SDValue Ptr = getValue(I.getOperand(0)); 7845 SDValue Mask = getValue(I.getOperand(1)); 7846 7847 // On arm64_32, pointers are 32 bits when stored in memory, but 7848 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to 7849 // match the index type, but the pointer is 64 bits, so the the mask must be 7850 // zero-extended up to 64 bits to match the pointer. 7851 EVT PtrVT = 7852 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 7853 EVT MemVT = 7854 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 7855 assert(PtrVT == Ptr.getValueType()); 7856 assert(MemVT == Mask.getValueType()); 7857 if (MemVT != PtrVT) 7858 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT); 7859 7860 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7861 return; 7862 } 7863 case Intrinsic::threadlocal_address: { 7864 setValue(&I, getValue(I.getOperand(0))); 7865 return; 7866 } 7867 case Intrinsic::get_active_lane_mask: { 7868 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7869 SDValue Index = getValue(I.getOperand(0)); 7870 EVT ElementVT = Index.getValueType(); 7871 7872 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7873 visitTargetIntrinsic(I, Intrinsic); 7874 return; 7875 } 7876 7877 SDValue TripCount = getValue(I.getOperand(1)); 7878 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7879 CCVT.getVectorElementCount()); 7880 7881 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7882 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7883 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7884 SDValue VectorInduction = DAG.getNode( 7885 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7886 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7887 VectorTripCount, ISD::CondCode::SETULT); 7888 setValue(&I, SetCC); 7889 return; 7890 } 7891 case Intrinsic::experimental_get_vector_length: { 7892 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7893 "Expected positive VF"); 7894 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7895 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7896 7897 SDValue Count = getValue(I.getOperand(0)); 7898 EVT CountVT = Count.getValueType(); 7899 7900 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7901 visitTargetIntrinsic(I, Intrinsic); 7902 return; 7903 } 7904 7905 // Expand to a umin between the trip count and the maximum elements the type 7906 // can hold. 7907 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7908 7909 // Extend the trip count to at least the result VT. 7910 if (CountVT.bitsLT(VT)) { 7911 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7912 CountVT = VT; 7913 } 7914 7915 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7916 ElementCount::get(VF, IsScalable)); 7917 7918 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7919 // Clip to the result type if needed. 7920 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7921 7922 setValue(&I, Trunc); 7923 return; 7924 } 7925 case Intrinsic::experimental_cttz_elts: { 7926 auto DL = getCurSDLoc(); 7927 SDValue Op = getValue(I.getOperand(0)); 7928 EVT OpVT = Op.getValueType(); 7929 7930 if (!TLI.shouldExpandCttzElements(OpVT)) { 7931 visitTargetIntrinsic(I, Intrinsic); 7932 return; 7933 } 7934 7935 if (OpVT.getScalarType() != MVT::i1) { 7936 // Compare the input vector elements to zero & use to count trailing zeros 7937 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 7938 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 7939 OpVT.getVectorElementCount()); 7940 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 7941 } 7942 7943 // If the zero-is-poison flag is set, we can assume the upper limit 7944 // of the result is VF-1. 7945 bool ZeroIsPoison = 7946 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero(); 7947 ConstantRange VScaleRange(1, true); // Dummy value. 7948 if (isa<ScalableVectorType>(I.getOperand(0)->getType())) 7949 VScaleRange = getVScaleRange(I.getCaller(), 64); 7950 unsigned EltWidth = TLI.getBitWidthForCttzElements( 7951 I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange); 7952 7953 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 7954 7955 // Create the new vector type & get the vector length 7956 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 7957 OpVT.getVectorElementCount()); 7958 7959 SDValue VL = 7960 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 7961 7962 SDValue StepVec = DAG.getStepVector(DL, NewVT); 7963 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 7964 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 7965 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 7966 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 7967 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 7968 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 7969 7970 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7971 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 7972 7973 setValue(&I, Ret); 7974 return; 7975 } 7976 case Intrinsic::vector_insert: { 7977 SDValue Vec = getValue(I.getOperand(0)); 7978 SDValue SubVec = getValue(I.getOperand(1)); 7979 SDValue Index = getValue(I.getOperand(2)); 7980 7981 // The intrinsic's index type is i64, but the SDNode requires an index type 7982 // suitable for the target. Convert the index as required. 7983 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7984 if (Index.getValueType() != VectorIdxTy) 7985 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7986 7987 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7988 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7989 Index)); 7990 return; 7991 } 7992 case Intrinsic::vector_extract: { 7993 SDValue Vec = getValue(I.getOperand(0)); 7994 SDValue Index = getValue(I.getOperand(1)); 7995 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7996 7997 // The intrinsic's index type is i64, but the SDNode requires an index type 7998 // suitable for the target. Convert the index as required. 7999 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8000 if (Index.getValueType() != VectorIdxTy) 8001 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 8002 8003 setValue(&I, 8004 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 8005 return; 8006 } 8007 case Intrinsic::vector_reverse: 8008 visitVectorReverse(I); 8009 return; 8010 case Intrinsic::vector_splice: 8011 visitVectorSplice(I); 8012 return; 8013 case Intrinsic::callbr_landingpad: 8014 visitCallBrLandingPad(I); 8015 return; 8016 case Intrinsic::vector_interleave2: 8017 visitVectorInterleave(I); 8018 return; 8019 case Intrinsic::vector_deinterleave2: 8020 visitVectorDeinterleave(I); 8021 return; 8022 case Intrinsic::experimental_convergence_anchor: 8023 case Intrinsic::experimental_convergence_entry: 8024 case Intrinsic::experimental_convergence_loop: 8025 visitConvergenceControl(I, Intrinsic); 8026 return; 8027 case Intrinsic::experimental_vector_histogram_add: { 8028 visitVectorHistogram(I, Intrinsic); 8029 return; 8030 } 8031 } 8032 } 8033 8034 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 8035 const ConstrainedFPIntrinsic &FPI) { 8036 SDLoc sdl = getCurSDLoc(); 8037 8038 // We do not need to serialize constrained FP intrinsics against 8039 // each other or against (nonvolatile) loads, so they can be 8040 // chained like loads. 8041 SDValue Chain = DAG.getRoot(); 8042 SmallVector<SDValue, 4> Opers; 8043 Opers.push_back(Chain); 8044 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I) 8045 Opers.push_back(getValue(FPI.getArgOperand(I))); 8046 8047 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 8048 assert(Result.getNode()->getNumValues() == 2); 8049 8050 // Push node to the appropriate list so that future instructions can be 8051 // chained up correctly. 8052 SDValue OutChain = Result.getValue(1); 8053 switch (EB) { 8054 case fp::ExceptionBehavior::ebIgnore: 8055 // The only reason why ebIgnore nodes still need to be chained is that 8056 // they might depend on the current rounding mode, and therefore must 8057 // not be moved across instruction that may change that mode. 8058 [[fallthrough]]; 8059 case fp::ExceptionBehavior::ebMayTrap: 8060 // These must not be moved across calls or instructions that may change 8061 // floating-point exception masks. 8062 PendingConstrainedFP.push_back(OutChain); 8063 break; 8064 case fp::ExceptionBehavior::ebStrict: 8065 // These must not be moved across calls or instructions that may change 8066 // floating-point exception masks or read floating-point exception flags. 8067 // In addition, they cannot be optimized out even if unused. 8068 PendingConstrainedFPStrict.push_back(OutChain); 8069 break; 8070 } 8071 }; 8072 8073 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8074 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 8075 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 8076 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 8077 8078 SDNodeFlags Flags; 8079 if (EB == fp::ExceptionBehavior::ebIgnore) 8080 Flags.setNoFPExcept(true); 8081 8082 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 8083 Flags.copyFMF(*FPOp); 8084 8085 unsigned Opcode; 8086 switch (FPI.getIntrinsicID()) { 8087 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8088 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8089 case Intrinsic::INTRINSIC: \ 8090 Opcode = ISD::STRICT_##DAGN; \ 8091 break; 8092 #include "llvm/IR/ConstrainedOps.def" 8093 case Intrinsic::experimental_constrained_fmuladd: { 8094 Opcode = ISD::STRICT_FMA; 8095 // Break fmuladd into fmul and fadd. 8096 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 8097 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 8098 Opers.pop_back(); 8099 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 8100 pushOutChain(Mul, EB); 8101 Opcode = ISD::STRICT_FADD; 8102 Opers.clear(); 8103 Opers.push_back(Mul.getValue(1)); 8104 Opers.push_back(Mul.getValue(0)); 8105 Opers.push_back(getValue(FPI.getArgOperand(2))); 8106 } 8107 break; 8108 } 8109 } 8110 8111 // A few strict DAG nodes carry additional operands that are not 8112 // set up by the default code above. 8113 switch (Opcode) { 8114 default: break; 8115 case ISD::STRICT_FP_ROUND: 8116 Opers.push_back( 8117 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 8118 break; 8119 case ISD::STRICT_FSETCC: 8120 case ISD::STRICT_FSETCCS: { 8121 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 8122 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 8123 if (TM.Options.NoNaNsFPMath) 8124 Condition = getFCmpCodeWithoutNaN(Condition); 8125 Opers.push_back(DAG.getCondCode(Condition)); 8126 break; 8127 } 8128 } 8129 8130 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 8131 pushOutChain(Result, EB); 8132 8133 SDValue FPResult = Result.getValue(0); 8134 setValue(&FPI, FPResult); 8135 } 8136 8137 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 8138 std::optional<unsigned> ResOPC; 8139 switch (VPIntrin.getIntrinsicID()) { 8140 case Intrinsic::vp_ctlz: { 8141 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8142 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 8143 break; 8144 } 8145 case Intrinsic::vp_cttz: { 8146 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8147 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 8148 break; 8149 } 8150 case Intrinsic::vp_cttz_elts: { 8151 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8152 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS; 8153 break; 8154 } 8155 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 8156 case Intrinsic::VPID: \ 8157 ResOPC = ISD::VPSD; \ 8158 break; 8159 #include "llvm/IR/VPIntrinsics.def" 8160 } 8161 8162 if (!ResOPC) 8163 llvm_unreachable( 8164 "Inconsistency: no SDNode available for this VPIntrinsic!"); 8165 8166 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 8167 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 8168 if (VPIntrin.getFastMathFlags().allowReassoc()) 8169 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 8170 : ISD::VP_REDUCE_FMUL; 8171 } 8172 8173 return *ResOPC; 8174 } 8175 8176 void SelectionDAGBuilder::visitVPLoad( 8177 const VPIntrinsic &VPIntrin, EVT VT, 8178 const SmallVectorImpl<SDValue> &OpValues) { 8179 SDLoc DL = getCurSDLoc(); 8180 Value *PtrOperand = VPIntrin.getArgOperand(0); 8181 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8182 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8183 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8184 SDValue LD; 8185 // Do not serialize variable-length loads of constant memory with 8186 // anything. 8187 if (!Alignment) 8188 Alignment = DAG.getEVTAlign(VT); 8189 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8190 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8191 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8192 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8193 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8194 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8195 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 8196 MMO, false /*IsExpanding */); 8197 if (AddToChain) 8198 PendingLoads.push_back(LD.getValue(1)); 8199 setValue(&VPIntrin, LD); 8200 } 8201 8202 void SelectionDAGBuilder::visitVPGather( 8203 const VPIntrinsic &VPIntrin, EVT VT, 8204 const SmallVectorImpl<SDValue> &OpValues) { 8205 SDLoc DL = getCurSDLoc(); 8206 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8207 Value *PtrOperand = VPIntrin.getArgOperand(0); 8208 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8209 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8210 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8211 SDValue LD; 8212 if (!Alignment) 8213 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8214 unsigned AS = 8215 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8216 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8217 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8218 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8219 SDValue Base, Index, Scale; 8220 ISD::MemIndexType IndexType; 8221 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8222 this, VPIntrin.getParent(), 8223 VT.getScalarStoreSize()); 8224 if (!UniformBase) { 8225 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8226 Index = getValue(PtrOperand); 8227 IndexType = ISD::SIGNED_SCALED; 8228 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8229 } 8230 EVT IdxVT = Index.getValueType(); 8231 EVT EltTy = IdxVT.getVectorElementType(); 8232 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8233 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8234 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8235 } 8236 LD = DAG.getGatherVP( 8237 DAG.getVTList(VT, MVT::Other), VT, DL, 8238 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 8239 IndexType); 8240 PendingLoads.push_back(LD.getValue(1)); 8241 setValue(&VPIntrin, LD); 8242 } 8243 8244 void SelectionDAGBuilder::visitVPStore( 8245 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8246 SDLoc DL = getCurSDLoc(); 8247 Value *PtrOperand = VPIntrin.getArgOperand(1); 8248 EVT VT = OpValues[0].getValueType(); 8249 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8250 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8251 SDValue ST; 8252 if (!Alignment) 8253 Alignment = DAG.getEVTAlign(VT); 8254 SDValue Ptr = OpValues[1]; 8255 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 8256 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8257 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8258 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8259 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 8260 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 8261 /* IsTruncating */ false, /*IsCompressing*/ false); 8262 DAG.setRoot(ST); 8263 setValue(&VPIntrin, ST); 8264 } 8265 8266 void SelectionDAGBuilder::visitVPScatter( 8267 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8268 SDLoc DL = getCurSDLoc(); 8269 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8270 Value *PtrOperand = VPIntrin.getArgOperand(1); 8271 EVT VT = OpValues[0].getValueType(); 8272 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8273 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8274 SDValue ST; 8275 if (!Alignment) 8276 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8277 unsigned AS = 8278 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8279 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8280 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8281 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8282 SDValue Base, Index, Scale; 8283 ISD::MemIndexType IndexType; 8284 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8285 this, VPIntrin.getParent(), 8286 VT.getScalarStoreSize()); 8287 if (!UniformBase) { 8288 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8289 Index = getValue(PtrOperand); 8290 IndexType = ISD::SIGNED_SCALED; 8291 Scale = 8292 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8293 } 8294 EVT IdxVT = Index.getValueType(); 8295 EVT EltTy = IdxVT.getVectorElementType(); 8296 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8297 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8298 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8299 } 8300 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8301 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8302 OpValues[2], OpValues[3]}, 8303 MMO, IndexType); 8304 DAG.setRoot(ST); 8305 setValue(&VPIntrin, ST); 8306 } 8307 8308 void SelectionDAGBuilder::visitVPStridedLoad( 8309 const VPIntrinsic &VPIntrin, EVT VT, 8310 const SmallVectorImpl<SDValue> &OpValues) { 8311 SDLoc DL = getCurSDLoc(); 8312 Value *PtrOperand = VPIntrin.getArgOperand(0); 8313 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8314 if (!Alignment) 8315 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8316 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8317 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8318 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8319 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8320 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8321 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8322 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8323 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8324 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8325 8326 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8327 OpValues[2], OpValues[3], MMO, 8328 false /*IsExpanding*/); 8329 8330 if (AddToChain) 8331 PendingLoads.push_back(LD.getValue(1)); 8332 setValue(&VPIntrin, LD); 8333 } 8334 8335 void SelectionDAGBuilder::visitVPStridedStore( 8336 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8337 SDLoc DL = getCurSDLoc(); 8338 Value *PtrOperand = VPIntrin.getArgOperand(1); 8339 EVT VT = OpValues[0].getValueType(); 8340 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8341 if (!Alignment) 8342 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8343 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8344 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8345 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8346 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8347 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8348 8349 SDValue ST = DAG.getStridedStoreVP( 8350 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8351 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8352 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8353 /*IsCompressing*/ false); 8354 8355 DAG.setRoot(ST); 8356 setValue(&VPIntrin, ST); 8357 } 8358 8359 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8360 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8361 SDLoc DL = getCurSDLoc(); 8362 8363 ISD::CondCode Condition; 8364 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8365 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8366 if (IsFP) { 8367 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8368 // flags, but calls that don't return floating-point types can't be 8369 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8370 Condition = getFCmpCondCode(CondCode); 8371 if (TM.Options.NoNaNsFPMath) 8372 Condition = getFCmpCodeWithoutNaN(Condition); 8373 } else { 8374 Condition = getICmpCondCode(CondCode); 8375 } 8376 8377 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8378 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8379 // #2 is the condition code 8380 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8381 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8382 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8383 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8384 "Unexpected target EVL type"); 8385 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8386 8387 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8388 VPIntrin.getType()); 8389 setValue(&VPIntrin, 8390 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8391 } 8392 8393 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8394 const VPIntrinsic &VPIntrin) { 8395 SDLoc DL = getCurSDLoc(); 8396 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8397 8398 auto IID = VPIntrin.getIntrinsicID(); 8399 8400 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8401 return visitVPCmp(*CmpI); 8402 8403 SmallVector<EVT, 4> ValueVTs; 8404 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8405 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8406 SDVTList VTs = DAG.getVTList(ValueVTs); 8407 8408 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8409 8410 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8411 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8412 "Unexpected target EVL type"); 8413 8414 // Request operands. 8415 SmallVector<SDValue, 7> OpValues; 8416 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8417 auto Op = getValue(VPIntrin.getArgOperand(I)); 8418 if (I == EVLParamPos) 8419 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8420 OpValues.push_back(Op); 8421 } 8422 8423 switch (Opcode) { 8424 default: { 8425 SDNodeFlags SDFlags; 8426 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8427 SDFlags.copyFMF(*FPMO); 8428 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8429 setValue(&VPIntrin, Result); 8430 break; 8431 } 8432 case ISD::VP_LOAD: 8433 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8434 break; 8435 case ISD::VP_GATHER: 8436 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8437 break; 8438 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8439 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8440 break; 8441 case ISD::VP_STORE: 8442 visitVPStore(VPIntrin, OpValues); 8443 break; 8444 case ISD::VP_SCATTER: 8445 visitVPScatter(VPIntrin, OpValues); 8446 break; 8447 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8448 visitVPStridedStore(VPIntrin, OpValues); 8449 break; 8450 case ISD::VP_FMULADD: { 8451 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8452 SDNodeFlags SDFlags; 8453 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8454 SDFlags.copyFMF(*FPMO); 8455 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8456 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8457 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8458 } else { 8459 SDValue Mul = DAG.getNode( 8460 ISD::VP_FMUL, DL, VTs, 8461 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8462 SDValue Add = 8463 DAG.getNode(ISD::VP_FADD, DL, VTs, 8464 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8465 setValue(&VPIntrin, Add); 8466 } 8467 break; 8468 } 8469 case ISD::VP_IS_FPCLASS: { 8470 const DataLayout DLayout = DAG.getDataLayout(); 8471 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8472 auto Constant = OpValues[1]->getAsZExtVal(); 8473 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8474 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8475 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8476 setValue(&VPIntrin, V); 8477 return; 8478 } 8479 case ISD::VP_INTTOPTR: { 8480 SDValue N = OpValues[0]; 8481 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8482 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8483 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8484 OpValues[2]); 8485 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8486 OpValues[2]); 8487 setValue(&VPIntrin, N); 8488 break; 8489 } 8490 case ISD::VP_PTRTOINT: { 8491 SDValue N = OpValues[0]; 8492 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8493 VPIntrin.getType()); 8494 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8495 VPIntrin.getOperand(0)->getType()); 8496 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8497 OpValues[2]); 8498 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8499 OpValues[2]); 8500 setValue(&VPIntrin, N); 8501 break; 8502 } 8503 case ISD::VP_ABS: 8504 case ISD::VP_CTLZ: 8505 case ISD::VP_CTLZ_ZERO_UNDEF: 8506 case ISD::VP_CTTZ: 8507 case ISD::VP_CTTZ_ZERO_UNDEF: 8508 case ISD::VP_CTTZ_ELTS_ZERO_UNDEF: 8509 case ISD::VP_CTTZ_ELTS: { 8510 SDValue Result = 8511 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8512 setValue(&VPIntrin, Result); 8513 break; 8514 } 8515 } 8516 } 8517 8518 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8519 const BasicBlock *EHPadBB, 8520 MCSymbol *&BeginLabel) { 8521 MachineFunction &MF = DAG.getMachineFunction(); 8522 MachineModuleInfo &MMI = MF.getMMI(); 8523 8524 // Insert a label before the invoke call to mark the try range. This can be 8525 // used to detect deletion of the invoke via the MachineModuleInfo. 8526 BeginLabel = MMI.getContext().createTempSymbol(); 8527 8528 // For SjLj, keep track of which landing pads go with which invokes 8529 // so as to maintain the ordering of pads in the LSDA. 8530 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 8531 if (CallSiteIndex) { 8532 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8533 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 8534 8535 // Now that the call site is handled, stop tracking it. 8536 MMI.setCurrentCallSite(0); 8537 } 8538 8539 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8540 } 8541 8542 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8543 const BasicBlock *EHPadBB, 8544 MCSymbol *BeginLabel) { 8545 assert(BeginLabel && "BeginLabel should've been set"); 8546 8547 MachineFunction &MF = DAG.getMachineFunction(); 8548 MachineModuleInfo &MMI = MF.getMMI(); 8549 8550 // Insert a label at the end of the invoke call to mark the try range. This 8551 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8552 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8553 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8554 8555 // Inform MachineModuleInfo of range. 8556 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8557 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8558 // actually use outlined funclets and their LSDA info style. 8559 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8560 assert(II && "II should've been set"); 8561 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8562 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8563 } else if (!isScopedEHPersonality(Pers)) { 8564 assert(EHPadBB); 8565 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8566 } 8567 8568 return Chain; 8569 } 8570 8571 std::pair<SDValue, SDValue> 8572 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8573 const BasicBlock *EHPadBB) { 8574 MCSymbol *BeginLabel = nullptr; 8575 8576 if (EHPadBB) { 8577 // Both PendingLoads and PendingExports must be flushed here; 8578 // this call might not return. 8579 (void)getRoot(); 8580 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8581 CLI.setChain(getRoot()); 8582 } 8583 8584 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8585 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8586 8587 assert((CLI.IsTailCall || Result.second.getNode()) && 8588 "Non-null chain expected with non-tail call!"); 8589 assert((Result.second.getNode() || !Result.first.getNode()) && 8590 "Null value expected with tail call!"); 8591 8592 if (!Result.second.getNode()) { 8593 // As a special case, a null chain means that a tail call has been emitted 8594 // and the DAG root is already updated. 8595 HasTailCall = true; 8596 8597 // Since there's no actual continuation from this block, nothing can be 8598 // relying on us setting vregs for them. 8599 PendingExports.clear(); 8600 } else { 8601 DAG.setRoot(Result.second); 8602 } 8603 8604 if (EHPadBB) { 8605 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8606 BeginLabel)); 8607 } 8608 8609 return Result; 8610 } 8611 8612 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8613 bool isTailCall, bool isMustTailCall, 8614 const BasicBlock *EHPadBB, 8615 const TargetLowering::PtrAuthInfo *PAI) { 8616 auto &DL = DAG.getDataLayout(); 8617 FunctionType *FTy = CB.getFunctionType(); 8618 Type *RetTy = CB.getType(); 8619 8620 TargetLowering::ArgListTy Args; 8621 Args.reserve(CB.arg_size()); 8622 8623 const Value *SwiftErrorVal = nullptr; 8624 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8625 8626 if (isTailCall) { 8627 // Avoid emitting tail calls in functions with the disable-tail-calls 8628 // attribute. 8629 auto *Caller = CB.getParent()->getParent(); 8630 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8631 "true" && !isMustTailCall) 8632 isTailCall = false; 8633 8634 // We can't tail call inside a function with a swifterror argument. Lowering 8635 // does not support this yet. It would have to move into the swifterror 8636 // register before the call. 8637 if (TLI.supportSwiftError() && 8638 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8639 isTailCall = false; 8640 } 8641 8642 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8643 TargetLowering::ArgListEntry Entry; 8644 const Value *V = *I; 8645 8646 // Skip empty types 8647 if (V->getType()->isEmptyTy()) 8648 continue; 8649 8650 SDValue ArgNode = getValue(V); 8651 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8652 8653 Entry.setAttributes(&CB, I - CB.arg_begin()); 8654 8655 // Use swifterror virtual register as input to the call. 8656 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8657 SwiftErrorVal = V; 8658 // We find the virtual register for the actual swifterror argument. 8659 // Instead of using the Value, we use the virtual register instead. 8660 Entry.Node = 8661 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8662 EVT(TLI.getPointerTy(DL))); 8663 } 8664 8665 Args.push_back(Entry); 8666 8667 // If we have an explicit sret argument that is an Instruction, (i.e., it 8668 // might point to function-local memory), we can't meaningfully tail-call. 8669 if (Entry.IsSRet && isa<Instruction>(V)) 8670 isTailCall = false; 8671 } 8672 8673 // If call site has a cfguardtarget operand bundle, create and add an 8674 // additional ArgListEntry. 8675 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8676 TargetLowering::ArgListEntry Entry; 8677 Value *V = Bundle->Inputs[0]; 8678 SDValue ArgNode = getValue(V); 8679 Entry.Node = ArgNode; 8680 Entry.Ty = V->getType(); 8681 Entry.IsCFGuardTarget = true; 8682 Args.push_back(Entry); 8683 } 8684 8685 // Check if target-independent constraints permit a tail call here. 8686 // Target-dependent constraints are checked within TLI->LowerCallTo. 8687 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8688 isTailCall = false; 8689 8690 // Disable tail calls if there is an swifterror argument. Targets have not 8691 // been updated to support tail calls. 8692 if (TLI.supportSwiftError() && SwiftErrorVal) 8693 isTailCall = false; 8694 8695 ConstantInt *CFIType = nullptr; 8696 if (CB.isIndirectCall()) { 8697 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8698 if (!TLI.supportKCFIBundles()) 8699 report_fatal_error( 8700 "Target doesn't support calls with kcfi operand bundles."); 8701 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8702 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8703 } 8704 } 8705 8706 SDValue ConvControlToken; 8707 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) { 8708 auto *Token = Bundle->Inputs[0].get(); 8709 ConvControlToken = getValue(Token); 8710 } 8711 8712 TargetLowering::CallLoweringInfo CLI(DAG); 8713 CLI.setDebugLoc(getCurSDLoc()) 8714 .setChain(getRoot()) 8715 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8716 .setTailCall(isTailCall) 8717 .setConvergent(CB.isConvergent()) 8718 .setIsPreallocated( 8719 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8720 .setCFIType(CFIType) 8721 .setConvergenceControlToken(ConvControlToken); 8722 8723 // Set the pointer authentication info if we have it. 8724 if (PAI) { 8725 if (!TLI.supportPtrAuthBundles()) 8726 report_fatal_error( 8727 "This target doesn't support calls with ptrauth operand bundles."); 8728 CLI.setPtrAuth(*PAI); 8729 } 8730 8731 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8732 8733 if (Result.first.getNode()) { 8734 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8735 setValue(&CB, Result.first); 8736 } 8737 8738 // The last element of CLI.InVals has the SDValue for swifterror return. 8739 // Here we copy it to a virtual register and update SwiftErrorMap for 8740 // book-keeping. 8741 if (SwiftErrorVal && TLI.supportSwiftError()) { 8742 // Get the last element of InVals. 8743 SDValue Src = CLI.InVals.back(); 8744 Register VReg = 8745 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8746 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8747 DAG.setRoot(CopyNode); 8748 } 8749 } 8750 8751 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8752 SelectionDAGBuilder &Builder) { 8753 // Check to see if this load can be trivially constant folded, e.g. if the 8754 // input is from a string literal. 8755 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8756 // Cast pointer to the type we really want to load. 8757 Type *LoadTy = 8758 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8759 if (LoadVT.isVector()) 8760 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8761 8762 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8763 PointerType::getUnqual(LoadTy)); 8764 8765 if (const Constant *LoadCst = 8766 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8767 LoadTy, Builder.DAG.getDataLayout())) 8768 return Builder.getValue(LoadCst); 8769 } 8770 8771 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8772 // still constant memory, the input chain can be the entry node. 8773 SDValue Root; 8774 bool ConstantMemory = false; 8775 8776 // Do not serialize (non-volatile) loads of constant memory with anything. 8777 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8778 Root = Builder.DAG.getEntryNode(); 8779 ConstantMemory = true; 8780 } else { 8781 // Do not serialize non-volatile loads against each other. 8782 Root = Builder.DAG.getRoot(); 8783 } 8784 8785 SDValue Ptr = Builder.getValue(PtrVal); 8786 SDValue LoadVal = 8787 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8788 MachinePointerInfo(PtrVal), Align(1)); 8789 8790 if (!ConstantMemory) 8791 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8792 return LoadVal; 8793 } 8794 8795 /// Record the value for an instruction that produces an integer result, 8796 /// converting the type where necessary. 8797 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8798 SDValue Value, 8799 bool IsSigned) { 8800 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8801 I.getType(), true); 8802 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8803 setValue(&I, Value); 8804 } 8805 8806 /// See if we can lower a memcmp/bcmp 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::visitMemCmpBCmpCall(const CallInst &I) { 8812 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8813 const Value *Size = I.getArgOperand(2); 8814 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8815 if (CSize && CSize->getZExtValue() == 0) { 8816 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8817 I.getType(), true); 8818 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8819 return true; 8820 } 8821 8822 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8823 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8824 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8825 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8826 if (Res.first.getNode()) { 8827 processIntegerCallValue(I, Res.first, true); 8828 PendingLoads.push_back(Res.second); 8829 return true; 8830 } 8831 8832 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8833 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8834 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8835 return false; 8836 8837 // If the target has a fast compare for the given size, it will return a 8838 // preferred load type for that size. Require that the load VT is legal and 8839 // that the target supports unaligned loads of that type. Otherwise, return 8840 // INVALID. 8841 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8843 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8844 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8845 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8846 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8847 // TODO: Check alignment of src and dest ptrs. 8848 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8849 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8850 if (!TLI.isTypeLegal(LVT) || 8851 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8852 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8853 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8854 } 8855 8856 return LVT; 8857 }; 8858 8859 // This turns into unaligned loads. We only do this if the target natively 8860 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8861 // we'll only produce a small number of byte loads. 8862 MVT LoadVT; 8863 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8864 switch (NumBitsToCompare) { 8865 default: 8866 return false; 8867 case 16: 8868 LoadVT = MVT::i16; 8869 break; 8870 case 32: 8871 LoadVT = MVT::i32; 8872 break; 8873 case 64: 8874 case 128: 8875 case 256: 8876 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8877 break; 8878 } 8879 8880 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8881 return false; 8882 8883 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8884 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8885 8886 // Bitcast to a wide integer type if the loads are vectors. 8887 if (LoadVT.isVector()) { 8888 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8889 LoadL = DAG.getBitcast(CmpVT, LoadL); 8890 LoadR = DAG.getBitcast(CmpVT, LoadR); 8891 } 8892 8893 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8894 processIntegerCallValue(I, Cmp, false); 8895 return true; 8896 } 8897 8898 /// See if we can lower a memchr call into an optimized form. If so, return 8899 /// true and lower it. Otherwise return false, and it will be lowered like a 8900 /// normal call. 8901 /// The caller already checked that \p I calls the appropriate LibFunc with a 8902 /// correct prototype. 8903 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8904 const Value *Src = I.getArgOperand(0); 8905 const Value *Char = I.getArgOperand(1); 8906 const Value *Length = I.getArgOperand(2); 8907 8908 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8909 std::pair<SDValue, SDValue> Res = 8910 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8911 getValue(Src), getValue(Char), getValue(Length), 8912 MachinePointerInfo(Src)); 8913 if (Res.first.getNode()) { 8914 setValue(&I, Res.first); 8915 PendingLoads.push_back(Res.second); 8916 return true; 8917 } 8918 8919 return false; 8920 } 8921 8922 /// See if we can lower a mempcpy call into an optimized form. If so, return 8923 /// true and lower it. Otherwise return false, and it will be lowered like a 8924 /// normal call. 8925 /// The caller already checked that \p I calls the appropriate LibFunc with a 8926 /// correct prototype. 8927 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8928 SDValue Dst = getValue(I.getArgOperand(0)); 8929 SDValue Src = getValue(I.getArgOperand(1)); 8930 SDValue Size = getValue(I.getArgOperand(2)); 8931 8932 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8933 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8934 // DAG::getMemcpy needs Alignment to be defined. 8935 Align Alignment = std::min(DstAlign, SrcAlign); 8936 8937 SDLoc sdl = getCurSDLoc(); 8938 8939 // In the mempcpy context we need to pass in a false value for isTailCall 8940 // because the return pointer needs to be adjusted by the size of 8941 // the copied memory. 8942 SDValue Root = getMemoryRoot(); 8943 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8944 /*isTailCall=*/false, 8945 MachinePointerInfo(I.getArgOperand(0)), 8946 MachinePointerInfo(I.getArgOperand(1)), 8947 I.getAAMetadata()); 8948 assert(MC.getNode() != nullptr && 8949 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8950 DAG.setRoot(MC); 8951 8952 // Check if Size needs to be truncated or extended. 8953 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8954 8955 // Adjust return pointer to point just past the last dst byte. 8956 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8957 Dst, Size); 8958 setValue(&I, DstPlusSize); 8959 return true; 8960 } 8961 8962 /// See if we can lower a strcpy call into an optimized form. If so, return 8963 /// true and lower it, otherwise return false and it will be lowered like a 8964 /// normal call. 8965 /// The caller already checked that \p I calls the appropriate LibFunc with a 8966 /// correct prototype. 8967 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8968 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8969 8970 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8971 std::pair<SDValue, SDValue> Res = 8972 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8973 getValue(Arg0), getValue(Arg1), 8974 MachinePointerInfo(Arg0), 8975 MachinePointerInfo(Arg1), isStpcpy); 8976 if (Res.first.getNode()) { 8977 setValue(&I, Res.first); 8978 DAG.setRoot(Res.second); 8979 return true; 8980 } 8981 8982 return false; 8983 } 8984 8985 /// See if we can lower a strcmp call into an optimized form. If so, return 8986 /// true and lower it, otherwise return false and it will be lowered like a 8987 /// normal call. 8988 /// The caller already checked that \p I calls the appropriate LibFunc with a 8989 /// correct prototype. 8990 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8991 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8992 8993 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8994 std::pair<SDValue, SDValue> Res = 8995 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8996 getValue(Arg0), getValue(Arg1), 8997 MachinePointerInfo(Arg0), 8998 MachinePointerInfo(Arg1)); 8999 if (Res.first.getNode()) { 9000 processIntegerCallValue(I, Res.first, true); 9001 PendingLoads.push_back(Res.second); 9002 return true; 9003 } 9004 9005 return false; 9006 } 9007 9008 /// See if we can lower a strlen call into an optimized form. If so, return 9009 /// true and lower it, otherwise return false and it will be lowered like a 9010 /// normal call. 9011 /// The caller already checked that \p I calls the appropriate LibFunc with a 9012 /// correct prototype. 9013 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 9014 const Value *Arg0 = I.getArgOperand(0); 9015 9016 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9017 std::pair<SDValue, SDValue> Res = 9018 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 9019 getValue(Arg0), MachinePointerInfo(Arg0)); 9020 if (Res.first.getNode()) { 9021 processIntegerCallValue(I, Res.first, false); 9022 PendingLoads.push_back(Res.second); 9023 return true; 9024 } 9025 9026 return false; 9027 } 9028 9029 /// See if we can lower a strnlen call into an optimized form. If so, return 9030 /// true and lower it, otherwise return false and it will be lowered like a 9031 /// normal call. 9032 /// The caller already checked that \p I calls the appropriate LibFunc with a 9033 /// correct prototype. 9034 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 9035 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9036 9037 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9038 std::pair<SDValue, SDValue> Res = 9039 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 9040 getValue(Arg0), getValue(Arg1), 9041 MachinePointerInfo(Arg0)); 9042 if (Res.first.getNode()) { 9043 processIntegerCallValue(I, Res.first, false); 9044 PendingLoads.push_back(Res.second); 9045 return true; 9046 } 9047 9048 return false; 9049 } 9050 9051 /// See if we can lower a unary floating-point operation into an SDNode with 9052 /// the specified Opcode. If so, return true and lower it, otherwise return 9053 /// false and it will be lowered like a normal call. 9054 /// The caller already checked that \p I calls the appropriate LibFunc with a 9055 /// correct prototype. 9056 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 9057 unsigned Opcode) { 9058 // We already checked this call's prototype; verify it doesn't modify errno. 9059 if (!I.onlyReadsMemory()) 9060 return false; 9061 9062 SDNodeFlags Flags; 9063 Flags.copyFMF(cast<FPMathOperator>(I)); 9064 9065 SDValue Tmp = getValue(I.getArgOperand(0)); 9066 setValue(&I, 9067 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 9068 return true; 9069 } 9070 9071 /// See if we can lower a binary floating-point operation into an SDNode with 9072 /// the specified Opcode. If so, return true and lower it. Otherwise return 9073 /// false, and it will be lowered like a normal call. 9074 /// The caller already checked that \p I calls the appropriate LibFunc with a 9075 /// correct prototype. 9076 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 9077 unsigned Opcode) { 9078 // We already checked this call's prototype; verify it doesn't modify errno. 9079 if (!I.onlyReadsMemory()) 9080 return false; 9081 9082 SDNodeFlags Flags; 9083 Flags.copyFMF(cast<FPMathOperator>(I)); 9084 9085 SDValue Tmp0 = getValue(I.getArgOperand(0)); 9086 SDValue Tmp1 = getValue(I.getArgOperand(1)); 9087 EVT VT = Tmp0.getValueType(); 9088 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 9089 return true; 9090 } 9091 9092 void SelectionDAGBuilder::visitCall(const CallInst &I) { 9093 // Handle inline assembly differently. 9094 if (I.isInlineAsm()) { 9095 visitInlineAsm(I); 9096 return; 9097 } 9098 9099 diagnoseDontCall(I); 9100 9101 if (Function *F = I.getCalledFunction()) { 9102 if (F->isDeclaration()) { 9103 // Is this an LLVM intrinsic or a target-specific intrinsic? 9104 unsigned IID = F->getIntrinsicID(); 9105 if (!IID) 9106 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 9107 IID = II->getIntrinsicID(F); 9108 9109 if (IID) { 9110 visitIntrinsicCall(I, IID); 9111 return; 9112 } 9113 } 9114 9115 // Check for well-known libc/libm calls. If the function is internal, it 9116 // can't be a library call. Don't do the check if marked as nobuiltin for 9117 // some reason or the call site requires strict floating point semantics. 9118 LibFunc Func; 9119 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 9120 F->hasName() && LibInfo->getLibFunc(*F, Func) && 9121 LibInfo->hasOptimizedCodeGen(Func)) { 9122 switch (Func) { 9123 default: break; 9124 case LibFunc_bcmp: 9125 if (visitMemCmpBCmpCall(I)) 9126 return; 9127 break; 9128 case LibFunc_copysign: 9129 case LibFunc_copysignf: 9130 case LibFunc_copysignl: 9131 // We already checked this call's prototype; verify it doesn't modify 9132 // errno. 9133 if (I.onlyReadsMemory()) { 9134 SDValue LHS = getValue(I.getArgOperand(0)); 9135 SDValue RHS = getValue(I.getArgOperand(1)); 9136 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 9137 LHS.getValueType(), LHS, RHS)); 9138 return; 9139 } 9140 break; 9141 case LibFunc_fabs: 9142 case LibFunc_fabsf: 9143 case LibFunc_fabsl: 9144 if (visitUnaryFloatCall(I, ISD::FABS)) 9145 return; 9146 break; 9147 case LibFunc_fmin: 9148 case LibFunc_fminf: 9149 case LibFunc_fminl: 9150 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 9151 return; 9152 break; 9153 case LibFunc_fmax: 9154 case LibFunc_fmaxf: 9155 case LibFunc_fmaxl: 9156 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 9157 return; 9158 break; 9159 case LibFunc_sin: 9160 case LibFunc_sinf: 9161 case LibFunc_sinl: 9162 if (visitUnaryFloatCall(I, ISD::FSIN)) 9163 return; 9164 break; 9165 case LibFunc_cos: 9166 case LibFunc_cosf: 9167 case LibFunc_cosl: 9168 if (visitUnaryFloatCall(I, ISD::FCOS)) 9169 return; 9170 break; 9171 case LibFunc_sqrt: 9172 case LibFunc_sqrtf: 9173 case LibFunc_sqrtl: 9174 case LibFunc_sqrt_finite: 9175 case LibFunc_sqrtf_finite: 9176 case LibFunc_sqrtl_finite: 9177 if (visitUnaryFloatCall(I, ISD::FSQRT)) 9178 return; 9179 break; 9180 case LibFunc_floor: 9181 case LibFunc_floorf: 9182 case LibFunc_floorl: 9183 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 9184 return; 9185 break; 9186 case LibFunc_nearbyint: 9187 case LibFunc_nearbyintf: 9188 case LibFunc_nearbyintl: 9189 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 9190 return; 9191 break; 9192 case LibFunc_ceil: 9193 case LibFunc_ceilf: 9194 case LibFunc_ceill: 9195 if (visitUnaryFloatCall(I, ISD::FCEIL)) 9196 return; 9197 break; 9198 case LibFunc_rint: 9199 case LibFunc_rintf: 9200 case LibFunc_rintl: 9201 if (visitUnaryFloatCall(I, ISD::FRINT)) 9202 return; 9203 break; 9204 case LibFunc_round: 9205 case LibFunc_roundf: 9206 case LibFunc_roundl: 9207 if (visitUnaryFloatCall(I, ISD::FROUND)) 9208 return; 9209 break; 9210 case LibFunc_trunc: 9211 case LibFunc_truncf: 9212 case LibFunc_truncl: 9213 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 9214 return; 9215 break; 9216 case LibFunc_log2: 9217 case LibFunc_log2f: 9218 case LibFunc_log2l: 9219 if (visitUnaryFloatCall(I, ISD::FLOG2)) 9220 return; 9221 break; 9222 case LibFunc_exp2: 9223 case LibFunc_exp2f: 9224 case LibFunc_exp2l: 9225 if (visitUnaryFloatCall(I, ISD::FEXP2)) 9226 return; 9227 break; 9228 case LibFunc_exp10: 9229 case LibFunc_exp10f: 9230 case LibFunc_exp10l: 9231 if (visitUnaryFloatCall(I, ISD::FEXP10)) 9232 return; 9233 break; 9234 case LibFunc_ldexp: 9235 case LibFunc_ldexpf: 9236 case LibFunc_ldexpl: 9237 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 9238 return; 9239 break; 9240 case LibFunc_memcmp: 9241 if (visitMemCmpBCmpCall(I)) 9242 return; 9243 break; 9244 case LibFunc_mempcpy: 9245 if (visitMemPCpyCall(I)) 9246 return; 9247 break; 9248 case LibFunc_memchr: 9249 if (visitMemChrCall(I)) 9250 return; 9251 break; 9252 case LibFunc_strcpy: 9253 if (visitStrCpyCall(I, false)) 9254 return; 9255 break; 9256 case LibFunc_stpcpy: 9257 if (visitStrCpyCall(I, true)) 9258 return; 9259 break; 9260 case LibFunc_strcmp: 9261 if (visitStrCmpCall(I)) 9262 return; 9263 break; 9264 case LibFunc_strlen: 9265 if (visitStrLenCall(I)) 9266 return; 9267 break; 9268 case LibFunc_strnlen: 9269 if (visitStrNLenCall(I)) 9270 return; 9271 break; 9272 } 9273 } 9274 } 9275 9276 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 9277 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr); 9278 return; 9279 } 9280 9281 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9282 // have to do anything here to lower funclet bundles. 9283 // CFGuardTarget bundles are lowered in LowerCallTo. 9284 assert(!I.hasOperandBundlesOtherThan( 9285 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9286 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9287 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi, 9288 LLVMContext::OB_convergencectrl}) && 9289 "Cannot lower calls with arbitrary operand bundles!"); 9290 9291 SDValue Callee = getValue(I.getCalledOperand()); 9292 9293 if (I.hasDeoptState()) 9294 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9295 else 9296 // Check if we can potentially perform a tail call. More detailed checking 9297 // is be done within LowerCallTo, after more information about the call is 9298 // known. 9299 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9300 } 9301 9302 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle( 9303 const CallBase &CB, const BasicBlock *EHPadBB) { 9304 auto PAB = CB.getOperandBundle("ptrauth"); 9305 const Value *CalleeV = CB.getCalledOperand(); 9306 9307 // Gather the call ptrauth data from the operand bundle: 9308 // [ i32 <key>, i64 <discriminator> ] 9309 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]); 9310 const Value *Discriminator = PAB->Inputs[1]; 9311 9312 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key"); 9313 assert(Discriminator->getType()->isIntegerTy(64) && 9314 "Invalid ptrauth discriminator"); 9315 9316 // Functions should never be ptrauth-called directly. 9317 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call"); 9318 9319 // Otherwise, do an authenticated indirect call. 9320 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(), 9321 getValue(Discriminator)}; 9322 9323 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(), 9324 EHPadBB, &PAI); 9325 } 9326 9327 namespace { 9328 9329 /// AsmOperandInfo - This contains information for each constraint that we are 9330 /// lowering. 9331 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9332 public: 9333 /// CallOperand - If this is the result output operand or a clobber 9334 /// this is null, otherwise it is the incoming operand to the CallInst. 9335 /// This gets modified as the asm is processed. 9336 SDValue CallOperand; 9337 9338 /// AssignedRegs - If this is a register or register class operand, this 9339 /// contains the set of register corresponding to the operand. 9340 RegsForValue AssignedRegs; 9341 9342 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9343 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9344 } 9345 9346 /// Whether or not this operand accesses memory 9347 bool hasMemory(const TargetLowering &TLI) const { 9348 // Indirect operand accesses access memory. 9349 if (isIndirect) 9350 return true; 9351 9352 for (const auto &Code : Codes) 9353 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9354 return true; 9355 9356 return false; 9357 } 9358 }; 9359 9360 9361 } // end anonymous namespace 9362 9363 /// Make sure that the output operand \p OpInfo and its corresponding input 9364 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9365 /// out). 9366 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9367 SDISelAsmOperandInfo &MatchingOpInfo, 9368 SelectionDAG &DAG) { 9369 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9370 return; 9371 9372 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9373 const auto &TLI = DAG.getTargetLoweringInfo(); 9374 9375 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9376 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9377 OpInfo.ConstraintVT); 9378 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9379 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9380 MatchingOpInfo.ConstraintVT); 9381 if ((OpInfo.ConstraintVT.isInteger() != 9382 MatchingOpInfo.ConstraintVT.isInteger()) || 9383 (MatchRC.second != InputRC.second)) { 9384 // FIXME: error out in a more elegant fashion 9385 report_fatal_error("Unsupported asm: input constraint" 9386 " with a matching output constraint of" 9387 " incompatible type!"); 9388 } 9389 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9390 } 9391 9392 /// Get a direct memory input to behave well as an indirect operand. 9393 /// This may introduce stores, hence the need for a \p Chain. 9394 /// \return The (possibly updated) chain. 9395 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9396 SDISelAsmOperandInfo &OpInfo, 9397 SelectionDAG &DAG) { 9398 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9399 9400 // If we don't have an indirect input, put it in the constpool if we can, 9401 // otherwise spill it to a stack slot. 9402 // TODO: This isn't quite right. We need to handle these according to 9403 // the addressing mode that the constraint wants. Also, this may take 9404 // an additional register for the computation and we don't want that 9405 // either. 9406 9407 // If the operand is a float, integer, or vector constant, spill to a 9408 // constant pool entry to get its address. 9409 const Value *OpVal = OpInfo.CallOperandVal; 9410 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9411 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9412 OpInfo.CallOperand = DAG.getConstantPool( 9413 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9414 return Chain; 9415 } 9416 9417 // Otherwise, create a stack slot and emit a store to it before the asm. 9418 Type *Ty = OpVal->getType(); 9419 auto &DL = DAG.getDataLayout(); 9420 uint64_t TySize = DL.getTypeAllocSize(Ty); 9421 MachineFunction &MF = DAG.getMachineFunction(); 9422 int SSFI = MF.getFrameInfo().CreateStackObject( 9423 TySize, DL.getPrefTypeAlign(Ty), false); 9424 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9425 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9426 MachinePointerInfo::getFixedStack(MF, SSFI), 9427 TLI.getMemValueType(DL, Ty)); 9428 OpInfo.CallOperand = StackSlot; 9429 9430 return Chain; 9431 } 9432 9433 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9434 /// specified operand. We prefer to assign virtual registers, to allow the 9435 /// register allocator to handle the assignment process. However, if the asm 9436 /// uses features that we can't model on machineinstrs, we have SDISel do the 9437 /// allocation. This produces generally horrible, but correct, code. 9438 /// 9439 /// OpInfo describes the operand 9440 /// RefOpInfo describes the matching operand if any, the operand otherwise 9441 static std::optional<unsigned> 9442 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9443 SDISelAsmOperandInfo &OpInfo, 9444 SDISelAsmOperandInfo &RefOpInfo) { 9445 LLVMContext &Context = *DAG.getContext(); 9446 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9447 9448 MachineFunction &MF = DAG.getMachineFunction(); 9449 SmallVector<unsigned, 4> Regs; 9450 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9451 9452 // No work to do for memory/address operands. 9453 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9454 OpInfo.ConstraintType == TargetLowering::C_Address) 9455 return std::nullopt; 9456 9457 // If this is a constraint for a single physreg, or a constraint for a 9458 // register class, find it. 9459 unsigned AssignedReg; 9460 const TargetRegisterClass *RC; 9461 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9462 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9463 // RC is unset only on failure. Return immediately. 9464 if (!RC) 9465 return std::nullopt; 9466 9467 // Get the actual register value type. This is important, because the user 9468 // may have asked for (e.g.) the AX register in i32 type. We need to 9469 // remember that AX is actually i16 to get the right extension. 9470 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9471 9472 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9473 // If this is an FP operand in an integer register (or visa versa), or more 9474 // generally if the operand value disagrees with the register class we plan 9475 // to stick it in, fix the operand type. 9476 // 9477 // If this is an input value, the bitcast to the new type is done now. 9478 // Bitcast for output value is done at the end of visitInlineAsm(). 9479 if ((OpInfo.Type == InlineAsm::isOutput || 9480 OpInfo.Type == InlineAsm::isInput) && 9481 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9482 // Try to convert to the first EVT that the reg class contains. If the 9483 // types are identical size, use a bitcast to convert (e.g. two differing 9484 // vector types). Note: output bitcast is done at the end of 9485 // visitInlineAsm(). 9486 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9487 // Exclude indirect inputs while they are unsupported because the code 9488 // to perform the load is missing and thus OpInfo.CallOperand still 9489 // refers to the input address rather than the pointed-to value. 9490 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9491 OpInfo.CallOperand = 9492 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9493 OpInfo.ConstraintVT = RegVT; 9494 // If the operand is an FP value and we want it in integer registers, 9495 // use the corresponding integer type. This turns an f64 value into 9496 // i64, which can be passed with two i32 values on a 32-bit machine. 9497 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9498 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9499 if (OpInfo.Type == InlineAsm::isInput) 9500 OpInfo.CallOperand = 9501 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9502 OpInfo.ConstraintVT = VT; 9503 } 9504 } 9505 } 9506 9507 // No need to allocate a matching input constraint since the constraint it's 9508 // matching to has already been allocated. 9509 if (OpInfo.isMatchingInputConstraint()) 9510 return std::nullopt; 9511 9512 EVT ValueVT = OpInfo.ConstraintVT; 9513 if (OpInfo.ConstraintVT == MVT::Other) 9514 ValueVT = RegVT; 9515 9516 // Initialize NumRegs. 9517 unsigned NumRegs = 1; 9518 if (OpInfo.ConstraintVT != MVT::Other) 9519 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9520 9521 // If this is a constraint for a specific physical register, like {r17}, 9522 // assign it now. 9523 9524 // If this associated to a specific register, initialize iterator to correct 9525 // place. If virtual, make sure we have enough registers 9526 9527 // Initialize iterator if necessary 9528 TargetRegisterClass::iterator I = RC->begin(); 9529 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9530 9531 // Do not check for single registers. 9532 if (AssignedReg) { 9533 I = std::find(I, RC->end(), AssignedReg); 9534 if (I == RC->end()) { 9535 // RC does not contain the selected register, which indicates a 9536 // mismatch between the register and the required type/bitwidth. 9537 return {AssignedReg}; 9538 } 9539 } 9540 9541 for (; NumRegs; --NumRegs, ++I) { 9542 assert(I != RC->end() && "Ran out of registers to allocate!"); 9543 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9544 Regs.push_back(R); 9545 } 9546 9547 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9548 return std::nullopt; 9549 } 9550 9551 static unsigned 9552 findMatchingInlineAsmOperand(unsigned OperandNo, 9553 const std::vector<SDValue> &AsmNodeOperands) { 9554 // Scan until we find the definition we already emitted of this operand. 9555 unsigned CurOp = InlineAsm::Op_FirstOperand; 9556 for (; OperandNo; --OperandNo) { 9557 // Advance to the next operand. 9558 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9559 const InlineAsm::Flag F(OpFlag); 9560 assert( 9561 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9562 "Skipped past definitions?"); 9563 CurOp += F.getNumOperandRegisters() + 1; 9564 } 9565 return CurOp; 9566 } 9567 9568 namespace { 9569 9570 class ExtraFlags { 9571 unsigned Flags = 0; 9572 9573 public: 9574 explicit ExtraFlags(const CallBase &Call) { 9575 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9576 if (IA->hasSideEffects()) 9577 Flags |= InlineAsm::Extra_HasSideEffects; 9578 if (IA->isAlignStack()) 9579 Flags |= InlineAsm::Extra_IsAlignStack; 9580 if (Call.isConvergent()) 9581 Flags |= InlineAsm::Extra_IsConvergent; 9582 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9583 } 9584 9585 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9586 // Ideally, we would only check against memory constraints. However, the 9587 // meaning of an Other constraint can be target-specific and we can't easily 9588 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9589 // for Other constraints as well. 9590 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9591 OpInfo.ConstraintType == TargetLowering::C_Other) { 9592 if (OpInfo.Type == InlineAsm::isInput) 9593 Flags |= InlineAsm::Extra_MayLoad; 9594 else if (OpInfo.Type == InlineAsm::isOutput) 9595 Flags |= InlineAsm::Extra_MayStore; 9596 else if (OpInfo.Type == InlineAsm::isClobber) 9597 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9598 } 9599 } 9600 9601 unsigned get() const { return Flags; } 9602 }; 9603 9604 } // end anonymous namespace 9605 9606 static bool isFunction(SDValue Op) { 9607 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9608 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9609 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9610 9611 // In normal "call dllimport func" instruction (non-inlineasm) it force 9612 // indirect access by specifing call opcode. And usually specially print 9613 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9614 // not do in this way now. (In fact, this is similar with "Data Access" 9615 // action). So here we ignore dllimport function. 9616 if (Fn && !Fn->hasDLLImportStorageClass()) 9617 return true; 9618 } 9619 } 9620 return false; 9621 } 9622 9623 /// visitInlineAsm - Handle a call to an InlineAsm object. 9624 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9625 const BasicBlock *EHPadBB) { 9626 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9627 9628 /// ConstraintOperands - Information about all of the constraints. 9629 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9630 9631 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9632 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9633 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9634 9635 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9636 // AsmDialect, MayLoad, MayStore). 9637 bool HasSideEffect = IA->hasSideEffects(); 9638 ExtraFlags ExtraInfo(Call); 9639 9640 for (auto &T : TargetConstraints) { 9641 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9642 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9643 9644 if (OpInfo.CallOperandVal) 9645 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9646 9647 if (!HasSideEffect) 9648 HasSideEffect = OpInfo.hasMemory(TLI); 9649 9650 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9651 // FIXME: Could we compute this on OpInfo rather than T? 9652 9653 // Compute the constraint code and ConstraintType to use. 9654 TLI.ComputeConstraintToUse(T, SDValue()); 9655 9656 if (T.ConstraintType == TargetLowering::C_Immediate && 9657 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9658 // We've delayed emitting a diagnostic like the "n" constraint because 9659 // inlining could cause an integer showing up. 9660 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9661 "' expects an integer constant " 9662 "expression"); 9663 9664 ExtraInfo.update(T); 9665 } 9666 9667 // We won't need to flush pending loads if this asm doesn't touch 9668 // memory and is nonvolatile. 9669 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9670 9671 bool EmitEHLabels = isa<InvokeInst>(Call); 9672 if (EmitEHLabels) { 9673 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9674 } 9675 bool IsCallBr = isa<CallBrInst>(Call); 9676 9677 if (IsCallBr || EmitEHLabels) { 9678 // If this is a callbr or invoke we need to flush pending exports since 9679 // inlineasm_br and invoke are terminators. 9680 // We need to do this before nodes are glued to the inlineasm_br node. 9681 Chain = getControlRoot(); 9682 } 9683 9684 MCSymbol *BeginLabel = nullptr; 9685 if (EmitEHLabels) { 9686 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9687 } 9688 9689 int OpNo = -1; 9690 SmallVector<StringRef> AsmStrs; 9691 IA->collectAsmStrs(AsmStrs); 9692 9693 // Second pass over the constraints: compute which constraint option to use. 9694 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9695 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9696 OpNo++; 9697 9698 // If this is an output operand with a matching input operand, look up the 9699 // matching input. If their types mismatch, e.g. one is an integer, the 9700 // other is floating point, or their sizes are different, flag it as an 9701 // error. 9702 if (OpInfo.hasMatchingInput()) { 9703 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9704 patchMatchingInput(OpInfo, Input, DAG); 9705 } 9706 9707 // Compute the constraint code and ConstraintType to use. 9708 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9709 9710 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9711 OpInfo.Type == InlineAsm::isClobber) || 9712 OpInfo.ConstraintType == TargetLowering::C_Address) 9713 continue; 9714 9715 // In Linux PIC model, there are 4 cases about value/label addressing: 9716 // 9717 // 1: Function call or Label jmp inside the module. 9718 // 2: Data access (such as global variable, static variable) inside module. 9719 // 3: Function call or Label jmp outside the module. 9720 // 4: Data access (such as global variable) outside the module. 9721 // 9722 // Due to current llvm inline asm architecture designed to not "recognize" 9723 // the asm code, there are quite troubles for us to treat mem addressing 9724 // differently for same value/adress used in different instuctions. 9725 // For example, in pic model, call a func may in plt way or direclty 9726 // pc-related, but lea/mov a function adress may use got. 9727 // 9728 // Here we try to "recognize" function call for the case 1 and case 3 in 9729 // inline asm. And try to adjust the constraint for them. 9730 // 9731 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9732 // label, so here we don't handle jmp function label now, but we need to 9733 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9734 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9735 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9736 TM.getCodeModel() != CodeModel::Large) { 9737 OpInfo.isIndirect = false; 9738 OpInfo.ConstraintType = TargetLowering::C_Address; 9739 } 9740 9741 // If this is a memory input, and if the operand is not indirect, do what we 9742 // need to provide an address for the memory input. 9743 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9744 !OpInfo.isIndirect) { 9745 assert((OpInfo.isMultipleAlternative || 9746 (OpInfo.Type == InlineAsm::isInput)) && 9747 "Can only indirectify direct input operands!"); 9748 9749 // Memory operands really want the address of the value. 9750 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9751 9752 // There is no longer a Value* corresponding to this operand. 9753 OpInfo.CallOperandVal = nullptr; 9754 9755 // It is now an indirect operand. 9756 OpInfo.isIndirect = true; 9757 } 9758 9759 } 9760 9761 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9762 std::vector<SDValue> AsmNodeOperands; 9763 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9764 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9765 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9766 9767 // If we have a !srcloc metadata node associated with it, we want to attach 9768 // this to the ultimately generated inline asm machineinstr. To do this, we 9769 // pass in the third operand as this (potentially null) inline asm MDNode. 9770 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9771 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9772 9773 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9774 // bits as operand 3. 9775 AsmNodeOperands.push_back(DAG.getTargetConstant( 9776 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9777 9778 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9779 // this, assign virtual and physical registers for inputs and otput. 9780 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9781 // Assign Registers. 9782 SDISelAsmOperandInfo &RefOpInfo = 9783 OpInfo.isMatchingInputConstraint() 9784 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9785 : OpInfo; 9786 const auto RegError = 9787 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9788 if (RegError) { 9789 const MachineFunction &MF = DAG.getMachineFunction(); 9790 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9791 const char *RegName = TRI.getName(*RegError); 9792 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9793 "' allocated for constraint '" + 9794 Twine(OpInfo.ConstraintCode) + 9795 "' does not match required type"); 9796 return; 9797 } 9798 9799 auto DetectWriteToReservedRegister = [&]() { 9800 const MachineFunction &MF = DAG.getMachineFunction(); 9801 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9802 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9803 if (Register::isPhysicalRegister(Reg) && 9804 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9805 const char *RegName = TRI.getName(Reg); 9806 emitInlineAsmError(Call, "write to reserved register '" + 9807 Twine(RegName) + "'"); 9808 return true; 9809 } 9810 } 9811 return false; 9812 }; 9813 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9814 (OpInfo.Type == InlineAsm::isInput && 9815 !OpInfo.isMatchingInputConstraint())) && 9816 "Only address as input operand is allowed."); 9817 9818 switch (OpInfo.Type) { 9819 case InlineAsm::isOutput: 9820 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9821 const InlineAsm::ConstraintCode ConstraintID = 9822 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9823 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9824 "Failed to convert memory constraint code to constraint id."); 9825 9826 // Add information to the INLINEASM node to know about this output. 9827 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 9828 OpFlags.setMemConstraint(ConstraintID); 9829 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9830 MVT::i32)); 9831 AsmNodeOperands.push_back(OpInfo.CallOperand); 9832 } else { 9833 // Otherwise, this outputs to a register (directly for C_Register / 9834 // C_RegisterClass, and a target-defined fashion for 9835 // C_Immediate/C_Other). Find a register that we can use. 9836 if (OpInfo.AssignedRegs.Regs.empty()) { 9837 emitInlineAsmError( 9838 Call, "couldn't allocate output register for constraint '" + 9839 Twine(OpInfo.ConstraintCode) + "'"); 9840 return; 9841 } 9842 9843 if (DetectWriteToReservedRegister()) 9844 return; 9845 9846 // Add information to the INLINEASM node to know that this register is 9847 // set. 9848 OpInfo.AssignedRegs.AddInlineAsmOperands( 9849 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 9850 : InlineAsm::Kind::RegDef, 9851 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9852 } 9853 break; 9854 9855 case InlineAsm::isInput: 9856 case InlineAsm::isLabel: { 9857 SDValue InOperandVal = OpInfo.CallOperand; 9858 9859 if (OpInfo.isMatchingInputConstraint()) { 9860 // If this is required to match an output register we have already set, 9861 // just use its register. 9862 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9863 AsmNodeOperands); 9864 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 9865 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 9866 if (OpInfo.isIndirect) { 9867 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9868 emitInlineAsmError(Call, "inline asm not supported yet: " 9869 "don't know how to handle tied " 9870 "indirect register inputs"); 9871 return; 9872 } 9873 9874 SmallVector<unsigned, 4> Regs; 9875 MachineFunction &MF = DAG.getMachineFunction(); 9876 MachineRegisterInfo &MRI = MF.getRegInfo(); 9877 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9878 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9879 Register TiedReg = R->getReg(); 9880 MVT RegVT = R->getSimpleValueType(0); 9881 const TargetRegisterClass *RC = 9882 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9883 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9884 : TRI.getMinimalPhysRegClass(TiedReg); 9885 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 9886 Regs.push_back(MRI.createVirtualRegister(RC)); 9887 9888 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9889 9890 SDLoc dl = getCurSDLoc(); 9891 // Use the produced MatchedRegs object to 9892 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9893 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 9894 OpInfo.getMatchedOperand(), dl, DAG, 9895 AsmNodeOperands); 9896 break; 9897 } 9898 9899 assert(Flag.isMemKind() && "Unknown matching constraint!"); 9900 assert(Flag.getNumOperandRegisters() == 1 && 9901 "Unexpected number of operands"); 9902 // Add information to the INLINEASM node to know about this input. 9903 // See InlineAsm.h isUseOperandTiedToDef. 9904 Flag.clearMemConstraint(); 9905 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 9906 AsmNodeOperands.push_back(DAG.getTargetConstant( 9907 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9908 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9909 break; 9910 } 9911 9912 // Treat indirect 'X' constraint as memory. 9913 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9914 OpInfo.isIndirect) 9915 OpInfo.ConstraintType = TargetLowering::C_Memory; 9916 9917 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9918 OpInfo.ConstraintType == TargetLowering::C_Other) { 9919 std::vector<SDValue> Ops; 9920 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9921 Ops, DAG); 9922 if (Ops.empty()) { 9923 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9924 if (isa<ConstantSDNode>(InOperandVal)) { 9925 emitInlineAsmError(Call, "value out of range for constraint '" + 9926 Twine(OpInfo.ConstraintCode) + "'"); 9927 return; 9928 } 9929 9930 emitInlineAsmError(Call, 9931 "invalid operand for inline asm constraint '" + 9932 Twine(OpInfo.ConstraintCode) + "'"); 9933 return; 9934 } 9935 9936 // Add information to the INLINEASM node to know about this input. 9937 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 9938 AsmNodeOperands.push_back(DAG.getTargetConstant( 9939 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9940 llvm::append_range(AsmNodeOperands, Ops); 9941 break; 9942 } 9943 9944 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9945 assert((OpInfo.isIndirect || 9946 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9947 "Operand must be indirect to be a mem!"); 9948 assert(InOperandVal.getValueType() == 9949 TLI.getPointerTy(DAG.getDataLayout()) && 9950 "Memory operands expect pointer values"); 9951 9952 const InlineAsm::ConstraintCode ConstraintID = 9953 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9954 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9955 "Failed to convert memory constraint code to constraint id."); 9956 9957 // Add information to the INLINEASM node to know about this input. 9958 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9959 ResOpType.setMemConstraint(ConstraintID); 9960 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9961 getCurSDLoc(), 9962 MVT::i32)); 9963 AsmNodeOperands.push_back(InOperandVal); 9964 break; 9965 } 9966 9967 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9968 const InlineAsm::ConstraintCode ConstraintID = 9969 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9970 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9971 "Failed to convert memory constraint code to constraint id."); 9972 9973 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9974 9975 SDValue AsmOp = InOperandVal; 9976 if (isFunction(InOperandVal)) { 9977 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9978 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 9979 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9980 InOperandVal.getValueType(), 9981 GA->getOffset()); 9982 } 9983 9984 // Add information to the INLINEASM node to know about this input. 9985 ResOpType.setMemConstraint(ConstraintID); 9986 9987 AsmNodeOperands.push_back( 9988 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9989 9990 AsmNodeOperands.push_back(AsmOp); 9991 break; 9992 } 9993 9994 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9995 OpInfo.ConstraintType == TargetLowering::C_Register) && 9996 "Unknown constraint type!"); 9997 9998 // TODO: Support this. 9999 if (OpInfo.isIndirect) { 10000 emitInlineAsmError( 10001 Call, "Don't know how to handle indirect register inputs yet " 10002 "for constraint '" + 10003 Twine(OpInfo.ConstraintCode) + "'"); 10004 return; 10005 } 10006 10007 // Copy the input into the appropriate registers. 10008 if (OpInfo.AssignedRegs.Regs.empty()) { 10009 emitInlineAsmError(Call, 10010 "couldn't allocate input reg for constraint '" + 10011 Twine(OpInfo.ConstraintCode) + "'"); 10012 return; 10013 } 10014 10015 if (DetectWriteToReservedRegister()) 10016 return; 10017 10018 SDLoc dl = getCurSDLoc(); 10019 10020 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 10021 &Call); 10022 10023 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 10024 0, dl, DAG, AsmNodeOperands); 10025 break; 10026 } 10027 case InlineAsm::isClobber: 10028 // Add the clobbered value to the operand list, so that the register 10029 // allocator is aware that the physreg got clobbered. 10030 if (!OpInfo.AssignedRegs.Regs.empty()) 10031 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 10032 false, 0, getCurSDLoc(), DAG, 10033 AsmNodeOperands); 10034 break; 10035 } 10036 } 10037 10038 // Finish up input operands. Set the input chain and add the flag last. 10039 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 10040 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 10041 10042 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 10043 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 10044 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 10045 Glue = Chain.getValue(1); 10046 10047 // Do additional work to generate outputs. 10048 10049 SmallVector<EVT, 1> ResultVTs; 10050 SmallVector<SDValue, 1> ResultValues; 10051 SmallVector<SDValue, 8> OutChains; 10052 10053 llvm::Type *CallResultType = Call.getType(); 10054 ArrayRef<Type *> ResultTypes; 10055 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 10056 ResultTypes = StructResult->elements(); 10057 else if (!CallResultType->isVoidTy()) 10058 ResultTypes = ArrayRef(CallResultType); 10059 10060 auto CurResultType = ResultTypes.begin(); 10061 auto handleRegAssign = [&](SDValue V) { 10062 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 10063 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 10064 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 10065 ++CurResultType; 10066 // If the type of the inline asm call site return value is different but has 10067 // same size as the type of the asm output bitcast it. One example of this 10068 // is for vectors with different width / number of elements. This can 10069 // happen for register classes that can contain multiple different value 10070 // types. The preg or vreg allocated may not have the same VT as was 10071 // expected. 10072 // 10073 // This can also happen for a return value that disagrees with the register 10074 // class it is put in, eg. a double in a general-purpose register on a 10075 // 32-bit machine. 10076 if (ResultVT != V.getValueType() && 10077 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 10078 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 10079 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 10080 V.getValueType().isInteger()) { 10081 // If a result value was tied to an input value, the computed result 10082 // may have a wider width than the expected result. Extract the 10083 // relevant portion. 10084 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 10085 } 10086 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 10087 ResultVTs.push_back(ResultVT); 10088 ResultValues.push_back(V); 10089 }; 10090 10091 // Deal with output operands. 10092 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10093 if (OpInfo.Type == InlineAsm::isOutput) { 10094 SDValue Val; 10095 // Skip trivial output operands. 10096 if (OpInfo.AssignedRegs.Regs.empty()) 10097 continue; 10098 10099 switch (OpInfo.ConstraintType) { 10100 case TargetLowering::C_Register: 10101 case TargetLowering::C_RegisterClass: 10102 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 10103 Chain, &Glue, &Call); 10104 break; 10105 case TargetLowering::C_Immediate: 10106 case TargetLowering::C_Other: 10107 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 10108 OpInfo, DAG); 10109 break; 10110 case TargetLowering::C_Memory: 10111 break; // Already handled. 10112 case TargetLowering::C_Address: 10113 break; // Silence warning. 10114 case TargetLowering::C_Unknown: 10115 assert(false && "Unexpected unknown constraint"); 10116 } 10117 10118 // Indirect output manifest as stores. Record output chains. 10119 if (OpInfo.isIndirect) { 10120 const Value *Ptr = OpInfo.CallOperandVal; 10121 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 10122 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 10123 MachinePointerInfo(Ptr)); 10124 OutChains.push_back(Store); 10125 } else { 10126 // generate CopyFromRegs to associated registers. 10127 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 10128 if (Val.getOpcode() == ISD::MERGE_VALUES) { 10129 for (const SDValue &V : Val->op_values()) 10130 handleRegAssign(V); 10131 } else 10132 handleRegAssign(Val); 10133 } 10134 } 10135 } 10136 10137 // Set results. 10138 if (!ResultValues.empty()) { 10139 assert(CurResultType == ResultTypes.end() && 10140 "Mismatch in number of ResultTypes"); 10141 assert(ResultValues.size() == ResultTypes.size() && 10142 "Mismatch in number of output operands in asm result"); 10143 10144 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10145 DAG.getVTList(ResultVTs), ResultValues); 10146 setValue(&Call, V); 10147 } 10148 10149 // Collect store chains. 10150 if (!OutChains.empty()) 10151 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 10152 10153 if (EmitEHLabels) { 10154 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 10155 } 10156 10157 // Only Update Root if inline assembly has a memory effect. 10158 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 10159 EmitEHLabels) 10160 DAG.setRoot(Chain); 10161 } 10162 10163 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 10164 const Twine &Message) { 10165 LLVMContext &Ctx = *DAG.getContext(); 10166 Ctx.emitError(&Call, Message); 10167 10168 // Make sure we leave the DAG in a valid state 10169 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10170 SmallVector<EVT, 1> ValueVTs; 10171 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 10172 10173 if (ValueVTs.empty()) 10174 return; 10175 10176 SmallVector<SDValue, 1> Ops; 10177 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 10178 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 10179 10180 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 10181 } 10182 10183 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 10184 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 10185 MVT::Other, getRoot(), 10186 getValue(I.getArgOperand(0)), 10187 DAG.getSrcValue(I.getArgOperand(0)))); 10188 } 10189 10190 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 10191 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10192 const DataLayout &DL = DAG.getDataLayout(); 10193 SDValue V = DAG.getVAArg( 10194 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 10195 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 10196 DL.getABITypeAlign(I.getType()).value()); 10197 DAG.setRoot(V.getValue(1)); 10198 10199 if (I.getType()->isPointerTy()) 10200 V = DAG.getPtrExtOrTrunc( 10201 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 10202 setValue(&I, V); 10203 } 10204 10205 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 10206 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 10207 MVT::Other, getRoot(), 10208 getValue(I.getArgOperand(0)), 10209 DAG.getSrcValue(I.getArgOperand(0)))); 10210 } 10211 10212 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 10213 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 10214 MVT::Other, getRoot(), 10215 getValue(I.getArgOperand(0)), 10216 getValue(I.getArgOperand(1)), 10217 DAG.getSrcValue(I.getArgOperand(0)), 10218 DAG.getSrcValue(I.getArgOperand(1)))); 10219 } 10220 10221 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 10222 const Instruction &I, 10223 SDValue Op) { 10224 const MDNode *Range = getRangeMetadata(I); 10225 if (!Range) 10226 return Op; 10227 10228 ConstantRange CR = getConstantRangeFromMetadata(*Range); 10229 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 10230 return Op; 10231 10232 APInt Lo = CR.getUnsignedMin(); 10233 if (!Lo.isMinValue()) 10234 return Op; 10235 10236 APInt Hi = CR.getUnsignedMax(); 10237 unsigned Bits = std::max(Hi.getActiveBits(), 10238 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 10239 10240 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 10241 10242 SDLoc SL = getCurSDLoc(); 10243 10244 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 10245 DAG.getValueType(SmallVT)); 10246 unsigned NumVals = Op.getNode()->getNumValues(); 10247 if (NumVals == 1) 10248 return ZExt; 10249 10250 SmallVector<SDValue, 4> Ops; 10251 10252 Ops.push_back(ZExt); 10253 for (unsigned I = 1; I != NumVals; ++I) 10254 Ops.push_back(Op.getValue(I)); 10255 10256 return DAG.getMergeValues(Ops, SL); 10257 } 10258 10259 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 10260 /// the call being lowered. 10261 /// 10262 /// This is a helper for lowering intrinsics that follow a target calling 10263 /// convention or require stack pointer adjustment. Only a subset of the 10264 /// intrinsic's operands need to participate in the calling convention. 10265 void SelectionDAGBuilder::populateCallLoweringInfo( 10266 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 10267 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 10268 AttributeSet RetAttrs, bool IsPatchPoint) { 10269 TargetLowering::ArgListTy Args; 10270 Args.reserve(NumArgs); 10271 10272 // Populate the argument list. 10273 // Attributes for args start at offset 1, after the return attribute. 10274 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 10275 ArgI != ArgE; ++ArgI) { 10276 const Value *V = Call->getOperand(ArgI); 10277 10278 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 10279 10280 TargetLowering::ArgListEntry Entry; 10281 Entry.Node = getValue(V); 10282 Entry.Ty = V->getType(); 10283 Entry.setAttributes(Call, ArgI); 10284 Args.push_back(Entry); 10285 } 10286 10287 CLI.setDebugLoc(getCurSDLoc()) 10288 .setChain(getRoot()) 10289 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 10290 RetAttrs) 10291 .setDiscardResult(Call->use_empty()) 10292 .setIsPatchPoint(IsPatchPoint) 10293 .setIsPreallocated( 10294 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 10295 } 10296 10297 /// Add a stack map intrinsic call's live variable operands to a stackmap 10298 /// or patchpoint target node's operand list. 10299 /// 10300 /// Constants are converted to TargetConstants purely as an optimization to 10301 /// avoid constant materialization and register allocation. 10302 /// 10303 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 10304 /// generate addess computation nodes, and so FinalizeISel can convert the 10305 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10306 /// address materialization and register allocation, but may also be required 10307 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10308 /// alloca in the entry block, then the runtime may assume that the alloca's 10309 /// StackMap location can be read immediately after compilation and that the 10310 /// location is valid at any point during execution (this is similar to the 10311 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10312 /// only available in a register, then the runtime would need to trap when 10313 /// execution reaches the StackMap in order to read the alloca's location. 10314 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10315 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10316 SelectionDAGBuilder &Builder) { 10317 SelectionDAG &DAG = Builder.DAG; 10318 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10319 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10320 10321 // Things on the stack are pointer-typed, meaning that they are already 10322 // legal and can be emitted directly to target nodes. 10323 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10324 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10325 } else { 10326 // Otherwise emit a target independent node to be legalised. 10327 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10328 } 10329 } 10330 } 10331 10332 /// Lower llvm.experimental.stackmap. 10333 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10334 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10335 // [live variables...]) 10336 10337 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10338 10339 SDValue Chain, InGlue, Callee; 10340 SmallVector<SDValue, 32> Ops; 10341 10342 SDLoc DL = getCurSDLoc(); 10343 Callee = getValue(CI.getCalledOperand()); 10344 10345 // The stackmap intrinsic only records the live variables (the arguments 10346 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10347 // intrinsic, this won't be lowered to a function call. This means we don't 10348 // have to worry about calling conventions and target specific lowering code. 10349 // Instead we perform the call lowering right here. 10350 // 10351 // chain, flag = CALLSEQ_START(chain, 0, 0) 10352 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10353 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10354 // 10355 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10356 InGlue = Chain.getValue(1); 10357 10358 // Add the STACKMAP operands, starting with DAG house-keeping. 10359 Ops.push_back(Chain); 10360 Ops.push_back(InGlue); 10361 10362 // Add the <id>, <numShadowBytes> operands. 10363 // 10364 // These do not require legalisation, and can be emitted directly to target 10365 // constant nodes. 10366 SDValue ID = getValue(CI.getArgOperand(0)); 10367 assert(ID.getValueType() == MVT::i64); 10368 SDValue IDConst = 10369 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10370 Ops.push_back(IDConst); 10371 10372 SDValue Shad = getValue(CI.getArgOperand(1)); 10373 assert(Shad.getValueType() == MVT::i32); 10374 SDValue ShadConst = 10375 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10376 Ops.push_back(ShadConst); 10377 10378 // Add the live variables. 10379 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10380 10381 // Create the STACKMAP node. 10382 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10383 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10384 InGlue = Chain.getValue(1); 10385 10386 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10387 10388 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10389 10390 // Set the root to the target-lowered call chain. 10391 DAG.setRoot(Chain); 10392 10393 // Inform the Frame Information that we have a stackmap in this function. 10394 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10395 } 10396 10397 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10398 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10399 const BasicBlock *EHPadBB) { 10400 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>, 10401 // i32 <numBytes>, 10402 // i8* <target>, 10403 // i32 <numArgs>, 10404 // [Args...], 10405 // [live variables...]) 10406 10407 CallingConv::ID CC = CB.getCallingConv(); 10408 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10409 bool HasDef = !CB.getType()->isVoidTy(); 10410 SDLoc dl = getCurSDLoc(); 10411 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10412 10413 // Handle immediate and symbolic callees. 10414 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10415 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10416 /*isTarget=*/true); 10417 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10418 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10419 SDLoc(SymbolicCallee), 10420 SymbolicCallee->getValueType(0)); 10421 10422 // Get the real number of arguments participating in the call <numArgs> 10423 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10424 unsigned NumArgs = NArgVal->getAsZExtVal(); 10425 10426 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10427 // Intrinsics include all meta-operands up to but not including CC. 10428 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10429 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10430 "Not enough arguments provided to the patchpoint intrinsic"); 10431 10432 // For AnyRegCC the arguments are lowered later on manually. 10433 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10434 Type *ReturnTy = 10435 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10436 10437 TargetLowering::CallLoweringInfo CLI(DAG); 10438 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10439 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10440 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10441 10442 SDNode *CallEnd = Result.second.getNode(); 10443 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10444 CallEnd = CallEnd->getOperand(0).getNode(); 10445 10446 /// Get a call instruction from the call sequence chain. 10447 /// Tail calls are not allowed. 10448 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10449 "Expected a callseq node."); 10450 SDNode *Call = CallEnd->getOperand(0).getNode(); 10451 bool HasGlue = Call->getGluedNode(); 10452 10453 // Replace the target specific call node with the patchable intrinsic. 10454 SmallVector<SDValue, 8> Ops; 10455 10456 // Push the chain. 10457 Ops.push_back(*(Call->op_begin())); 10458 10459 // Optionally, push the glue (if any). 10460 if (HasGlue) 10461 Ops.push_back(*(Call->op_end() - 1)); 10462 10463 // Push the register mask info. 10464 if (HasGlue) 10465 Ops.push_back(*(Call->op_end() - 2)); 10466 else 10467 Ops.push_back(*(Call->op_end() - 1)); 10468 10469 // Add the <id> and <numBytes> constants. 10470 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10471 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10472 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10473 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10474 10475 // Add the callee. 10476 Ops.push_back(Callee); 10477 10478 // Adjust <numArgs> to account for any arguments that have been passed on the 10479 // stack instead. 10480 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10481 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10482 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10483 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10484 10485 // Add the calling convention 10486 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10487 10488 // Add the arguments we omitted previously. The register allocator should 10489 // place these in any free register. 10490 if (IsAnyRegCC) 10491 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10492 Ops.push_back(getValue(CB.getArgOperand(i))); 10493 10494 // Push the arguments from the call instruction. 10495 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10496 Ops.append(Call->op_begin() + 2, e); 10497 10498 // Push live variables for the stack map. 10499 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10500 10501 SDVTList NodeTys; 10502 if (IsAnyRegCC && HasDef) { 10503 // Create the return types based on the intrinsic definition 10504 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10505 SmallVector<EVT, 3> ValueVTs; 10506 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10507 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10508 10509 // There is always a chain and a glue type at the end 10510 ValueVTs.push_back(MVT::Other); 10511 ValueVTs.push_back(MVT::Glue); 10512 NodeTys = DAG.getVTList(ValueVTs); 10513 } else 10514 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10515 10516 // Replace the target specific call node with a PATCHPOINT node. 10517 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10518 10519 // Update the NodeMap. 10520 if (HasDef) { 10521 if (IsAnyRegCC) 10522 setValue(&CB, SDValue(PPV.getNode(), 0)); 10523 else 10524 setValue(&CB, Result.first); 10525 } 10526 10527 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10528 // call sequence. Furthermore the location of the chain and glue can change 10529 // when the AnyReg calling convention is used and the intrinsic returns a 10530 // value. 10531 if (IsAnyRegCC && HasDef) { 10532 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10533 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10534 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10535 } else 10536 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10537 DAG.DeleteNode(Call); 10538 10539 // Inform the Frame Information that we have a patchpoint in this function. 10540 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10541 } 10542 10543 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10544 unsigned Intrinsic) { 10545 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10546 SDValue Op1 = getValue(I.getArgOperand(0)); 10547 SDValue Op2; 10548 if (I.arg_size() > 1) 10549 Op2 = getValue(I.getArgOperand(1)); 10550 SDLoc dl = getCurSDLoc(); 10551 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10552 SDValue Res; 10553 SDNodeFlags SDFlags; 10554 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10555 SDFlags.copyFMF(*FPMO); 10556 10557 switch (Intrinsic) { 10558 case Intrinsic::vector_reduce_fadd: 10559 if (SDFlags.hasAllowReassociation()) 10560 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10561 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10562 SDFlags); 10563 else 10564 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10565 break; 10566 case Intrinsic::vector_reduce_fmul: 10567 if (SDFlags.hasAllowReassociation()) 10568 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10569 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10570 SDFlags); 10571 else 10572 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10573 break; 10574 case Intrinsic::vector_reduce_add: 10575 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10576 break; 10577 case Intrinsic::vector_reduce_mul: 10578 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10579 break; 10580 case Intrinsic::vector_reduce_and: 10581 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10582 break; 10583 case Intrinsic::vector_reduce_or: 10584 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10585 break; 10586 case Intrinsic::vector_reduce_xor: 10587 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10588 break; 10589 case Intrinsic::vector_reduce_smax: 10590 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10591 break; 10592 case Intrinsic::vector_reduce_smin: 10593 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10594 break; 10595 case Intrinsic::vector_reduce_umax: 10596 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10597 break; 10598 case Intrinsic::vector_reduce_umin: 10599 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10600 break; 10601 case Intrinsic::vector_reduce_fmax: 10602 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10603 break; 10604 case Intrinsic::vector_reduce_fmin: 10605 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10606 break; 10607 case Intrinsic::vector_reduce_fmaximum: 10608 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10609 break; 10610 case Intrinsic::vector_reduce_fminimum: 10611 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10612 break; 10613 default: 10614 llvm_unreachable("Unhandled vector reduce intrinsic"); 10615 } 10616 setValue(&I, Res); 10617 } 10618 10619 /// Returns an AttributeList representing the attributes applied to the return 10620 /// value of the given call. 10621 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10622 SmallVector<Attribute::AttrKind, 2> Attrs; 10623 if (CLI.RetSExt) 10624 Attrs.push_back(Attribute::SExt); 10625 if (CLI.RetZExt) 10626 Attrs.push_back(Attribute::ZExt); 10627 if (CLI.IsInReg) 10628 Attrs.push_back(Attribute::InReg); 10629 10630 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10631 Attrs); 10632 } 10633 10634 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10635 /// implementation, which just calls LowerCall. 10636 /// FIXME: When all targets are 10637 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10638 std::pair<SDValue, SDValue> 10639 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10640 // Handle the incoming return values from the call. 10641 CLI.Ins.clear(); 10642 Type *OrigRetTy = CLI.RetTy; 10643 SmallVector<EVT, 4> RetTys; 10644 SmallVector<TypeSize, 4> Offsets; 10645 auto &DL = CLI.DAG.getDataLayout(); 10646 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 10647 10648 if (CLI.IsPostTypeLegalization) { 10649 // If we are lowering a libcall after legalization, split the return type. 10650 SmallVector<EVT, 4> OldRetTys; 10651 SmallVector<TypeSize, 4> OldOffsets; 10652 RetTys.swap(OldRetTys); 10653 Offsets.swap(OldOffsets); 10654 10655 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10656 EVT RetVT = OldRetTys[i]; 10657 uint64_t Offset = OldOffsets[i]; 10658 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10659 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10660 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10661 RetTys.append(NumRegs, RegisterVT); 10662 for (unsigned j = 0; j != NumRegs; ++j) 10663 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ)); 10664 } 10665 } 10666 10667 SmallVector<ISD::OutputArg, 4> Outs; 10668 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10669 10670 bool CanLowerReturn = 10671 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10672 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10673 10674 SDValue DemoteStackSlot; 10675 int DemoteStackIdx = -100; 10676 if (!CanLowerReturn) { 10677 // FIXME: equivalent assert? 10678 // assert(!CS.hasInAllocaArgument() && 10679 // "sret demotion is incompatible with inalloca"); 10680 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10681 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10682 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10683 DemoteStackIdx = 10684 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10685 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10686 DL.getAllocaAddrSpace()); 10687 10688 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10689 ArgListEntry Entry; 10690 Entry.Node = DemoteStackSlot; 10691 Entry.Ty = StackSlotPtrType; 10692 Entry.IsSExt = false; 10693 Entry.IsZExt = false; 10694 Entry.IsInReg = false; 10695 Entry.IsSRet = true; 10696 Entry.IsNest = false; 10697 Entry.IsByVal = false; 10698 Entry.IsByRef = false; 10699 Entry.IsReturned = false; 10700 Entry.IsSwiftSelf = false; 10701 Entry.IsSwiftAsync = false; 10702 Entry.IsSwiftError = false; 10703 Entry.IsCFGuardTarget = false; 10704 Entry.Alignment = Alignment; 10705 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10706 CLI.NumFixedArgs += 1; 10707 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10708 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10709 10710 // sret demotion isn't compatible with tail-calls, since the sret argument 10711 // points into the callers stack frame. 10712 CLI.IsTailCall = false; 10713 } else { 10714 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10715 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10716 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10717 ISD::ArgFlagsTy Flags; 10718 if (NeedsRegBlock) { 10719 Flags.setInConsecutiveRegs(); 10720 if (I == RetTys.size() - 1) 10721 Flags.setInConsecutiveRegsLast(); 10722 } 10723 EVT VT = RetTys[I]; 10724 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10725 CLI.CallConv, VT); 10726 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10727 CLI.CallConv, VT); 10728 for (unsigned i = 0; i != NumRegs; ++i) { 10729 ISD::InputArg MyFlags; 10730 MyFlags.Flags = Flags; 10731 MyFlags.VT = RegisterVT; 10732 MyFlags.ArgVT = VT; 10733 MyFlags.Used = CLI.IsReturnValueUsed; 10734 if (CLI.RetTy->isPointerTy()) { 10735 MyFlags.Flags.setPointer(); 10736 MyFlags.Flags.setPointerAddrSpace( 10737 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10738 } 10739 if (CLI.RetSExt) 10740 MyFlags.Flags.setSExt(); 10741 if (CLI.RetZExt) 10742 MyFlags.Flags.setZExt(); 10743 if (CLI.IsInReg) 10744 MyFlags.Flags.setInReg(); 10745 CLI.Ins.push_back(MyFlags); 10746 } 10747 } 10748 } 10749 10750 // We push in swifterror return as the last element of CLI.Ins. 10751 ArgListTy &Args = CLI.getArgs(); 10752 if (supportSwiftError()) { 10753 for (const ArgListEntry &Arg : Args) { 10754 if (Arg.IsSwiftError) { 10755 ISD::InputArg MyFlags; 10756 MyFlags.VT = getPointerTy(DL); 10757 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10758 MyFlags.Flags.setSwiftError(); 10759 CLI.Ins.push_back(MyFlags); 10760 } 10761 } 10762 } 10763 10764 // Handle all of the outgoing arguments. 10765 CLI.Outs.clear(); 10766 CLI.OutVals.clear(); 10767 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10768 SmallVector<EVT, 4> ValueVTs; 10769 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10770 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10771 Type *FinalType = Args[i].Ty; 10772 if (Args[i].IsByVal) 10773 FinalType = Args[i].IndirectType; 10774 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10775 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10776 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10777 ++Value) { 10778 EVT VT = ValueVTs[Value]; 10779 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10780 SDValue Op = SDValue(Args[i].Node.getNode(), 10781 Args[i].Node.getResNo() + Value); 10782 ISD::ArgFlagsTy Flags; 10783 10784 // Certain targets (such as MIPS), may have a different ABI alignment 10785 // for a type depending on the context. Give the target a chance to 10786 // specify the alignment it wants. 10787 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10788 Flags.setOrigAlign(OriginalAlignment); 10789 10790 if (Args[i].Ty->isPointerTy()) { 10791 Flags.setPointer(); 10792 Flags.setPointerAddrSpace( 10793 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10794 } 10795 if (Args[i].IsZExt) 10796 Flags.setZExt(); 10797 if (Args[i].IsSExt) 10798 Flags.setSExt(); 10799 if (Args[i].IsInReg) { 10800 // If we are using vectorcall calling convention, a structure that is 10801 // passed InReg - is surely an HVA 10802 if (CLI.CallConv == CallingConv::X86_VectorCall && 10803 isa<StructType>(FinalType)) { 10804 // The first value of a structure is marked 10805 if (0 == Value) 10806 Flags.setHvaStart(); 10807 Flags.setHva(); 10808 } 10809 // Set InReg Flag 10810 Flags.setInReg(); 10811 } 10812 if (Args[i].IsSRet) 10813 Flags.setSRet(); 10814 if (Args[i].IsSwiftSelf) 10815 Flags.setSwiftSelf(); 10816 if (Args[i].IsSwiftAsync) 10817 Flags.setSwiftAsync(); 10818 if (Args[i].IsSwiftError) 10819 Flags.setSwiftError(); 10820 if (Args[i].IsCFGuardTarget) 10821 Flags.setCFGuardTarget(); 10822 if (Args[i].IsByVal) 10823 Flags.setByVal(); 10824 if (Args[i].IsByRef) 10825 Flags.setByRef(); 10826 if (Args[i].IsPreallocated) { 10827 Flags.setPreallocated(); 10828 // Set the byval flag for CCAssignFn callbacks that don't know about 10829 // preallocated. This way we can know how many bytes we should've 10830 // allocated and how many bytes a callee cleanup function will pop. If 10831 // we port preallocated to more targets, we'll have to add custom 10832 // preallocated handling in the various CC lowering callbacks. 10833 Flags.setByVal(); 10834 } 10835 if (Args[i].IsInAlloca) { 10836 Flags.setInAlloca(); 10837 // Set the byval flag for CCAssignFn callbacks that don't know about 10838 // inalloca. This way we can know how many bytes we should've allocated 10839 // and how many bytes a callee cleanup function will pop. If we port 10840 // inalloca to more targets, we'll have to add custom inalloca handling 10841 // in the various CC lowering callbacks. 10842 Flags.setByVal(); 10843 } 10844 Align MemAlign; 10845 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10846 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10847 Flags.setByValSize(FrameSize); 10848 10849 // info is not there but there are cases it cannot get right. 10850 if (auto MA = Args[i].Alignment) 10851 MemAlign = *MA; 10852 else 10853 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10854 } else if (auto MA = Args[i].Alignment) { 10855 MemAlign = *MA; 10856 } else { 10857 MemAlign = OriginalAlignment; 10858 } 10859 Flags.setMemAlign(MemAlign); 10860 if (Args[i].IsNest) 10861 Flags.setNest(); 10862 if (NeedsRegBlock) 10863 Flags.setInConsecutiveRegs(); 10864 10865 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10866 CLI.CallConv, VT); 10867 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10868 CLI.CallConv, VT); 10869 SmallVector<SDValue, 4> Parts(NumParts); 10870 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10871 10872 if (Args[i].IsSExt) 10873 ExtendKind = ISD::SIGN_EXTEND; 10874 else if (Args[i].IsZExt) 10875 ExtendKind = ISD::ZERO_EXTEND; 10876 10877 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10878 // for now. 10879 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10880 CanLowerReturn) { 10881 assert((CLI.RetTy == Args[i].Ty || 10882 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10883 CLI.RetTy->getPointerAddressSpace() == 10884 Args[i].Ty->getPointerAddressSpace())) && 10885 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10886 // Before passing 'returned' to the target lowering code, ensure that 10887 // either the register MVT and the actual EVT are the same size or that 10888 // the return value and argument are extended in the same way; in these 10889 // cases it's safe to pass the argument register value unchanged as the 10890 // return register value (although it's at the target's option whether 10891 // to do so) 10892 // TODO: allow code generation to take advantage of partially preserved 10893 // registers rather than clobbering the entire register when the 10894 // parameter extension method is not compatible with the return 10895 // extension method 10896 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10897 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10898 CLI.RetZExt == Args[i].IsZExt)) 10899 Flags.setReturned(); 10900 } 10901 10902 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10903 CLI.CallConv, ExtendKind); 10904 10905 for (unsigned j = 0; j != NumParts; ++j) { 10906 // if it isn't first piece, alignment must be 1 10907 // For scalable vectors the scalable part is currently handled 10908 // by individual targets, so we just use the known minimum size here. 10909 ISD::OutputArg MyFlags( 10910 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10911 i < CLI.NumFixedArgs, i, 10912 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10913 if (NumParts > 1 && j == 0) 10914 MyFlags.Flags.setSplit(); 10915 else if (j != 0) { 10916 MyFlags.Flags.setOrigAlign(Align(1)); 10917 if (j == NumParts - 1) 10918 MyFlags.Flags.setSplitEnd(); 10919 } 10920 10921 CLI.Outs.push_back(MyFlags); 10922 CLI.OutVals.push_back(Parts[j]); 10923 } 10924 10925 if (NeedsRegBlock && Value == NumValues - 1) 10926 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10927 } 10928 } 10929 10930 SmallVector<SDValue, 4> InVals; 10931 CLI.Chain = LowerCall(CLI, InVals); 10932 10933 // Update CLI.InVals to use outside of this function. 10934 CLI.InVals = InVals; 10935 10936 // Verify that the target's LowerCall behaved as expected. 10937 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10938 "LowerCall didn't return a valid chain!"); 10939 assert((!CLI.IsTailCall || InVals.empty()) && 10940 "LowerCall emitted a return value for a tail call!"); 10941 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10942 "LowerCall didn't emit the correct number of values!"); 10943 10944 // For a tail call, the return value is merely live-out and there aren't 10945 // any nodes in the DAG representing it. Return a special value to 10946 // indicate that a tail call has been emitted and no more Instructions 10947 // should be processed in the current block. 10948 if (CLI.IsTailCall) { 10949 CLI.DAG.setRoot(CLI.Chain); 10950 return std::make_pair(SDValue(), SDValue()); 10951 } 10952 10953 #ifndef NDEBUG 10954 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10955 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10956 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10957 "LowerCall emitted a value with the wrong type!"); 10958 } 10959 #endif 10960 10961 SmallVector<SDValue, 4> ReturnValues; 10962 if (!CanLowerReturn) { 10963 // The instruction result is the result of loading from the 10964 // hidden sret parameter. 10965 SmallVector<EVT, 1> PVTs; 10966 Type *PtrRetTy = 10967 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10968 10969 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10970 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10971 EVT PtrVT = PVTs[0]; 10972 10973 unsigned NumValues = RetTys.size(); 10974 ReturnValues.resize(NumValues); 10975 SmallVector<SDValue, 4> Chains(NumValues); 10976 10977 // An aggregate return value cannot wrap around the address space, so 10978 // offsets to its parts don't wrap either. 10979 SDNodeFlags Flags; 10980 Flags.setNoUnsignedWrap(true); 10981 10982 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10983 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10984 for (unsigned i = 0; i < NumValues; ++i) { 10985 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10986 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10987 PtrVT), Flags); 10988 SDValue L = CLI.DAG.getLoad( 10989 RetTys[i], CLI.DL, CLI.Chain, Add, 10990 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10991 DemoteStackIdx, Offsets[i]), 10992 HiddenSRetAlign); 10993 ReturnValues[i] = L; 10994 Chains[i] = L.getValue(1); 10995 } 10996 10997 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10998 } else { 10999 // Collect the legal value parts into potentially illegal values 11000 // that correspond to the original function's return values. 11001 std::optional<ISD::NodeType> AssertOp; 11002 if (CLI.RetSExt) 11003 AssertOp = ISD::AssertSext; 11004 else if (CLI.RetZExt) 11005 AssertOp = ISD::AssertZext; 11006 unsigned CurReg = 0; 11007 for (EVT VT : RetTys) { 11008 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11009 CLI.CallConv, VT); 11010 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11011 CLI.CallConv, VT); 11012 11013 ReturnValues.push_back(getCopyFromParts( 11014 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 11015 CLI.Chain, CLI.CallConv, AssertOp)); 11016 CurReg += NumRegs; 11017 } 11018 11019 // For a function returning void, there is no return value. We can't create 11020 // such a node, so we just return a null return value in that case. In 11021 // that case, nothing will actually look at the value. 11022 if (ReturnValues.empty()) 11023 return std::make_pair(SDValue(), CLI.Chain); 11024 } 11025 11026 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 11027 CLI.DAG.getVTList(RetTys), ReturnValues); 11028 return std::make_pair(Res, CLI.Chain); 11029 } 11030 11031 /// Places new result values for the node in Results (their number 11032 /// and types must exactly match those of the original return values of 11033 /// the node), or leaves Results empty, which indicates that the node is not 11034 /// to be custom lowered after all. 11035 void TargetLowering::LowerOperationWrapper(SDNode *N, 11036 SmallVectorImpl<SDValue> &Results, 11037 SelectionDAG &DAG) const { 11038 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 11039 11040 if (!Res.getNode()) 11041 return; 11042 11043 // If the original node has one result, take the return value from 11044 // LowerOperation as is. It might not be result number 0. 11045 if (N->getNumValues() == 1) { 11046 Results.push_back(Res); 11047 return; 11048 } 11049 11050 // If the original node has multiple results, then the return node should 11051 // have the same number of results. 11052 assert((N->getNumValues() == Res->getNumValues()) && 11053 "Lowering returned the wrong number of results!"); 11054 11055 // Places new result values base on N result number. 11056 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 11057 Results.push_back(Res.getValue(I)); 11058 } 11059 11060 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11061 llvm_unreachable("LowerOperation not implemented for this target!"); 11062 } 11063 11064 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 11065 unsigned Reg, 11066 ISD::NodeType ExtendType) { 11067 SDValue Op = getNonRegisterValue(V); 11068 assert((Op.getOpcode() != ISD::CopyFromReg || 11069 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 11070 "Copy from a reg to the same reg!"); 11071 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 11072 11073 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11074 // If this is an InlineAsm we have to match the registers required, not the 11075 // notional registers required by the type. 11076 11077 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 11078 std::nullopt); // This is not an ABI copy. 11079 SDValue Chain = DAG.getEntryNode(); 11080 11081 if (ExtendType == ISD::ANY_EXTEND) { 11082 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 11083 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 11084 ExtendType = PreferredExtendIt->second; 11085 } 11086 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 11087 PendingExports.push_back(Chain); 11088 } 11089 11090 #include "llvm/CodeGen/SelectionDAGISel.h" 11091 11092 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 11093 /// entry block, return true. This includes arguments used by switches, since 11094 /// the switch may expand into multiple basic blocks. 11095 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 11096 // With FastISel active, we may be splitting blocks, so force creation 11097 // of virtual registers for all non-dead arguments. 11098 if (FastISel) 11099 return A->use_empty(); 11100 11101 const BasicBlock &Entry = A->getParent()->front(); 11102 for (const User *U : A->users()) 11103 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 11104 return false; // Use not in entry block. 11105 11106 return true; 11107 } 11108 11109 using ArgCopyElisionMapTy = 11110 DenseMap<const Argument *, 11111 std::pair<const AllocaInst *, const StoreInst *>>; 11112 11113 /// Scan the entry block of the function in FuncInfo for arguments that look 11114 /// like copies into a local alloca. Record any copied arguments in 11115 /// ArgCopyElisionCandidates. 11116 static void 11117 findArgumentCopyElisionCandidates(const DataLayout &DL, 11118 FunctionLoweringInfo *FuncInfo, 11119 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 11120 // Record the state of every static alloca used in the entry block. Argument 11121 // allocas are all used in the entry block, so we need approximately as many 11122 // entries as we have arguments. 11123 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 11124 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 11125 unsigned NumArgs = FuncInfo->Fn->arg_size(); 11126 StaticAllocas.reserve(NumArgs * 2); 11127 11128 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 11129 if (!V) 11130 return nullptr; 11131 V = V->stripPointerCasts(); 11132 const auto *AI = dyn_cast<AllocaInst>(V); 11133 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 11134 return nullptr; 11135 auto Iter = StaticAllocas.insert({AI, Unknown}); 11136 return &Iter.first->second; 11137 }; 11138 11139 // Look for stores of arguments to static allocas. Look through bitcasts and 11140 // GEPs to handle type coercions, as long as the alloca is fully initialized 11141 // by the store. Any non-store use of an alloca escapes it and any subsequent 11142 // unanalyzed store might write it. 11143 // FIXME: Handle structs initialized with multiple stores. 11144 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 11145 // Look for stores, and handle non-store uses conservatively. 11146 const auto *SI = dyn_cast<StoreInst>(&I); 11147 if (!SI) { 11148 // We will look through cast uses, so ignore them completely. 11149 if (I.isCast()) 11150 continue; 11151 // Ignore debug info and pseudo op intrinsics, they don't escape or store 11152 // to allocas. 11153 if (I.isDebugOrPseudoInst()) 11154 continue; 11155 // This is an unknown instruction. Assume it escapes or writes to all 11156 // static alloca operands. 11157 for (const Use &U : I.operands()) { 11158 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 11159 *Info = StaticAllocaInfo::Clobbered; 11160 } 11161 continue; 11162 } 11163 11164 // If the stored value is a static alloca, mark it as escaped. 11165 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 11166 *Info = StaticAllocaInfo::Clobbered; 11167 11168 // Check if the destination is a static alloca. 11169 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 11170 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 11171 if (!Info) 11172 continue; 11173 const AllocaInst *AI = cast<AllocaInst>(Dst); 11174 11175 // Skip allocas that have been initialized or clobbered. 11176 if (*Info != StaticAllocaInfo::Unknown) 11177 continue; 11178 11179 // Check if the stored value is an argument, and that this store fully 11180 // initializes the alloca. 11181 // If the argument type has padding bits we can't directly forward a pointer 11182 // as the upper bits may contain garbage. 11183 // Don't elide copies from the same argument twice. 11184 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 11185 const auto *Arg = dyn_cast<Argument>(Val); 11186 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 11187 Arg->getType()->isEmptyTy() || 11188 DL.getTypeStoreSize(Arg->getType()) != 11189 DL.getTypeAllocSize(AI->getAllocatedType()) || 11190 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 11191 ArgCopyElisionCandidates.count(Arg)) { 11192 *Info = StaticAllocaInfo::Clobbered; 11193 continue; 11194 } 11195 11196 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 11197 << '\n'); 11198 11199 // Mark this alloca and store for argument copy elision. 11200 *Info = StaticAllocaInfo::Elidable; 11201 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 11202 11203 // Stop scanning if we've seen all arguments. This will happen early in -O0 11204 // builds, which is useful, because -O0 builds have large entry blocks and 11205 // many allocas. 11206 if (ArgCopyElisionCandidates.size() == NumArgs) 11207 break; 11208 } 11209 } 11210 11211 /// Try to elide argument copies from memory into a local alloca. Succeeds if 11212 /// ArgVal is a load from a suitable fixed stack object. 11213 static void tryToElideArgumentCopy( 11214 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 11215 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 11216 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 11217 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 11218 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 11219 // Check if this is a load from a fixed stack object. 11220 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 11221 if (!LNode) 11222 return; 11223 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 11224 if (!FINode) 11225 return; 11226 11227 // Check that the fixed stack object is the right size and alignment. 11228 // Look at the alignment that the user wrote on the alloca instead of looking 11229 // at the stack object. 11230 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 11231 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 11232 const AllocaInst *AI = ArgCopyIter->second.first; 11233 int FixedIndex = FINode->getIndex(); 11234 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 11235 int OldIndex = AllocaIndex; 11236 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 11237 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 11238 LLVM_DEBUG( 11239 dbgs() << " argument copy elision failed due to bad fixed stack " 11240 "object size\n"); 11241 return; 11242 } 11243 Align RequiredAlignment = AI->getAlign(); 11244 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 11245 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 11246 "greater than stack argument alignment (" 11247 << DebugStr(RequiredAlignment) << " vs " 11248 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 11249 return; 11250 } 11251 11252 // Perform the elision. Delete the old stack object and replace its only use 11253 // in the variable info map. Mark the stack object as mutable and aliased. 11254 LLVM_DEBUG({ 11255 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 11256 << " Replacing frame index " << OldIndex << " with " << FixedIndex 11257 << '\n'; 11258 }); 11259 MFI.RemoveStackObject(OldIndex); 11260 MFI.setIsImmutableObjectIndex(FixedIndex, false); 11261 MFI.setIsAliasedObjectIndex(FixedIndex, true); 11262 AllocaIndex = FixedIndex; 11263 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 11264 for (SDValue ArgVal : ArgVals) 11265 Chains.push_back(ArgVal.getValue(1)); 11266 11267 // Avoid emitting code for the store implementing the copy. 11268 const StoreInst *SI = ArgCopyIter->second.second; 11269 ElidedArgCopyInstrs.insert(SI); 11270 11271 // Check for uses of the argument again so that we can avoid exporting ArgVal 11272 // if it is't used by anything other than the store. 11273 for (const Value *U : Arg.users()) { 11274 if (U != SI) { 11275 ArgHasUses = true; 11276 break; 11277 } 11278 } 11279 } 11280 11281 void SelectionDAGISel::LowerArguments(const Function &F) { 11282 SelectionDAG &DAG = SDB->DAG; 11283 SDLoc dl = SDB->getCurSDLoc(); 11284 const DataLayout &DL = DAG.getDataLayout(); 11285 SmallVector<ISD::InputArg, 16> Ins; 11286 11287 // In Naked functions we aren't going to save any registers. 11288 if (F.hasFnAttribute(Attribute::Naked)) 11289 return; 11290 11291 if (!FuncInfo->CanLowerReturn) { 11292 // Put in an sret pointer parameter before all the other parameters. 11293 SmallVector<EVT, 1> ValueVTs; 11294 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11295 PointerType::get(F.getContext(), 11296 DAG.getDataLayout().getAllocaAddrSpace()), 11297 ValueVTs); 11298 11299 // NOTE: Assuming that a pointer will never break down to more than one VT 11300 // or one register. 11301 ISD::ArgFlagsTy Flags; 11302 Flags.setSRet(); 11303 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 11304 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 11305 ISD::InputArg::NoArgIndex, 0); 11306 Ins.push_back(RetArg); 11307 } 11308 11309 // Look for stores of arguments to static allocas. Mark such arguments with a 11310 // flag to ask the target to give us the memory location of that argument if 11311 // available. 11312 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11313 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11314 ArgCopyElisionCandidates); 11315 11316 // Set up the incoming argument description vector. 11317 for (const Argument &Arg : F.args()) { 11318 unsigned ArgNo = Arg.getArgNo(); 11319 SmallVector<EVT, 4> ValueVTs; 11320 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11321 bool isArgValueUsed = !Arg.use_empty(); 11322 unsigned PartBase = 0; 11323 Type *FinalType = Arg.getType(); 11324 if (Arg.hasAttribute(Attribute::ByVal)) 11325 FinalType = Arg.getParamByValType(); 11326 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11327 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11328 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11329 Value != NumValues; ++Value) { 11330 EVT VT = ValueVTs[Value]; 11331 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11332 ISD::ArgFlagsTy Flags; 11333 11334 11335 if (Arg.getType()->isPointerTy()) { 11336 Flags.setPointer(); 11337 Flags.setPointerAddrSpace( 11338 cast<PointerType>(Arg.getType())->getAddressSpace()); 11339 } 11340 if (Arg.hasAttribute(Attribute::ZExt)) 11341 Flags.setZExt(); 11342 if (Arg.hasAttribute(Attribute::SExt)) 11343 Flags.setSExt(); 11344 if (Arg.hasAttribute(Attribute::InReg)) { 11345 // If we are using vectorcall calling convention, a structure that is 11346 // passed InReg - is surely an HVA 11347 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11348 isa<StructType>(Arg.getType())) { 11349 // The first value of a structure is marked 11350 if (0 == Value) 11351 Flags.setHvaStart(); 11352 Flags.setHva(); 11353 } 11354 // Set InReg Flag 11355 Flags.setInReg(); 11356 } 11357 if (Arg.hasAttribute(Attribute::StructRet)) 11358 Flags.setSRet(); 11359 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11360 Flags.setSwiftSelf(); 11361 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11362 Flags.setSwiftAsync(); 11363 if (Arg.hasAttribute(Attribute::SwiftError)) 11364 Flags.setSwiftError(); 11365 if (Arg.hasAttribute(Attribute::ByVal)) 11366 Flags.setByVal(); 11367 if (Arg.hasAttribute(Attribute::ByRef)) 11368 Flags.setByRef(); 11369 if (Arg.hasAttribute(Attribute::InAlloca)) { 11370 Flags.setInAlloca(); 11371 // Set the byval flag for CCAssignFn callbacks that don't know about 11372 // inalloca. This way we can know how many bytes we should've allocated 11373 // and how many bytes a callee cleanup function will pop. If we port 11374 // inalloca to more targets, we'll have to add custom inalloca handling 11375 // in the various CC lowering callbacks. 11376 Flags.setByVal(); 11377 } 11378 if (Arg.hasAttribute(Attribute::Preallocated)) { 11379 Flags.setPreallocated(); 11380 // Set the byval flag for CCAssignFn callbacks that don't know about 11381 // preallocated. This way we can know how many bytes we should've 11382 // allocated and how many bytes a callee cleanup function will pop. If 11383 // we port preallocated to more targets, we'll have to add custom 11384 // preallocated handling in the various CC lowering callbacks. 11385 Flags.setByVal(); 11386 } 11387 11388 // Certain targets (such as MIPS), may have a different ABI alignment 11389 // for a type depending on the context. Give the target a chance to 11390 // specify the alignment it wants. 11391 const Align OriginalAlignment( 11392 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11393 Flags.setOrigAlign(OriginalAlignment); 11394 11395 Align MemAlign; 11396 Type *ArgMemTy = nullptr; 11397 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11398 Flags.isByRef()) { 11399 if (!ArgMemTy) 11400 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11401 11402 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11403 11404 // For in-memory arguments, size and alignment should be passed from FE. 11405 // BE will guess if this info is not there but there are cases it cannot 11406 // get right. 11407 if (auto ParamAlign = Arg.getParamStackAlign()) 11408 MemAlign = *ParamAlign; 11409 else if ((ParamAlign = Arg.getParamAlign())) 11410 MemAlign = *ParamAlign; 11411 else 11412 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11413 if (Flags.isByRef()) 11414 Flags.setByRefSize(MemSize); 11415 else 11416 Flags.setByValSize(MemSize); 11417 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11418 MemAlign = *ParamAlign; 11419 } else { 11420 MemAlign = OriginalAlignment; 11421 } 11422 Flags.setMemAlign(MemAlign); 11423 11424 if (Arg.hasAttribute(Attribute::Nest)) 11425 Flags.setNest(); 11426 if (NeedsRegBlock) 11427 Flags.setInConsecutiveRegs(); 11428 if (ArgCopyElisionCandidates.count(&Arg)) 11429 Flags.setCopyElisionCandidate(); 11430 if (Arg.hasAttribute(Attribute::Returned)) 11431 Flags.setReturned(); 11432 11433 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11434 *CurDAG->getContext(), F.getCallingConv(), VT); 11435 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11436 *CurDAG->getContext(), F.getCallingConv(), VT); 11437 for (unsigned i = 0; i != NumRegs; ++i) { 11438 // For scalable vectors, use the minimum size; individual targets 11439 // are responsible for handling scalable vector arguments and 11440 // return values. 11441 ISD::InputArg MyFlags( 11442 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11443 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11444 if (NumRegs > 1 && i == 0) 11445 MyFlags.Flags.setSplit(); 11446 // if it isn't first piece, alignment must be 1 11447 else if (i > 0) { 11448 MyFlags.Flags.setOrigAlign(Align(1)); 11449 if (i == NumRegs - 1) 11450 MyFlags.Flags.setSplitEnd(); 11451 } 11452 Ins.push_back(MyFlags); 11453 } 11454 if (NeedsRegBlock && Value == NumValues - 1) 11455 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11456 PartBase += VT.getStoreSize().getKnownMinValue(); 11457 } 11458 } 11459 11460 // Call the target to set up the argument values. 11461 SmallVector<SDValue, 8> InVals; 11462 SDValue NewRoot = TLI->LowerFormalArguments( 11463 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11464 11465 // Verify that the target's LowerFormalArguments behaved as expected. 11466 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11467 "LowerFormalArguments didn't return a valid chain!"); 11468 assert(InVals.size() == Ins.size() && 11469 "LowerFormalArguments didn't emit the correct number of values!"); 11470 LLVM_DEBUG({ 11471 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11472 assert(InVals[i].getNode() && 11473 "LowerFormalArguments emitted a null value!"); 11474 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11475 "LowerFormalArguments emitted a value with the wrong type!"); 11476 } 11477 }); 11478 11479 // Update the DAG with the new chain value resulting from argument lowering. 11480 DAG.setRoot(NewRoot); 11481 11482 // Set up the argument values. 11483 unsigned i = 0; 11484 if (!FuncInfo->CanLowerReturn) { 11485 // Create a virtual register for the sret pointer, and put in a copy 11486 // from the sret argument into it. 11487 SmallVector<EVT, 1> ValueVTs; 11488 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11489 PointerType::get(F.getContext(), 11490 DAG.getDataLayout().getAllocaAddrSpace()), 11491 ValueVTs); 11492 MVT VT = ValueVTs[0].getSimpleVT(); 11493 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11494 std::optional<ISD::NodeType> AssertOp; 11495 SDValue ArgValue = 11496 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11497 F.getCallingConv(), AssertOp); 11498 11499 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11500 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11501 Register SRetReg = 11502 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11503 FuncInfo->DemoteRegister = SRetReg; 11504 NewRoot = 11505 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11506 DAG.setRoot(NewRoot); 11507 11508 // i indexes lowered arguments. Bump it past the hidden sret argument. 11509 ++i; 11510 } 11511 11512 SmallVector<SDValue, 4> Chains; 11513 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11514 for (const Argument &Arg : F.args()) { 11515 SmallVector<SDValue, 4> ArgValues; 11516 SmallVector<EVT, 4> ValueVTs; 11517 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11518 unsigned NumValues = ValueVTs.size(); 11519 if (NumValues == 0) 11520 continue; 11521 11522 bool ArgHasUses = !Arg.use_empty(); 11523 11524 // Elide the copying store if the target loaded this argument from a 11525 // suitable fixed stack object. 11526 if (Ins[i].Flags.isCopyElisionCandidate()) { 11527 unsigned NumParts = 0; 11528 for (EVT VT : ValueVTs) 11529 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11530 F.getCallingConv(), VT); 11531 11532 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11533 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11534 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11535 } 11536 11537 // If this argument is unused then remember its value. It is used to generate 11538 // debugging information. 11539 bool isSwiftErrorArg = 11540 TLI->supportSwiftError() && 11541 Arg.hasAttribute(Attribute::SwiftError); 11542 if (!ArgHasUses && !isSwiftErrorArg) { 11543 SDB->setUnusedArgValue(&Arg, InVals[i]); 11544 11545 // Also remember any frame index for use in FastISel. 11546 if (FrameIndexSDNode *FI = 11547 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11548 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11549 } 11550 11551 for (unsigned Val = 0; Val != NumValues; ++Val) { 11552 EVT VT = ValueVTs[Val]; 11553 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11554 F.getCallingConv(), VT); 11555 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11556 *CurDAG->getContext(), F.getCallingConv(), VT); 11557 11558 // Even an apparent 'unused' swifterror argument needs to be returned. So 11559 // we do generate a copy for it that can be used on return from the 11560 // function. 11561 if (ArgHasUses || isSwiftErrorArg) { 11562 std::optional<ISD::NodeType> AssertOp; 11563 if (Arg.hasAttribute(Attribute::SExt)) 11564 AssertOp = ISD::AssertSext; 11565 else if (Arg.hasAttribute(Attribute::ZExt)) 11566 AssertOp = ISD::AssertZext; 11567 11568 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11569 PartVT, VT, nullptr, NewRoot, 11570 F.getCallingConv(), AssertOp)); 11571 } 11572 11573 i += NumParts; 11574 } 11575 11576 // We don't need to do anything else for unused arguments. 11577 if (ArgValues.empty()) 11578 continue; 11579 11580 // Note down frame index. 11581 if (FrameIndexSDNode *FI = 11582 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11583 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11584 11585 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11586 SDB->getCurSDLoc()); 11587 11588 SDB->setValue(&Arg, Res); 11589 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11590 // We want to associate the argument with the frame index, among 11591 // involved operands, that correspond to the lowest address. The 11592 // getCopyFromParts function, called earlier, is swapping the order of 11593 // the operands to BUILD_PAIR depending on endianness. The result of 11594 // that swapping is that the least significant bits of the argument will 11595 // be in the first operand of the BUILD_PAIR node, and the most 11596 // significant bits will be in the second operand. 11597 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11598 if (LoadSDNode *LNode = 11599 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11600 if (FrameIndexSDNode *FI = 11601 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11602 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11603 } 11604 11605 // Analyses past this point are naive and don't expect an assertion. 11606 if (Res.getOpcode() == ISD::AssertZext) 11607 Res = Res.getOperand(0); 11608 11609 // Update the SwiftErrorVRegDefMap. 11610 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11611 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11612 if (Register::isVirtualRegister(Reg)) 11613 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11614 Reg); 11615 } 11616 11617 // If this argument is live outside of the entry block, insert a copy from 11618 // wherever we got it to the vreg that other BB's will reference it as. 11619 if (Res.getOpcode() == ISD::CopyFromReg) { 11620 // If we can, though, try to skip creating an unnecessary vreg. 11621 // FIXME: This isn't very clean... it would be nice to make this more 11622 // general. 11623 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11624 if (Register::isVirtualRegister(Reg)) { 11625 FuncInfo->ValueMap[&Arg] = Reg; 11626 continue; 11627 } 11628 } 11629 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11630 FuncInfo->InitializeRegForValue(&Arg); 11631 SDB->CopyToExportRegsIfNeeded(&Arg); 11632 } 11633 } 11634 11635 if (!Chains.empty()) { 11636 Chains.push_back(NewRoot); 11637 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11638 } 11639 11640 DAG.setRoot(NewRoot); 11641 11642 assert(i == InVals.size() && "Argument register count mismatch!"); 11643 11644 // If any argument copy elisions occurred and we have debug info, update the 11645 // stale frame indices used in the dbg.declare variable info table. 11646 if (!ArgCopyElisionFrameIndexMap.empty()) { 11647 for (MachineFunction::VariableDbgInfo &VI : 11648 MF->getInStackSlotVariableDbgInfo()) { 11649 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11650 if (I != ArgCopyElisionFrameIndexMap.end()) 11651 VI.updateStackSlot(I->second); 11652 } 11653 } 11654 11655 // Finally, if the target has anything special to do, allow it to do so. 11656 emitFunctionEntryCode(); 11657 } 11658 11659 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11660 /// ensure constants are generated when needed. Remember the virtual registers 11661 /// that need to be added to the Machine PHI nodes as input. We cannot just 11662 /// directly add them, because expansion might result in multiple MBB's for one 11663 /// BB. As such, the start of the BB might correspond to a different MBB than 11664 /// the end. 11665 void 11666 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11667 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11668 11669 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11670 11671 // Check PHI nodes in successors that expect a value to be available from this 11672 // block. 11673 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11674 if (!isa<PHINode>(SuccBB->begin())) continue; 11675 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11676 11677 // If this terminator has multiple identical successors (common for 11678 // switches), only handle each succ once. 11679 if (!SuccsHandled.insert(SuccMBB).second) 11680 continue; 11681 11682 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11683 11684 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11685 // nodes and Machine PHI nodes, but the incoming operands have not been 11686 // emitted yet. 11687 for (const PHINode &PN : SuccBB->phis()) { 11688 // Ignore dead phi's. 11689 if (PN.use_empty()) 11690 continue; 11691 11692 // Skip empty types 11693 if (PN.getType()->isEmptyTy()) 11694 continue; 11695 11696 unsigned Reg; 11697 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11698 11699 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11700 unsigned &RegOut = ConstantsOut[C]; 11701 if (RegOut == 0) { 11702 RegOut = FuncInfo.CreateRegs(C); 11703 // We need to zero/sign extend ConstantInt phi operands to match 11704 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11705 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11706 if (auto *CI = dyn_cast<ConstantInt>(C)) 11707 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11708 : ISD::ZERO_EXTEND; 11709 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11710 } 11711 Reg = RegOut; 11712 } else { 11713 DenseMap<const Value *, Register>::iterator I = 11714 FuncInfo.ValueMap.find(PHIOp); 11715 if (I != FuncInfo.ValueMap.end()) 11716 Reg = I->second; 11717 else { 11718 assert(isa<AllocaInst>(PHIOp) && 11719 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11720 "Didn't codegen value into a register!??"); 11721 Reg = FuncInfo.CreateRegs(PHIOp); 11722 CopyValueToVirtualRegister(PHIOp, Reg); 11723 } 11724 } 11725 11726 // Remember that this register needs to added to the machine PHI node as 11727 // the input for this MBB. 11728 SmallVector<EVT, 4> ValueVTs; 11729 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11730 for (EVT VT : ValueVTs) { 11731 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11732 for (unsigned i = 0; i != NumRegisters; ++i) 11733 FuncInfo.PHINodesToUpdate.push_back( 11734 std::make_pair(&*MBBI++, Reg + i)); 11735 Reg += NumRegisters; 11736 } 11737 } 11738 } 11739 11740 ConstantsOut.clear(); 11741 } 11742 11743 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11744 MachineFunction::iterator I(MBB); 11745 if (++I == FuncInfo.MF->end()) 11746 return nullptr; 11747 return &*I; 11748 } 11749 11750 /// During lowering new call nodes can be created (such as memset, etc.). 11751 /// Those will become new roots of the current DAG, but complications arise 11752 /// when they are tail calls. In such cases, the call lowering will update 11753 /// the root, but the builder still needs to know that a tail call has been 11754 /// lowered in order to avoid generating an additional return. 11755 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11756 // If the node is null, we do have a tail call. 11757 if (MaybeTC.getNode() != nullptr) 11758 DAG.setRoot(MaybeTC); 11759 else 11760 HasTailCall = true; 11761 } 11762 11763 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11764 MachineBasicBlock *SwitchMBB, 11765 MachineBasicBlock *DefaultMBB) { 11766 MachineFunction *CurMF = FuncInfo.MF; 11767 MachineBasicBlock *NextMBB = nullptr; 11768 MachineFunction::iterator BBI(W.MBB); 11769 if (++BBI != FuncInfo.MF->end()) 11770 NextMBB = &*BBI; 11771 11772 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11773 11774 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11775 11776 if (Size == 2 && W.MBB == SwitchMBB) { 11777 // If any two of the cases has the same destination, and if one value 11778 // is the same as the other, but has one bit unset that the other has set, 11779 // use bit manipulation to do two compares at once. For example: 11780 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11781 // TODO: This could be extended to merge any 2 cases in switches with 3 11782 // cases. 11783 // TODO: Handle cases where W.CaseBB != SwitchBB. 11784 CaseCluster &Small = *W.FirstCluster; 11785 CaseCluster &Big = *W.LastCluster; 11786 11787 if (Small.Low == Small.High && Big.Low == Big.High && 11788 Small.MBB == Big.MBB) { 11789 const APInt &SmallValue = Small.Low->getValue(); 11790 const APInt &BigValue = Big.Low->getValue(); 11791 11792 // Check that there is only one bit different. 11793 APInt CommonBit = BigValue ^ SmallValue; 11794 if (CommonBit.isPowerOf2()) { 11795 SDValue CondLHS = getValue(Cond); 11796 EVT VT = CondLHS.getValueType(); 11797 SDLoc DL = getCurSDLoc(); 11798 11799 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11800 DAG.getConstant(CommonBit, DL, VT)); 11801 SDValue Cond = DAG.getSetCC( 11802 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11803 ISD::SETEQ); 11804 11805 // Update successor info. 11806 // Both Small and Big will jump to Small.BB, so we sum up the 11807 // probabilities. 11808 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11809 if (BPI) 11810 addSuccessorWithProb( 11811 SwitchMBB, DefaultMBB, 11812 // The default destination is the first successor in IR. 11813 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11814 else 11815 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11816 11817 // Insert the true branch. 11818 SDValue BrCond = 11819 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11820 DAG.getBasicBlock(Small.MBB)); 11821 // Insert the false branch. 11822 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11823 DAG.getBasicBlock(DefaultMBB)); 11824 11825 DAG.setRoot(BrCond); 11826 return; 11827 } 11828 } 11829 } 11830 11831 if (TM.getOptLevel() != CodeGenOptLevel::None) { 11832 // Here, we order cases by probability so the most likely case will be 11833 // checked first. However, two clusters can have the same probability in 11834 // which case their relative ordering is non-deterministic. So we use Low 11835 // as a tie-breaker as clusters are guaranteed to never overlap. 11836 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11837 [](const CaseCluster &a, const CaseCluster &b) { 11838 return a.Prob != b.Prob ? 11839 a.Prob > b.Prob : 11840 a.Low->getValue().slt(b.Low->getValue()); 11841 }); 11842 11843 // Rearrange the case blocks so that the last one falls through if possible 11844 // without changing the order of probabilities. 11845 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11846 --I; 11847 if (I->Prob > W.LastCluster->Prob) 11848 break; 11849 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11850 std::swap(*I, *W.LastCluster); 11851 break; 11852 } 11853 } 11854 } 11855 11856 // Compute total probability. 11857 BranchProbability DefaultProb = W.DefaultProb; 11858 BranchProbability UnhandledProbs = DefaultProb; 11859 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11860 UnhandledProbs += I->Prob; 11861 11862 MachineBasicBlock *CurMBB = W.MBB; 11863 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11864 bool FallthroughUnreachable = false; 11865 MachineBasicBlock *Fallthrough; 11866 if (I == W.LastCluster) { 11867 // For the last cluster, fall through to the default destination. 11868 Fallthrough = DefaultMBB; 11869 FallthroughUnreachable = isa<UnreachableInst>( 11870 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11871 } else { 11872 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11873 CurMF->insert(BBI, Fallthrough); 11874 // Put Cond in a virtual register to make it available from the new blocks. 11875 ExportFromCurrentBlock(Cond); 11876 } 11877 UnhandledProbs -= I->Prob; 11878 11879 switch (I->Kind) { 11880 case CC_JumpTable: { 11881 // FIXME: Optimize away range check based on pivot comparisons. 11882 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11883 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11884 11885 // The jump block hasn't been inserted yet; insert it here. 11886 MachineBasicBlock *JumpMBB = JT->MBB; 11887 CurMF->insert(BBI, JumpMBB); 11888 11889 auto JumpProb = I->Prob; 11890 auto FallthroughProb = UnhandledProbs; 11891 11892 // If the default statement is a target of the jump table, we evenly 11893 // distribute the default probability to successors of CurMBB. Also 11894 // update the probability on the edge from JumpMBB to Fallthrough. 11895 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11896 SE = JumpMBB->succ_end(); 11897 SI != SE; ++SI) { 11898 if (*SI == DefaultMBB) { 11899 JumpProb += DefaultProb / 2; 11900 FallthroughProb -= DefaultProb / 2; 11901 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11902 JumpMBB->normalizeSuccProbs(); 11903 break; 11904 } 11905 } 11906 11907 // If the default clause is unreachable, propagate that knowledge into 11908 // JTH->FallthroughUnreachable which will use it to suppress the range 11909 // check. 11910 // 11911 // However, don't do this if we're doing branch target enforcement, 11912 // because a table branch _without_ a range check can be a tempting JOP 11913 // gadget - out-of-bounds inputs that are impossible in correct 11914 // execution become possible again if an attacker can influence the 11915 // control flow. So if an attacker doesn't already have a BTI bypass 11916 // available, we don't want them to be able to get one out of this 11917 // table branch. 11918 if (FallthroughUnreachable) { 11919 Function &CurFunc = CurMF->getFunction(); 11920 bool HasBranchTargetEnforcement = false; 11921 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11922 HasBranchTargetEnforcement = 11923 CurFunc.getFnAttribute("branch-target-enforcement") 11924 .getValueAsBool(); 11925 } else { 11926 HasBranchTargetEnforcement = 11927 CurMF->getMMI().getModule()->getModuleFlag( 11928 "branch-target-enforcement"); 11929 } 11930 if (!HasBranchTargetEnforcement) 11931 JTH->FallthroughUnreachable = true; 11932 } 11933 11934 if (!JTH->FallthroughUnreachable) 11935 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11936 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11937 CurMBB->normalizeSuccProbs(); 11938 11939 // The jump table header will be inserted in our current block, do the 11940 // range check, and fall through to our fallthrough block. 11941 JTH->HeaderBB = CurMBB; 11942 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11943 11944 // If we're in the right place, emit the jump table header right now. 11945 if (CurMBB == SwitchMBB) { 11946 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11947 JTH->Emitted = true; 11948 } 11949 break; 11950 } 11951 case CC_BitTests: { 11952 // FIXME: Optimize away range check based on pivot comparisons. 11953 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11954 11955 // The bit test blocks haven't been inserted yet; insert them here. 11956 for (BitTestCase &BTC : BTB->Cases) 11957 CurMF->insert(BBI, BTC.ThisBB); 11958 11959 // Fill in fields of the BitTestBlock. 11960 BTB->Parent = CurMBB; 11961 BTB->Default = Fallthrough; 11962 11963 BTB->DefaultProb = UnhandledProbs; 11964 // If the cases in bit test don't form a contiguous range, we evenly 11965 // distribute the probability on the edge to Fallthrough to two 11966 // successors of CurMBB. 11967 if (!BTB->ContiguousRange) { 11968 BTB->Prob += DefaultProb / 2; 11969 BTB->DefaultProb -= DefaultProb / 2; 11970 } 11971 11972 if (FallthroughUnreachable) 11973 BTB->FallthroughUnreachable = true; 11974 11975 // If we're in the right place, emit the bit test header right now. 11976 if (CurMBB == SwitchMBB) { 11977 visitBitTestHeader(*BTB, SwitchMBB); 11978 BTB->Emitted = true; 11979 } 11980 break; 11981 } 11982 case CC_Range: { 11983 const Value *RHS, *LHS, *MHS; 11984 ISD::CondCode CC; 11985 if (I->Low == I->High) { 11986 // Check Cond == I->Low. 11987 CC = ISD::SETEQ; 11988 LHS = Cond; 11989 RHS=I->Low; 11990 MHS = nullptr; 11991 } else { 11992 // Check I->Low <= Cond <= I->High. 11993 CC = ISD::SETLE; 11994 LHS = I->Low; 11995 MHS = Cond; 11996 RHS = I->High; 11997 } 11998 11999 // If Fallthrough is unreachable, fold away the comparison. 12000 if (FallthroughUnreachable) 12001 CC = ISD::SETTRUE; 12002 12003 // The false probability is the sum of all unhandled cases. 12004 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 12005 getCurSDLoc(), I->Prob, UnhandledProbs); 12006 12007 if (CurMBB == SwitchMBB) 12008 visitSwitchCase(CB, SwitchMBB); 12009 else 12010 SL->SwitchCases.push_back(CB); 12011 12012 break; 12013 } 12014 } 12015 CurMBB = Fallthrough; 12016 } 12017 } 12018 12019 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 12020 const SwitchWorkListItem &W, 12021 Value *Cond, 12022 MachineBasicBlock *SwitchMBB) { 12023 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 12024 "Clusters not sorted?"); 12025 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 12026 12027 auto [LastLeft, FirstRight, LeftProb, RightProb] = 12028 SL->computeSplitWorkItemInfo(W); 12029 12030 // Use the first element on the right as pivot since we will make less-than 12031 // comparisons against it. 12032 CaseClusterIt PivotCluster = FirstRight; 12033 assert(PivotCluster > W.FirstCluster); 12034 assert(PivotCluster <= W.LastCluster); 12035 12036 CaseClusterIt FirstLeft = W.FirstCluster; 12037 CaseClusterIt LastRight = W.LastCluster; 12038 12039 const ConstantInt *Pivot = PivotCluster->Low; 12040 12041 // New blocks will be inserted immediately after the current one. 12042 MachineFunction::iterator BBI(W.MBB); 12043 ++BBI; 12044 12045 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 12046 // we can branch to its destination directly if it's squeezed exactly in 12047 // between the known lower bound and Pivot - 1. 12048 MachineBasicBlock *LeftMBB; 12049 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 12050 FirstLeft->Low == W.GE && 12051 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 12052 LeftMBB = FirstLeft->MBB; 12053 } else { 12054 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12055 FuncInfo.MF->insert(BBI, LeftMBB); 12056 WorkList.push_back( 12057 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 12058 // Put Cond in a virtual register to make it available from the new blocks. 12059 ExportFromCurrentBlock(Cond); 12060 } 12061 12062 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 12063 // single cluster, RHS.Low == Pivot, and we can branch to its destination 12064 // directly if RHS.High equals the current upper bound. 12065 MachineBasicBlock *RightMBB; 12066 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 12067 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 12068 RightMBB = FirstRight->MBB; 12069 } else { 12070 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12071 FuncInfo.MF->insert(BBI, RightMBB); 12072 WorkList.push_back( 12073 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 12074 // Put Cond in a virtual register to make it available from the new blocks. 12075 ExportFromCurrentBlock(Cond); 12076 } 12077 12078 // Create the CaseBlock record that will be used to lower the branch. 12079 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 12080 getCurSDLoc(), LeftProb, RightProb); 12081 12082 if (W.MBB == SwitchMBB) 12083 visitSwitchCase(CB, SwitchMBB); 12084 else 12085 SL->SwitchCases.push_back(CB); 12086 } 12087 12088 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 12089 // from the swith statement. 12090 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 12091 BranchProbability PeeledCaseProb) { 12092 if (PeeledCaseProb == BranchProbability::getOne()) 12093 return BranchProbability::getZero(); 12094 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 12095 12096 uint32_t Numerator = CaseProb.getNumerator(); 12097 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 12098 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 12099 } 12100 12101 // Try to peel the top probability case if it exceeds the threshold. 12102 // Return current MachineBasicBlock for the switch statement if the peeling 12103 // does not occur. 12104 // If the peeling is performed, return the newly created MachineBasicBlock 12105 // for the peeled switch statement. Also update Clusters to remove the peeled 12106 // case. PeeledCaseProb is the BranchProbability for the peeled case. 12107 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 12108 const SwitchInst &SI, CaseClusterVector &Clusters, 12109 BranchProbability &PeeledCaseProb) { 12110 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12111 // Don't perform if there is only one cluster or optimizing for size. 12112 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 12113 TM.getOptLevel() == CodeGenOptLevel::None || 12114 SwitchMBB->getParent()->getFunction().hasMinSize()) 12115 return SwitchMBB; 12116 12117 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 12118 unsigned PeeledCaseIndex = 0; 12119 bool SwitchPeeled = false; 12120 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 12121 CaseCluster &CC = Clusters[Index]; 12122 if (CC.Prob < TopCaseProb) 12123 continue; 12124 TopCaseProb = CC.Prob; 12125 PeeledCaseIndex = Index; 12126 SwitchPeeled = true; 12127 } 12128 if (!SwitchPeeled) 12129 return SwitchMBB; 12130 12131 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 12132 << TopCaseProb << "\n"); 12133 12134 // Record the MBB for the peeled switch statement. 12135 MachineFunction::iterator BBI(SwitchMBB); 12136 ++BBI; 12137 MachineBasicBlock *PeeledSwitchMBB = 12138 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 12139 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 12140 12141 ExportFromCurrentBlock(SI.getCondition()); 12142 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 12143 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 12144 nullptr, nullptr, TopCaseProb.getCompl()}; 12145 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 12146 12147 Clusters.erase(PeeledCaseIt); 12148 for (CaseCluster &CC : Clusters) { 12149 LLVM_DEBUG( 12150 dbgs() << "Scale the probablity for one cluster, before scaling: " 12151 << CC.Prob << "\n"); 12152 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 12153 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 12154 } 12155 PeeledCaseProb = TopCaseProb; 12156 return PeeledSwitchMBB; 12157 } 12158 12159 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 12160 // Extract cases from the switch. 12161 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12162 CaseClusterVector Clusters; 12163 Clusters.reserve(SI.getNumCases()); 12164 for (auto I : SI.cases()) { 12165 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 12166 const ConstantInt *CaseVal = I.getCaseValue(); 12167 BranchProbability Prob = 12168 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 12169 : BranchProbability(1, SI.getNumCases() + 1); 12170 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 12171 } 12172 12173 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 12174 12175 // Cluster adjacent cases with the same destination. We do this at all 12176 // optimization levels because it's cheap to do and will make codegen faster 12177 // if there are many clusters. 12178 sortAndRangeify(Clusters); 12179 12180 // The branch probablity of the peeled case. 12181 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 12182 MachineBasicBlock *PeeledSwitchMBB = 12183 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 12184 12185 // If there is only the default destination, jump there directly. 12186 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12187 if (Clusters.empty()) { 12188 assert(PeeledSwitchMBB == SwitchMBB); 12189 SwitchMBB->addSuccessor(DefaultMBB); 12190 if (DefaultMBB != NextBlock(SwitchMBB)) { 12191 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 12192 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 12193 } 12194 return; 12195 } 12196 12197 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 12198 DAG.getBFI()); 12199 SL->findBitTestClusters(Clusters, &SI); 12200 12201 LLVM_DEBUG({ 12202 dbgs() << "Case clusters: "; 12203 for (const CaseCluster &C : Clusters) { 12204 if (C.Kind == CC_JumpTable) 12205 dbgs() << "JT:"; 12206 if (C.Kind == CC_BitTests) 12207 dbgs() << "BT:"; 12208 12209 C.Low->getValue().print(dbgs(), true); 12210 if (C.Low != C.High) { 12211 dbgs() << '-'; 12212 C.High->getValue().print(dbgs(), true); 12213 } 12214 dbgs() << ' '; 12215 } 12216 dbgs() << '\n'; 12217 }); 12218 12219 assert(!Clusters.empty()); 12220 SwitchWorkList WorkList; 12221 CaseClusterIt First = Clusters.begin(); 12222 CaseClusterIt Last = Clusters.end() - 1; 12223 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 12224 // Scale the branchprobability for DefaultMBB if the peel occurs and 12225 // DefaultMBB is not replaced. 12226 if (PeeledCaseProb != BranchProbability::getZero() && 12227 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 12228 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 12229 WorkList.push_back( 12230 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 12231 12232 while (!WorkList.empty()) { 12233 SwitchWorkListItem W = WorkList.pop_back_val(); 12234 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 12235 12236 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 12237 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 12238 // For optimized builds, lower large range as a balanced binary tree. 12239 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 12240 continue; 12241 } 12242 12243 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 12244 } 12245 } 12246 12247 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 12248 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12249 auto DL = getCurSDLoc(); 12250 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12251 setValue(&I, DAG.getStepVector(DL, ResultVT)); 12252 } 12253 12254 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 12255 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12256 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12257 12258 SDLoc DL = getCurSDLoc(); 12259 SDValue V = getValue(I.getOperand(0)); 12260 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 12261 12262 if (VT.isScalableVector()) { 12263 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 12264 return; 12265 } 12266 12267 // Use VECTOR_SHUFFLE for the fixed-length vector 12268 // to maintain existing behavior. 12269 SmallVector<int, 8> Mask; 12270 unsigned NumElts = VT.getVectorMinNumElements(); 12271 for (unsigned i = 0; i != NumElts; ++i) 12272 Mask.push_back(NumElts - 1 - i); 12273 12274 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 12275 } 12276 12277 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 12278 auto DL = getCurSDLoc(); 12279 SDValue InVec = getValue(I.getOperand(0)); 12280 EVT OutVT = 12281 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 12282 12283 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 12284 12285 // ISD Node needs the input vectors split into two equal parts 12286 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12287 DAG.getVectorIdxConstant(0, DL)); 12288 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12289 DAG.getVectorIdxConstant(OutNumElts, DL)); 12290 12291 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12292 // legalisation and combines. 12293 if (OutVT.isFixedLengthVector()) { 12294 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12295 createStrideMask(0, 2, OutNumElts)); 12296 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12297 createStrideMask(1, 2, OutNumElts)); 12298 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 12299 setValue(&I, Res); 12300 return; 12301 } 12302 12303 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12304 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12305 setValue(&I, Res); 12306 } 12307 12308 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12309 auto DL = getCurSDLoc(); 12310 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12311 SDValue InVec0 = getValue(I.getOperand(0)); 12312 SDValue InVec1 = getValue(I.getOperand(1)); 12313 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12314 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12315 12316 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12317 // legalisation and combines. 12318 if (OutVT.isFixedLengthVector()) { 12319 unsigned NumElts = InVT.getVectorMinNumElements(); 12320 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12321 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12322 createInterleaveMask(NumElts, 2))); 12323 return; 12324 } 12325 12326 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12327 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12328 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12329 Res.getValue(1)); 12330 setValue(&I, Res); 12331 } 12332 12333 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12334 SmallVector<EVT, 4> ValueVTs; 12335 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12336 ValueVTs); 12337 unsigned NumValues = ValueVTs.size(); 12338 if (NumValues == 0) return; 12339 12340 SmallVector<SDValue, 4> Values(NumValues); 12341 SDValue Op = getValue(I.getOperand(0)); 12342 12343 for (unsigned i = 0; i != NumValues; ++i) 12344 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12345 SDValue(Op.getNode(), Op.getResNo() + i)); 12346 12347 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12348 DAG.getVTList(ValueVTs), Values)); 12349 } 12350 12351 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12352 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12353 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12354 12355 SDLoc DL = getCurSDLoc(); 12356 SDValue V1 = getValue(I.getOperand(0)); 12357 SDValue V2 = getValue(I.getOperand(1)); 12358 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12359 12360 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12361 if (VT.isScalableVector()) { 12362 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12363 DAG.getVectorIdxConstant(Imm, DL))); 12364 return; 12365 } 12366 12367 unsigned NumElts = VT.getVectorNumElements(); 12368 12369 uint64_t Idx = (NumElts + Imm) % NumElts; 12370 12371 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12372 SmallVector<int, 8> Mask; 12373 for (unsigned i = 0; i < NumElts; ++i) 12374 Mask.push_back(Idx + i); 12375 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12376 } 12377 12378 // Consider the following MIR after SelectionDAG, which produces output in 12379 // phyregs in the first case or virtregs in the second case. 12380 // 12381 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12382 // %5:gr32 = COPY $ebx 12383 // %6:gr32 = COPY $edx 12384 // %1:gr32 = COPY %6:gr32 12385 // %0:gr32 = COPY %5:gr32 12386 // 12387 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12388 // %1:gr32 = COPY %6:gr32 12389 // %0:gr32 = COPY %5:gr32 12390 // 12391 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12392 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12393 // 12394 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12395 // to a single virtreg (such as %0). The remaining outputs monotonically 12396 // increase in virtreg number from there. If a callbr has no outputs, then it 12397 // should not have a corresponding callbr landingpad; in fact, the callbr 12398 // landingpad would not even be able to refer to such a callbr. 12399 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12400 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12401 // There is definitely at least one copy. 12402 assert(MI->getOpcode() == TargetOpcode::COPY && 12403 "start of copy chain MUST be COPY"); 12404 Reg = MI->getOperand(1).getReg(); 12405 MI = MRI.def_begin(Reg)->getParent(); 12406 // There may be an optional second copy. 12407 if (MI->getOpcode() == TargetOpcode::COPY) { 12408 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12409 Reg = MI->getOperand(1).getReg(); 12410 assert(Reg.isPhysical() && "expected COPY of physical register"); 12411 MI = MRI.def_begin(Reg)->getParent(); 12412 } 12413 // The start of the chain must be an INLINEASM_BR. 12414 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12415 "end of copy chain MUST be INLINEASM_BR"); 12416 return Reg; 12417 } 12418 12419 // We must do this walk rather than the simpler 12420 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12421 // otherwise we will end up with copies of virtregs only valid along direct 12422 // edges. 12423 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12424 SmallVector<EVT, 8> ResultVTs; 12425 SmallVector<SDValue, 8> ResultValues; 12426 const auto *CBR = 12427 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12428 12429 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12430 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12431 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12432 12433 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12434 SDValue Chain = DAG.getRoot(); 12435 12436 // Re-parse the asm constraints string. 12437 TargetLowering::AsmOperandInfoVector TargetConstraints = 12438 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12439 for (auto &T : TargetConstraints) { 12440 SDISelAsmOperandInfo OpInfo(T); 12441 if (OpInfo.Type != InlineAsm::isOutput) 12442 continue; 12443 12444 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12445 // individual constraint. 12446 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12447 12448 switch (OpInfo.ConstraintType) { 12449 case TargetLowering::C_Register: 12450 case TargetLowering::C_RegisterClass: { 12451 // Fill in OpInfo.AssignedRegs.Regs. 12452 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12453 12454 // getRegistersForValue may produce 1 to many registers based on whether 12455 // the OpInfo.ConstraintVT is legal on the target or not. 12456 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 12457 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12458 if (Register::isPhysicalRegister(OriginalDef)) 12459 FuncInfo.MBB->addLiveIn(OriginalDef); 12460 // Update the assigned registers to use the original defs. 12461 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 12462 } 12463 12464 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12465 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12466 ResultValues.push_back(V); 12467 ResultVTs.push_back(OpInfo.ConstraintVT); 12468 break; 12469 } 12470 case TargetLowering::C_Other: { 12471 SDValue Flag; 12472 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12473 OpInfo, DAG); 12474 ++InitialDef; 12475 ResultValues.push_back(V); 12476 ResultVTs.push_back(OpInfo.ConstraintVT); 12477 break; 12478 } 12479 default: 12480 break; 12481 } 12482 } 12483 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12484 DAG.getVTList(ResultVTs), ResultValues); 12485 setValue(&I, V); 12486 } 12487